]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_dbus.py
tests: Add testcases for interface global properties
[thirdparty/hostap.git] / tests / hwsim / test_dbus.py
1 # wpa_supplicant D-Bus interface tests
2 # Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import binascii
8 import logging
9 logger = logging.getLogger()
10 import subprocess
11 import time
12
13 try:
14 import gobject
15 import dbus
16 dbus_imported = True
17 except ImportError:
18 dbus_imported = False
19
20 import hostapd
21 from wpasupplicant import WpaSupplicant
22 from utils import HwsimSkip, alloc_fail, fail_test
23 from test_ap_tdls import connect_2sta_open
24
25 WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1"
26 WPAS_DBUS_PATH = "/fi/w1/wpa_supplicant1"
27 WPAS_DBUS_IFACE = "fi.w1.wpa_supplicant1.Interface"
28 WPAS_DBUS_IFACE_WPS = WPAS_DBUS_IFACE + ".WPS"
29 WPAS_DBUS_NETWORK = "fi.w1.wpa_supplicant1.Network"
30 WPAS_DBUS_BSS = "fi.w1.wpa_supplicant1.BSS"
31 WPAS_DBUS_IFACE_P2PDEVICE = WPAS_DBUS_IFACE + ".P2PDevice"
32 WPAS_DBUS_P2P_PEER = "fi.w1.wpa_supplicant1.Peer"
33 WPAS_DBUS_GROUP = "fi.w1.wpa_supplicant1.Group"
34 WPAS_DBUS_PERSISTENT_GROUP = "fi.w1.wpa_supplicant1.PersistentGroup"
35
36 def prepare_dbus(dev):
37 if not dbus_imported:
38 logger.info("No dbus module available")
39 raise HwsimSkip("No dbus module available")
40 try:
41 from dbus.mainloop.glib import DBusGMainLoop
42 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
43 bus = dbus.SystemBus()
44 wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH)
45 wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
46 path = wpas.GetInterface(dev.ifname)
47 if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
48 return (bus,wpas_obj,path,if_obj)
49 except Exception, e:
50 raise HwsimSkip("Could not connect to D-Bus: %s" % e)
51
52 class TestDbus(object):
53 def __init__(self, bus):
54 self.loop = gobject.MainLoop()
55 self.signals = []
56 self.bus = bus
57
58 def __exit__(self, type, value, traceback):
59 for s in self.signals:
60 s.remove()
61
62 def add_signal(self, handler, interface, name, byte_arrays=False):
63 s = self.bus.add_signal_receiver(handler, dbus_interface=interface,
64 signal_name=name,
65 byte_arrays=byte_arrays)
66 self.signals.append(s)
67
68 def timeout(self, *args):
69 logger.debug("timeout")
70 self.loop.quit()
71 return False
72
73 class alloc_fail_dbus(object):
74 def __init__(self, dev, count, funcs, operation="Operation",
75 expected="NoMemory"):
76 self._dev = dev
77 self._count = count
78 self._funcs = funcs
79 self._operation = operation
80 self._expected = expected
81 def __enter__(self):
82 cmd = "TEST_ALLOC_FAIL %d:%s" % (self._count, self._funcs)
83 if "OK" not in self._dev.request(cmd):
84 raise HwsimSkip("TEST_ALLOC_FAIL not supported")
85 def __exit__(self, type, value, traceback):
86 if type is None:
87 raise Exception("%s succeeded during out-of-memory" % self._operation)
88 if type == dbus.exceptions.DBusException and self._expected in str(value):
89 return True
90 if self._dev.request("GET_ALLOC_FAIL") != "0:%s" % self._funcs:
91 raise Exception("%s did not trigger allocation failure" % self._operation)
92 return False
93
94 def start_ap(ap, ssid="test-wps",
95 ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"):
96 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
97 "wpa_passphrase": "12345678", "wpa": "2",
98 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
99 "ap_pin": "12345670", "uuid": ap_uuid}
100 return hostapd.add_ap(ap['ifname'], params)
101
102 def test_dbus_getall(dev, apdev):
103 """D-Bus GetAll"""
104 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
105
106 props = wpas_obj.GetAll(WPAS_DBUS_SERVICE,
107 dbus_interface=dbus.PROPERTIES_IFACE)
108 logger.debug("GetAll(fi.w1.wpa.supplicant1, /fi/w1/wpa_supplicant1) ==> " + str(props))
109
110 props = if_obj.GetAll(WPAS_DBUS_IFACE,
111 dbus_interface=dbus.PROPERTIES_IFACE)
112 logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE, path, str(props)))
113
114 props = if_obj.GetAll(WPAS_DBUS_IFACE_WPS,
115 dbus_interface=dbus.PROPERTIES_IFACE)
116 logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE_WPS, path, str(props)))
117
118 res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
119 dbus_interface=dbus.PROPERTIES_IFACE)
120 if len(res) != 0:
121 raise Exception("Unexpected BSSs entry: " + str(res))
122
123 res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
124 dbus_interface=dbus.PROPERTIES_IFACE)
125 if len(res) != 0:
126 raise Exception("Unexpected Networks entry: " + str(res))
127
128 hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
129 bssid = apdev[0]['bssid']
130 dev[0].scan_for_bss(bssid, freq=2412)
131 id = dev[0].add_network()
132 dev[0].set_network(id, "disabled", "0")
133 dev[0].set_network_quoted(id, "ssid", "test")
134
135 res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
136 dbus_interface=dbus.PROPERTIES_IFACE)
137 if len(res) != 1:
138 raise Exception("Missing BSSs entry: " + str(res))
139 bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
140 props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
141 logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
142 bssid_str = ''
143 for item in props['BSSID']:
144 if len(bssid_str) > 0:
145 bssid_str += ':'
146 bssid_str += '%02x' % item
147 if bssid_str != bssid:
148 raise Exception("Unexpected BSSID in BSSs entry")
149
150 res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
151 dbus_interface=dbus.PROPERTIES_IFACE)
152 if len(res) != 1:
153 raise Exception("Missing Networks entry: " + str(res))
154 net_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
155 props = net_obj.GetAll(WPAS_DBUS_NETWORK,
156 dbus_interface=dbus.PROPERTIES_IFACE)
157 logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_NETWORK, res[0], str(props)))
158 ssid = props['Properties']['ssid']
159 if ssid != '"test"':
160 raise Exception("Unexpected SSID in network entry")
161
162 def dbus_get(dbus, wpas_obj, prop, expect=None, byte_arrays=False):
163 val = wpas_obj.Get(WPAS_DBUS_SERVICE, prop,
164 dbus_interface=dbus.PROPERTIES_IFACE,
165 byte_arrays=byte_arrays)
166 if expect is not None and val != expect:
167 raise Exception("Unexpected %s: %s (expected: %s)" %
168 (prop, str(val), str(expect)))
169 return val
170
171 def dbus_set(dbus, wpas_obj, prop, val):
172 wpas_obj.Set(WPAS_DBUS_SERVICE, prop, val,
173 dbus_interface=dbus.PROPERTIES_IFACE)
174
175 def test_dbus_properties(dev, apdev):
176 """D-Bus Get/Set fi.w1.wpa_supplicant1 properties"""
177 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
178
179 dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
180 dbus_set(dbus, wpas_obj, "DebugLevel", "debug")
181 dbus_get(dbus, wpas_obj, "DebugLevel", expect="debug")
182 for (val,err) in [ (3, "Error.Failed: wrong property type"),
183 ("foo", "Error.Failed: wrong debug level value") ]:
184 try:
185 dbus_set(dbus, wpas_obj, "DebugLevel", val)
186 raise Exception("Invalid DebugLevel value accepted: " + str(val))
187 except dbus.exceptions.DBusException, e:
188 if err not in str(e):
189 raise Exception("Unexpected error message: " + str(e))
190 dbus_set(dbus, wpas_obj, "DebugLevel", "msgdump")
191 dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
192
193 dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
194 dbus_set(dbus, wpas_obj, "DebugTimestamp", False)
195 dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=False)
196 try:
197 dbus_set(dbus, wpas_obj, "DebugTimestamp", "foo")
198 raise Exception("Invalid DebugTimestamp value accepted")
199 except dbus.exceptions.DBusException, e:
200 if "Error.Failed: wrong property type" not in str(e):
201 raise Exception("Unexpected error message: " + str(e))
202 dbus_set(dbus, wpas_obj, "DebugTimestamp", True)
203 dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
204
205 dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
206 dbus_set(dbus, wpas_obj, "DebugShowKeys", False)
207 dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=False)
208 try:
209 dbus_set(dbus, wpas_obj, "DebugShowKeys", "foo")
210 raise Exception("Invalid DebugShowKeys value accepted")
211 except dbus.exceptions.DBusException, e:
212 if "Error.Failed: wrong property type" not in str(e):
213 raise Exception("Unexpected error message: " + str(e))
214 dbus_set(dbus, wpas_obj, "DebugShowKeys", True)
215 dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
216
217 res = dbus_get(dbus, wpas_obj, "Interfaces")
218 if len(res) != 1:
219 raise Exception("Unexpected Interfaces value: " + str(res))
220
221 res = dbus_get(dbus, wpas_obj, "EapMethods")
222 if len(res) < 5 or "TTLS" not in res:
223 raise Exception("Unexpected EapMethods value: " + str(res))
224
225 res = dbus_get(dbus, wpas_obj, "Capabilities")
226 if len(res) < 2 or "p2p" not in res:
227 raise Exception("Unexpected Capabilities value: " + str(res))
228
229 dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
230 val = binascii.unhexlify("010006020304050608")
231 dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
232 res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
233 if val != res:
234 raise Exception("WFDIEs value changed")
235 try:
236 dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray('\x00'))
237 raise Exception("Invalid WFDIEs value accepted")
238 except dbus.exceptions.DBusException, e:
239 if "InvalidArgs" not in str(e):
240 raise Exception("Unexpected error message: " + str(e))
241 dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
242 dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
243 dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
244 res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
245 if len(res) != 0:
246 raise Exception("WFDIEs not cleared properly")
247
248 res = dbus_get(dbus, wpas_obj, "EapMethods")
249 try:
250 dbus_set(dbus, wpas_obj, "EapMethods", res)
251 raise Exception("Invalid Set accepted")
252 except dbus.exceptions.DBusException, e:
253 if "InvalidArgs: Property is read-only" not in str(e):
254 raise Exception("Unexpected error message: " + str(e))
255
256 try:
257 wpas_obj.SetFoo(WPAS_DBUS_SERVICE, "DebugShowKeys", True,
258 dbus_interface=dbus.PROPERTIES_IFACE)
259 raise Exception("Unknown method accepted")
260 except dbus.exceptions.DBusException, e:
261 if "UnknownMethod" not in str(e):
262 raise Exception("Unexpected error message: " + str(e))
263
264 try:
265 wpas_obj.Get("foo", "DebugShowKeys",
266 dbus_interface=dbus.PROPERTIES_IFACE)
267 raise Exception("Invalid Get accepted")
268 except dbus.exceptions.DBusException, e:
269 if "InvalidArgs: No such property" not in str(e):
270 raise Exception("Unexpected error message: " + str(e))
271
272 test_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH,
273 introspect=False)
274 try:
275 test_obj.Get(123, "DebugShowKeys",
276 dbus_interface=dbus.PROPERTIES_IFACE)
277 raise Exception("Invalid Get accepted")
278 except dbus.exceptions.DBusException, e:
279 if "InvalidArgs: Invalid arguments" not in str(e):
280 raise Exception("Unexpected error message: " + str(e))
281 try:
282 test_obj.Get(WPAS_DBUS_SERVICE, 123,
283 dbus_interface=dbus.PROPERTIES_IFACE)
284 raise Exception("Invalid Get accepted")
285 except dbus.exceptions.DBusException, e:
286 if "InvalidArgs: Invalid arguments" not in str(e):
287 raise Exception("Unexpected error message: " + str(e))
288
289 try:
290 wpas_obj.Set(WPAS_DBUS_SERVICE, "WFDIEs",
291 dbus.ByteArray('', variant_level=2),
292 dbus_interface=dbus.PROPERTIES_IFACE)
293 raise Exception("Invalid Set accepted")
294 except dbus.exceptions.DBusException, e:
295 if "InvalidArgs: invalid message format" not in str(e):
296 raise Exception("Unexpected error message: " + str(e))
297
298 def test_dbus_set_global_properties(dev, apdev):
299 """D-Bus Get/Set fi.w1.wpa_supplicant1 interface global properties"""
300 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
301
302 props = [ ('Okc', '0', '1'), ('ModelName', '', 'blahblahblah') ]
303
304 for p in props:
305 res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
306 dbus_interface=dbus.PROPERTIES_IFACE)
307 if res != p[1]:
308 raise Exception("Unexpected " + p[0] + " value: " + str(res))
309
310 if_obj.Set(WPAS_DBUS_IFACE, p[0], p[2],
311 dbus_interface=dbus.PROPERTIES_IFACE)
312
313 res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
314 dbus_interface=dbus.PROPERTIES_IFACE)
315 if res != p[2]:
316 raise Exception("Unexpected " + p[0] + " value after set: " + str(res))
317
318 def test_dbus_invalid_method(dev, apdev):
319 """D-Bus invalid method"""
320 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
321 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
322
323 try:
324 wps.Foo()
325 raise Exception("Unknown method accepted")
326 except dbus.exceptions.DBusException, e:
327 if "UnknownMethod" not in str(e):
328 raise Exception("Unexpected error message: " + str(e))
329
330 test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
331 test_wps = dbus.Interface(test_obj, WPAS_DBUS_IFACE_WPS)
332 try:
333 test_wps.Start(123)
334 raise Exception("WPS.Start with incorrect signature accepted")
335 except dbus.exceptions.DBusException, e:
336 if "InvalidArgs: Invalid arg" not in str(e):
337 raise Exception("Unexpected error message: " + str(e))
338
339 def test_dbus_get_set_wps(dev, apdev):
340 """D-Bus Get/Set for WPS properties"""
341 try:
342 _test_dbus_get_set_wps(dev, apdev)
343 finally:
344 dev[0].request("SET wps_cred_processing 0")
345 dev[0].request("SET config_methods display keypad virtual_display nfc_interface p2ps")
346
347 def _test_dbus_get_set_wps(dev, apdev):
348 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
349
350 if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
351 dbus_interface=dbus.PROPERTIES_IFACE)
352
353 val = "display keypad virtual_display nfc_interface"
354 dev[0].request("SET config_methods " + val)
355
356 config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
357 dbus_interface=dbus.PROPERTIES_IFACE)
358 if config != val:
359 raise Exception("Unexpected Get(ConfigMethods) result: " + config)
360
361 val2 = "push_button display"
362 if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
363 dbus_interface=dbus.PROPERTIES_IFACE)
364 config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
365 dbus_interface=dbus.PROPERTIES_IFACE)
366 if config != val2:
367 raise Exception("Unexpected Get(ConfigMethods) result after Set: " + config)
368
369 dev[0].request("SET config_methods " + val)
370
371 for i in range(3):
372 dev[0].request("SET wps_cred_processing " + str(i))
373 val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
374 dbus_interface=dbus.PROPERTIES_IFACE)
375 expected_val = False if i == 1 else True
376 if val != expected_val:
377 raise Exception("Unexpected Get(ProcessCredentials) result({}): {}".format(i, val))
378
379 class TestDbusGetSet(TestDbus):
380 def __init__(self, bus):
381 TestDbus.__init__(self, bus)
382 self.signal_received = False
383 self.signal_received_deprecated = False
384 self.sets_done = False
385
386 def __enter__(self):
387 gobject.timeout_add(1, self.run_sets)
388 gobject.timeout_add(1000, self.timeout)
389 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE_WPS,
390 "PropertiesChanged")
391 self.add_signal(self.propertiesChanged2, dbus.PROPERTIES_IFACE,
392 "PropertiesChanged")
393 self.loop.run()
394 return self
395
396 def propertiesChanged(self, properties):
397 logger.debug("PropertiesChanged: " + str(properties))
398 if properties.has_key("ProcessCredentials"):
399 self.signal_received_deprecated = True
400 if self.sets_done and self.signal_received:
401 self.loop.quit()
402
403 def propertiesChanged2(self, interface_name, changed_properties,
404 invalidated_properties):
405 logger.debug("propertiesChanged2: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
406 if interface_name != WPAS_DBUS_IFACE_WPS:
407 return
408 if changed_properties.has_key("ProcessCredentials"):
409 self.signal_received = True
410 if self.sets_done and self.signal_received_deprecated:
411 self.loop.quit()
412
413 def run_sets(self, *args):
414 logger.debug("run_sets")
415 if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
416 dbus.Boolean(1),
417 dbus_interface=dbus.PROPERTIES_IFACE)
418 if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
419 dbus_interface=dbus.PROPERTIES_IFACE) != True:
420 raise Exception("Unexpected Get(ProcessCredentials) result after Set");
421 if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
422 dbus.Boolean(0),
423 dbus_interface=dbus.PROPERTIES_IFACE)
424 if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
425 dbus_interface=dbus.PROPERTIES_IFACE) != False:
426 raise Exception("Unexpected Get(ProcessCredentials) result after Set");
427
428 self.dbus_sets_done = True
429 return False
430
431 def success(self):
432 return self.signal_received and self.signal_received_deprecated
433
434 with TestDbusGetSet(bus) as t:
435 if not t.success():
436 raise Exception("No signal received for ProcessCredentials change")
437
438 def test_dbus_wps_invalid(dev, apdev):
439 """D-Bus invaldi WPS operation"""
440 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
441 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
442
443 failures = [ {'Role': 'foo', 'Type': 'pbc'},
444 {'Role': 123, 'Type': 'pbc'},
445 {'Type': 'pbc'},
446 {'Role': 'enrollee'},
447 {'Role': 'registrar'},
448 {'Role': 'enrollee', 'Type': 123},
449 {'Role': 'enrollee', 'Type': 'foo'},
450 {'Role': 'enrollee', 'Type': 'pbc',
451 'Bssid': '02:33:44:55:66:77'},
452 {'Role': 'enrollee', 'Type': 'pin', 'Pin': 123},
453 {'Role': 'enrollee', 'Type': 'pbc',
454 'Bssid': dbus.ByteArray('12345')},
455 {'Role': 'enrollee', 'Type': 'pbc',
456 'P2PDeviceAddress': 12345},
457 {'Role': 'enrollee', 'Type': 'pbc',
458 'P2PDeviceAddress': dbus.ByteArray('12345')},
459 {'Role': 'enrollee', 'Type': 'pbc', 'Foo': 'bar'} ]
460 for args in failures:
461 try:
462 wps.Start(args)
463 raise Exception("Invalid WPS.Start() arguments accepted: " + str(args))
464 except dbus.exceptions.DBusException, e:
465 if not str(e).startswith("fi.w1.wpa_supplicant1.InvalidArgs"):
466 raise Exception("Unexpected error message: " + str(e))
467
468 def test_dbus_wps_oom(dev, apdev):
469 """D-Bus WPS operation (OOM)"""
470 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
471 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
472
473 with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_state", "Get"):
474 if_obj.Get(WPAS_DBUS_IFACE, "State",
475 dbus_interface=dbus.PROPERTIES_IFACE)
476
477 hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
478 bssid = apdev[0]['bssid']
479 dev[0].scan_for_bss(bssid, freq=2412)
480
481 for i in range(1, 3):
482 with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_bsss", "Get"):
483 if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
484 dbus_interface=dbus.PROPERTIES_IFACE)
485
486 res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
487 dbus_interface=dbus.PROPERTIES_IFACE)
488 bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
489 with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_bss_rates", "Get"):
490 bss_obj.Get(WPAS_DBUS_BSS, "Rates",
491 dbus_interface=dbus.PROPERTIES_IFACE)
492
493 id = dev[0].add_network()
494 dev[0].set_network(id, "disabled", "0")
495 dev[0].set_network_quoted(id, "ssid", "test")
496
497 for i in range(1, 3):
498 with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_networks", "Get"):
499 if_obj.Get(WPAS_DBUS_IFACE, "Networks",
500 dbus_interface=dbus.PROPERTIES_IFACE)
501
502 with alloc_fail_dbus(dev[0], 1, "wpas_dbus_getter_interfaces", "Get"):
503 dbus_get(dbus, wpas_obj, "Interfaces")
504
505 for i in range(1, 6):
506 with alloc_fail_dbus(dev[0], i, "=eap_get_names_as_string_array;wpas_dbus_getter_eap_methods", "Get"):
507 dbus_get(dbus, wpas_obj, "EapMethods")
508
509 with alloc_fail_dbus(dev[0], 1, "wpas_dbus_setter_config_methods", "Set",
510 expected="Error.Failed: Failed to set property"):
511 val2 = "push_button display"
512 if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
513 dbus_interface=dbus.PROPERTIES_IFACE)
514
515 with alloc_fail_dbus(dev[0], 1, "=wpa_config_add_network;wpas_dbus_handler_wps_start",
516 "WPS.Start",
517 expected="UnknownError: WPS start failed"):
518 wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670'})
519
520 def test_dbus_wps_pbc(dev, apdev):
521 """D-Bus WPS/PBC operation and signals"""
522 try:
523 _test_dbus_wps_pbc(dev, apdev)
524 finally:
525 dev[0].request("SET wps_cred_processing 0")
526
527 def _test_dbus_wps_pbc(dev, apdev):
528 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
529 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
530
531 hapd = start_ap(apdev[0])
532 hapd.request("WPS_PBC")
533 bssid = apdev[0]['bssid']
534 dev[0].scan_for_bss(bssid, freq="2412")
535 dev[0].request("SET wps_cred_processing 2")
536
537 res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
538 dbus_interface=dbus.PROPERTIES_IFACE)
539 if len(res) != 1:
540 raise Exception("Missing BSSs entry: " + str(res))
541 bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
542 props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
543 logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
544 if 'WPS' not in props:
545 raise Exception("No WPS information in the BSS entry")
546 if 'Type' not in props['WPS']:
547 raise Exception("No Type field in the WPS dictionary")
548 if props['WPS']['Type'] != 'pbc':
549 raise Exception("Unexpected WPS Type: " + props['WPS']['Type'])
550
551 class TestDbusWps(TestDbus):
552 def __init__(self, bus, wps):
553 TestDbus.__init__(self, bus)
554 self.success_seen = False
555 self.credentials_received = False
556 self.wps = wps
557
558 def __enter__(self):
559 gobject.timeout_add(1, self.start_pbc)
560 gobject.timeout_add(15000, self.timeout)
561 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
562 self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
563 "Credentials")
564 self.loop.run()
565 return self
566
567 def wpsEvent(self, name, args):
568 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
569 if name == "success":
570 self.success_seen = True
571 if self.credentials_received:
572 self.loop.quit()
573
574 def credentials(self, args):
575 logger.debug("credentials: " + str(args))
576 self.credentials_received = True
577 if self.success_seen:
578 self.loop.quit()
579
580 def start_pbc(self, *args):
581 logger.debug("start_pbc")
582 self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
583 return False
584
585 def success(self):
586 return self.success_seen and self.credentials_received
587
588 with TestDbusWps(bus, wps) as t:
589 if not t.success():
590 raise Exception("Failure in D-Bus operations")
591
592 dev[0].wait_connected(timeout=10)
593 dev[0].request("DISCONNECT")
594 hapd.disable()
595 dev[0].flush_scan_cache()
596
597 def test_dbus_wps_pbc_overlap(dev, apdev):
598 """D-Bus WPS/PBC operation and signal for PBC overlap"""
599 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
600 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
601
602 hapd = start_ap(apdev[0])
603 hapd2 = start_ap(apdev[1], ssid="test-wps2",
604 ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7f")
605 hapd.request("WPS_PBC")
606 hapd2.request("WPS_PBC")
607 bssid = apdev[0]['bssid']
608 dev[0].scan_for_bss(bssid, freq="2412")
609 bssid2 = apdev[1]['bssid']
610 dev[0].scan_for_bss(bssid2, freq="2412")
611
612 class TestDbusWps(TestDbus):
613 def __init__(self, bus, wps):
614 TestDbus.__init__(self, bus)
615 self.overlap_seen = False
616 self.wps = wps
617
618 def __enter__(self):
619 gobject.timeout_add(1, self.start_pbc)
620 gobject.timeout_add(15000, self.timeout)
621 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
622 self.loop.run()
623 return self
624
625 def wpsEvent(self, name, args):
626 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
627 if name == "pbc-overlap":
628 self.overlap_seen = True
629 self.loop.quit()
630
631 def start_pbc(self, *args):
632 logger.debug("start_pbc")
633 self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
634 return False
635
636 def success(self):
637 return self.overlap_seen
638
639 with TestDbusWps(bus, wps) as t:
640 if not t.success():
641 raise Exception("Failure in D-Bus operations")
642
643 dev[0].request("WPS_CANCEL")
644 dev[0].request("DISCONNECT")
645 hapd.disable()
646 dev[0].flush_scan_cache()
647
648 def test_dbus_wps_pin(dev, apdev):
649 """D-Bus WPS/PIN operation and signals"""
650 try:
651 _test_dbus_wps_pin(dev, apdev)
652 finally:
653 dev[0].request("SET wps_cred_processing 0")
654
655 def _test_dbus_wps_pin(dev, apdev):
656 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
657 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
658
659 hapd = start_ap(apdev[0])
660 hapd.request("WPS_PIN any 12345670")
661 bssid = apdev[0]['bssid']
662 dev[0].scan_for_bss(bssid, freq="2412")
663 dev[0].request("SET wps_cred_processing 2")
664
665 class TestDbusWps(TestDbus):
666 def __init__(self, bus):
667 TestDbus.__init__(self, bus)
668 self.success_seen = False
669 self.credentials_received = False
670
671 def __enter__(self):
672 gobject.timeout_add(1, self.start_pin)
673 gobject.timeout_add(15000, self.timeout)
674 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
675 self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
676 "Credentials")
677 self.loop.run()
678 return self
679
680 def wpsEvent(self, name, args):
681 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
682 if name == "success":
683 self.success_seen = True
684 if self.credentials_received:
685 self.loop.quit()
686
687 def credentials(self, args):
688 logger.debug("credentials: " + str(args))
689 self.credentials_received = True
690 if self.success_seen:
691 self.loop.quit()
692
693 def start_pin(self, *args):
694 logger.debug("start_pin")
695 bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
696 wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
697 'Bssid': bssid_ay})
698 return False
699
700 def success(self):
701 return self.success_seen and self.credentials_received
702
703 with TestDbusWps(bus) as t:
704 if not t.success():
705 raise Exception("Failure in D-Bus operations")
706
707 dev[0].wait_connected(timeout=10)
708
709 def test_dbus_wps_pin2(dev, apdev):
710 """D-Bus WPS/PIN operation and signals (PIN from wpa_supplicant)"""
711 try:
712 _test_dbus_wps_pin2(dev, apdev)
713 finally:
714 dev[0].request("SET wps_cred_processing 0")
715
716 def _test_dbus_wps_pin2(dev, apdev):
717 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
718 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
719
720 hapd = start_ap(apdev[0])
721 bssid = apdev[0]['bssid']
722 dev[0].scan_for_bss(bssid, freq="2412")
723 dev[0].request("SET wps_cred_processing 2")
724
725 class TestDbusWps(TestDbus):
726 def __init__(self, bus):
727 TestDbus.__init__(self, bus)
728 self.success_seen = False
729 self.failed = False
730
731 def __enter__(self):
732 gobject.timeout_add(1, self.start_pin)
733 gobject.timeout_add(15000, self.timeout)
734 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
735 self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
736 "Credentials")
737 self.loop.run()
738 return self
739
740 def wpsEvent(self, name, args):
741 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
742 if name == "success":
743 self.success_seen = True
744 if self.credentials_received:
745 self.loop.quit()
746
747 def credentials(self, args):
748 logger.debug("credentials: " + str(args))
749 self.credentials_received = True
750 if self.success_seen:
751 self.loop.quit()
752
753 def start_pin(self, *args):
754 logger.debug("start_pin")
755 bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
756 res = wps.Start({'Role': 'enrollee', 'Type': 'pin',
757 'Bssid': bssid_ay})
758 pin = res['Pin']
759 h = hostapd.Hostapd(apdev[0]['ifname'])
760 h.request("WPS_PIN any " + pin)
761 return False
762
763 def success(self):
764 return self.success_seen and self.credentials_received
765
766 with TestDbusWps(bus) as t:
767 if not t.success():
768 raise Exception("Failure in D-Bus operations")
769
770 dev[0].wait_connected(timeout=10)
771
772 def test_dbus_wps_pin_m2d(dev, apdev):
773 """D-Bus WPS/PIN operation and signals with M2D"""
774 try:
775 _test_dbus_wps_pin_m2d(dev, apdev)
776 finally:
777 dev[0].request("SET wps_cred_processing 0")
778
779 def _test_dbus_wps_pin_m2d(dev, apdev):
780 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
781 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
782
783 hapd = start_ap(apdev[0])
784 bssid = apdev[0]['bssid']
785 dev[0].scan_for_bss(bssid, freq="2412")
786 dev[0].request("SET wps_cred_processing 2")
787
788 class TestDbusWps(TestDbus):
789 def __init__(self, bus):
790 TestDbus.__init__(self, bus)
791 self.success_seen = False
792 self.credentials_received = False
793
794 def __enter__(self):
795 gobject.timeout_add(1, self.start_pin)
796 gobject.timeout_add(15000, self.timeout)
797 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
798 self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
799 "Credentials")
800 self.loop.run()
801 return self
802
803 def wpsEvent(self, name, args):
804 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
805 if name == "success":
806 self.success_seen = True
807 if self.credentials_received:
808 self.loop.quit()
809 elif name == "m2d":
810 h = hostapd.Hostapd(apdev[0]['ifname'])
811 h.request("WPS_PIN any 12345670")
812
813 def credentials(self, args):
814 logger.debug("credentials: " + str(args))
815 self.credentials_received = True
816 if self.success_seen:
817 self.loop.quit()
818
819 def start_pin(self, *args):
820 logger.debug("start_pin")
821 bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
822 wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
823 'Bssid': bssid_ay})
824 return False
825
826 def success(self):
827 return self.success_seen and self.credentials_received
828
829 with TestDbusWps(bus) as t:
830 if not t.success():
831 raise Exception("Failure in D-Bus operations")
832
833 dev[0].wait_connected(timeout=10)
834
835 def test_dbus_wps_reg(dev, apdev):
836 """D-Bus WPS/Registrar operation and signals"""
837 try:
838 _test_dbus_wps_reg(dev, apdev)
839 finally:
840 dev[0].request("SET wps_cred_processing 0")
841
842 def _test_dbus_wps_reg(dev, apdev):
843 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
844 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
845
846 hapd = start_ap(apdev[0])
847 hapd.request("WPS_PIN any 12345670")
848 bssid = apdev[0]['bssid']
849 dev[0].scan_for_bss(bssid, freq="2412")
850 dev[0].request("SET wps_cred_processing 2")
851
852 class TestDbusWps(TestDbus):
853 def __init__(self, bus):
854 TestDbus.__init__(self, bus)
855 self.credentials_received = False
856
857 def __enter__(self):
858 gobject.timeout_add(100, self.start_reg)
859 gobject.timeout_add(15000, self.timeout)
860 self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
861 self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
862 "Credentials")
863 self.loop.run()
864 return self
865
866 def wpsEvent(self, name, args):
867 logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
868
869 def credentials(self, args):
870 logger.debug("credentials: " + str(args))
871 self.credentials_received = True
872 self.loop.quit()
873
874 def start_reg(self, *args):
875 logger.debug("start_reg")
876 bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
877 wps.Start({'Role': 'registrar', 'Type': 'pin',
878 'Pin': '12345670', 'Bssid': bssid_ay})
879 return False
880
881 def success(self):
882 return self.credentials_received
883
884 with TestDbusWps(bus) as t:
885 if not t.success():
886 raise Exception("Failure in D-Bus operations")
887
888 dev[0].wait_connected(timeout=10)
889
890 def test_dbus_wps_cancel(dev, apdev):
891 """D-Bus WPS Cancel operation"""
892 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
893 wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
894
895 hapd = start_ap(apdev[0])
896 bssid = apdev[0]['bssid']
897
898 wps.Cancel()
899 dev[0].scan_for_bss(bssid, freq="2412")
900 bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
901 wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
902 'Bssid': bssid_ay})
903 wps.Cancel()
904 dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 1)
905
906 def test_dbus_scan_invalid(dev, apdev):
907 """D-Bus invalid scan method"""
908 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
909 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
910
911 tests = [ ({}, "InvalidArgs"),
912 ({'Type': 123}, "InvalidArgs"),
913 ({'Type': 'foo'}, "InvalidArgs"),
914 ({'Type': 'active', 'Foo': 'bar'}, "InvalidArgs"),
915 ({'Type': 'active', 'SSIDs': 'foo'}, "InvalidArgs"),
916 ({'Type': 'active', 'SSIDs': ['foo']}, "InvalidArgs"),
917 ({'Type': 'active',
918 'SSIDs': [ dbus.ByteArray("1"), dbus.ByteArray("2"),
919 dbus.ByteArray("3"), dbus.ByteArray("4"),
920 dbus.ByteArray("5"), dbus.ByteArray("6"),
921 dbus.ByteArray("7"), dbus.ByteArray("8"),
922 dbus.ByteArray("9"), dbus.ByteArray("10"),
923 dbus.ByteArray("11"), dbus.ByteArray("12"),
924 dbus.ByteArray("13"), dbus.ByteArray("14"),
925 dbus.ByteArray("15"), dbus.ByteArray("16"),
926 dbus.ByteArray("17") ]},
927 "InvalidArgs"),
928 ({'Type': 'active',
929 'SSIDs': [ dbus.ByteArray("1234567890abcdef1234567890abcdef1") ]},
930 "InvalidArgs"),
931 ({'Type': 'active', 'IEs': 'foo'}, "InvalidArgs"),
932 ({'Type': 'active', 'IEs': ['foo']}, "InvalidArgs"),
933 ({'Type': 'active', 'Channels': 2412 }, "InvalidArgs"),
934 ({'Type': 'active', 'Channels': [ 2412 ] }, "InvalidArgs"),
935 ({'Type': 'active',
936 'Channels': [ (dbus.Int32(2412), dbus.UInt32(20)) ] },
937 "InvalidArgs"),
938 ({'Type': 'active',
939 'Channels': [ (dbus.UInt32(2412), dbus.Int32(20)) ] },
940 "InvalidArgs"),
941 ({'Type': 'active', 'AllowRoam': "yes" }, "InvalidArgs"),
942 ({'Type': 'passive', 'IEs': [ dbus.ByteArray("\xdd\x00") ]},
943 "InvalidArgs"),
944 ({'Type': 'passive', 'SSIDs': [ dbus.ByteArray("foo") ]},
945 "InvalidArgs")]
946 for (t,err) in tests:
947 try:
948 iface.Scan(t)
949 raise Exception("Invalid Scan() arguments accepted: " + str(t))
950 except dbus.exceptions.DBusException, e:
951 if err not in str(e):
952 raise Exception("Unexpected error message for invalid Scan(%s): %s" % (str(t), str(e)))
953
954 def test_dbus_scan_oom(dev, apdev):
955 """D-Bus scan method and OOM"""
956 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
957 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
958
959 with alloc_fail_dbus(dev[0], 1,
960 "wpa_scan_clone_params;wpas_dbus_handler_scan",
961 "Scan", expected="ScanError: Scan request rejected"):
962 iface.Scan({ 'Type': 'passive',
963 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
964
965 with alloc_fail_dbus(dev[0], 1,
966 "=wpas_dbus_get_scan_channels;wpas_dbus_handler_scan",
967 "Scan"):
968 iface.Scan({ 'Type': 'passive',
969 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
970
971 with alloc_fail_dbus(dev[0], 1,
972 "=wpas_dbus_get_scan_ies;wpas_dbus_handler_scan",
973 "Scan"):
974 iface.Scan({ 'Type': 'active',
975 'IEs': [ dbus.ByteArray("\xdd\x00") ],
976 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
977
978 with alloc_fail_dbus(dev[0], 1,
979 "=wpas_dbus_get_scan_ssids;wpas_dbus_handler_scan",
980 "Scan"):
981 iface.Scan({ 'Type': 'active',
982 'SSIDs': [ dbus.ByteArray("open"),
983 dbus.ByteArray() ],
984 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
985
986 def test_dbus_scan(dev, apdev):
987 """D-Bus scan and related signals"""
988 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
989 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
990
991 hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
992
993 class TestDbusScan(TestDbus):
994 def __init__(self, bus):
995 TestDbus.__init__(self, bus)
996 self.scan_completed = 0
997 self.bss_added = False
998 self.fail_reason = None
999
1000 def __enter__(self):
1001 gobject.timeout_add(1, self.run_scan)
1002 gobject.timeout_add(15000, self.timeout)
1003 self.add_signal(self.scanDone, WPAS_DBUS_IFACE, "ScanDone")
1004 self.add_signal(self.bssAdded, WPAS_DBUS_IFACE, "BSSAdded")
1005 self.add_signal(self.bssRemoved, WPAS_DBUS_IFACE, "BSSRemoved")
1006 self.loop.run()
1007 return self
1008
1009 def scanDone(self, success):
1010 logger.debug("scanDone: success=%s" % success)
1011 self.scan_completed += 1
1012 if self.scan_completed == 1:
1013 iface.Scan({'Type': 'passive',
1014 'AllowRoam': True,
1015 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
1016 elif self.scan_completed == 2:
1017 iface.Scan({'Type': 'passive',
1018 'AllowRoam': False})
1019 elif self.bss_added and self.scan_completed == 3:
1020 self.loop.quit()
1021
1022 def bssAdded(self, bss, properties):
1023 logger.debug("bssAdded: %s" % bss)
1024 logger.debug(str(properties))
1025 if 'WPS' in properties:
1026 if 'Type' in properties['WPS']:
1027 self.fail_reason = "Unexpected WPS dictionary entry in non-WPS BSS"
1028 self.loop.quit()
1029 self.bss_added = True
1030 if self.scan_completed == 3:
1031 self.loop.quit()
1032
1033 def bssRemoved(self, bss):
1034 logger.debug("bssRemoved: %s" % bss)
1035
1036 def run_scan(self, *args):
1037 logger.debug("run_scan")
1038 iface.Scan({'Type': 'active',
1039 'SSIDs': [ dbus.ByteArray("open"),
1040 dbus.ByteArray() ],
1041 'IEs': [ dbus.ByteArray("\xdd\x00"),
1042 dbus.ByteArray() ],
1043 'AllowRoam': False,
1044 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
1045 return False
1046
1047 def success(self):
1048 return self.scan_completed == 3 and self.bss_added
1049
1050 with TestDbusScan(bus) as t:
1051 if t.fail_reason:
1052 raise Exception(t.fail_reason)
1053 if not t.success():
1054 raise Exception("Expected signals not seen")
1055
1056 res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
1057 dbus_interface=dbus.PROPERTIES_IFACE)
1058 if len(res) < 1:
1059 raise Exception("Scan result not in BSSs property")
1060 iface.FlushBSS(0)
1061 res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
1062 dbus_interface=dbus.PROPERTIES_IFACE)
1063 if len(res) != 0:
1064 raise Exception("FlushBSS() did not remove scan results from BSSs property")
1065 iface.FlushBSS(1)
1066
1067 def test_dbus_scan_busy(dev, apdev):
1068 """D-Bus scan trigger rejection when busy with previous scan"""
1069 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1070 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1071
1072 if "OK" not in dev[0].request("SCAN freq=2412-2462"):
1073 raise Exception("Failed to start scan")
1074 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], 15)
1075 if ev is None:
1076 raise Exception("Scan start timed out")
1077
1078 try:
1079 iface.Scan({'Type': 'active', 'AllowRoam': False})
1080 raise Exception("Scan() accepted when busy")
1081 except dbus.exceptions.DBusException, e:
1082 if "ScanError: Scan request reject" not in str(e):
1083 raise Exception("Unexpected error message: " + str(e))
1084
1085 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
1086 if ev is None:
1087 raise Exception("Scan timed out")
1088
1089 def test_dbus_connect(dev, apdev):
1090 """D-Bus AddNetwork and connect"""
1091 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1092 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1093
1094 ssid = "test-wpa2-psk"
1095 passphrase = 'qwertyuiop'
1096 params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
1097 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1098
1099 class TestDbusConnect(TestDbus):
1100 def __init__(self, bus):
1101 TestDbus.__init__(self, bus)
1102 self.network_added = False
1103 self.network_selected = False
1104 self.network_removed = False
1105 self.state = 0
1106
1107 def __enter__(self):
1108 gobject.timeout_add(1, self.run_connect)
1109 gobject.timeout_add(15000, self.timeout)
1110 self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
1111 self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
1112 "NetworkRemoved")
1113 self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
1114 "NetworkSelected")
1115 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
1116 "PropertiesChanged")
1117 self.loop.run()
1118 return self
1119
1120 def networkAdded(self, network, properties):
1121 logger.debug("networkAdded: %s" % str(network))
1122 logger.debug(str(properties))
1123 self.network_added = True
1124
1125 def networkRemoved(self, network):
1126 logger.debug("networkRemoved: %s" % str(network))
1127 self.network_removed = True
1128
1129 def networkSelected(self, network):
1130 logger.debug("networkSelected: %s" % str(network))
1131 self.network_selected = True
1132
1133 def propertiesChanged(self, properties):
1134 logger.debug("propertiesChanged: %s" % str(properties))
1135 if 'State' in properties and properties['State'] == "completed":
1136 if self.state == 0:
1137 self.state = 1
1138 iface.Disconnect()
1139 elif self.state == 2:
1140 self.state = 3
1141 iface.Disconnect()
1142 elif self.state == 4:
1143 self.state = 5
1144 iface.Reattach()
1145 elif self.state == 5:
1146 self.state = 6
1147 iface.Disconnect()
1148 elif self.state == 7:
1149 self.state = 8
1150 res = iface.SignalPoll()
1151 logger.debug("SignalPoll: " + str(res))
1152 if 'frequency' not in res or res['frequency'] != 2412:
1153 self.state = -1
1154 logger.info("Unexpected SignalPoll result")
1155 iface.RemoveNetwork(self.netw)
1156 if 'State' in properties and properties['State'] == "disconnected":
1157 if self.state == 1:
1158 self.state = 2
1159 iface.SelectNetwork(self.netw)
1160 elif self.state == 3:
1161 self.state = 4
1162 iface.Reassociate()
1163 elif self.state == 6:
1164 self.state = 7
1165 iface.Reconnect()
1166 elif self.state == 8:
1167 self.state = 9
1168 self.loop.quit()
1169
1170 def run_connect(self, *args):
1171 logger.debug("run_connect")
1172 args = dbus.Dictionary({ 'ssid': ssid,
1173 'key_mgmt': 'WPA-PSK',
1174 'psk': passphrase,
1175 'scan_freq': 2412 },
1176 signature='sv')
1177 self.netw = iface.AddNetwork(args)
1178 iface.SelectNetwork(self.netw)
1179 return False
1180
1181 def success(self):
1182 if not self.network_added or \
1183 not self.network_removed or \
1184 not self.network_selected:
1185 return False
1186 return self.state == 9
1187
1188 with TestDbusConnect(bus) as t:
1189 if not t.success():
1190 raise Exception("Expected signals not seen")
1191
1192 def test_dbus_connect_psk_mem(dev, apdev):
1193 """D-Bus AddNetwork and connect with memory-only PSK"""
1194 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1195 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1196
1197 ssid = "test-wpa2-psk"
1198 passphrase = 'qwertyuiop'
1199 params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
1200 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1201
1202 class TestDbusConnect(TestDbus):
1203 def __init__(self, bus):
1204 TestDbus.__init__(self, bus)
1205 self.connected = False
1206
1207 def __enter__(self):
1208 gobject.timeout_add(1, self.run_connect)
1209 gobject.timeout_add(15000, self.timeout)
1210 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
1211 "PropertiesChanged")
1212 self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
1213 "NetworkRequest")
1214 self.loop.run()
1215 return self
1216
1217 def propertiesChanged(self, properties):
1218 logger.debug("propertiesChanged: %s" % str(properties))
1219 if 'State' in properties and properties['State'] == "completed":
1220 self.connected = True
1221 self.loop.quit()
1222
1223 def networkRequest(self, path, field, txt):
1224 logger.debug("networkRequest: %s %s %s" % (path, field, txt))
1225 if field == "PSK_PASSPHRASE":
1226 iface.NetworkReply(path, field, '"' + passphrase + '"')
1227
1228 def run_connect(self, *args):
1229 logger.debug("run_connect")
1230 args = dbus.Dictionary({ 'ssid': ssid,
1231 'key_mgmt': 'WPA-PSK',
1232 'mem_only_psk': 1,
1233 'scan_freq': 2412 },
1234 signature='sv')
1235 self.netw = iface.AddNetwork(args)
1236 iface.SelectNetwork(self.netw)
1237 return False
1238
1239 def success(self):
1240 return self.connected
1241
1242 with TestDbusConnect(bus) as t:
1243 if not t.success():
1244 raise Exception("Expected signals not seen")
1245
1246 def test_dbus_connect_oom(dev, apdev):
1247 """D-Bus AddNetwork and connect when out-of-memory"""
1248 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1249 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1250
1251 if "OK" not in dev[0].request("TEST_ALLOC_FAIL 0:"):
1252 raise HwsimSkip("TEST_ALLOC_FAIL not supported in the build")
1253
1254 ssid = "test-wpa2-psk"
1255 passphrase = 'qwertyuiop'
1256 params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
1257 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1258
1259 class TestDbusConnect(TestDbus):
1260 def __init__(self, bus):
1261 TestDbus.__init__(self, bus)
1262 self.network_added = False
1263 self.network_selected = False
1264 self.network_removed = False
1265 self.state = 0
1266
1267 def __enter__(self):
1268 gobject.timeout_add(1, self.run_connect)
1269 gobject.timeout_add(1500, self.timeout)
1270 self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
1271 self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
1272 "NetworkRemoved")
1273 self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
1274 "NetworkSelected")
1275 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
1276 "PropertiesChanged")
1277 self.loop.run()
1278 return self
1279
1280 def networkAdded(self, network, properties):
1281 logger.debug("networkAdded: %s" % str(network))
1282 logger.debug(str(properties))
1283 self.network_added = True
1284
1285 def networkRemoved(self, network):
1286 logger.debug("networkRemoved: %s" % str(network))
1287 self.network_removed = True
1288
1289 def networkSelected(self, network):
1290 logger.debug("networkSelected: %s" % str(network))
1291 self.network_selected = True
1292
1293 def propertiesChanged(self, properties):
1294 logger.debug("propertiesChanged: %s" % str(properties))
1295 if 'State' in properties and properties['State'] == "completed":
1296 if self.state == 0:
1297 self.state = 1
1298 iface.Disconnect()
1299 elif self.state == 2:
1300 self.state = 3
1301 iface.Disconnect()
1302 elif self.state == 4:
1303 self.state = 5
1304 iface.Reattach()
1305 elif self.state == 5:
1306 self.state = 6
1307 res = iface.SignalPoll()
1308 logger.debug("SignalPoll: " + str(res))
1309 if 'frequency' not in res or res['frequency'] != 2412:
1310 self.state = -1
1311 logger.info("Unexpected SignalPoll result")
1312 iface.RemoveNetwork(self.netw)
1313 if 'State' in properties and properties['State'] == "disconnected":
1314 if self.state == 1:
1315 self.state = 2
1316 iface.SelectNetwork(self.netw)
1317 elif self.state == 3:
1318 self.state = 4
1319 iface.Reassociate()
1320 elif self.state == 6:
1321 self.state = 7
1322 self.loop.quit()
1323
1324 def run_connect(self, *args):
1325 logger.debug("run_connect")
1326 args = dbus.Dictionary({ 'ssid': ssid,
1327 'key_mgmt': 'WPA-PSK',
1328 'psk': passphrase,
1329 'scan_freq': 2412 },
1330 signature='sv')
1331 try:
1332 self.netw = iface.AddNetwork(args)
1333 except Exception, e:
1334 logger.info("Exception on AddNetwork: " + str(e))
1335 self.loop.quit()
1336 return False
1337 try:
1338 iface.SelectNetwork(self.netw)
1339 except Exception, e:
1340 logger.info("Exception on SelectNetwork: " + str(e))
1341 self.loop.quit()
1342
1343 return False
1344
1345 def success(self):
1346 if not self.network_added or \
1347 not self.network_removed or \
1348 not self.network_selected:
1349 return False
1350 return self.state == 7
1351
1352 count = 0
1353 for i in range(1, 1000):
1354 for j in range(3):
1355 dev[j].dump_monitor()
1356 dev[0].request("TEST_ALLOC_FAIL %d:main" % i)
1357 try:
1358 with TestDbusConnect(bus) as t:
1359 if not t.success():
1360 logger.info("Iteration %d - Expected signals not seen" % i)
1361 else:
1362 logger.info("Iteration %d - success" % i)
1363
1364 state = dev[0].request('GET_ALLOC_FAIL')
1365 logger.info("GET_ALLOC_FAIL: " + state)
1366 dev[0].dump_monitor()
1367 dev[0].request("TEST_ALLOC_FAIL 0:")
1368 if i < 3:
1369 raise Exception("Connection succeeded during out-of-memory")
1370 if not state.startswith('0:'):
1371 count += 1
1372 if count == 5:
1373 break
1374 except:
1375 pass
1376
1377 def test_dbus_while_not_connected(dev, apdev):
1378 """D-Bus invalid operations while not connected"""
1379 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1380 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1381
1382 try:
1383 iface.Disconnect()
1384 raise Exception("Disconnect() accepted when not connected")
1385 except dbus.exceptions.DBusException, e:
1386 if "NotConnected" not in str(e):
1387 raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
1388
1389 try:
1390 iface.Reattach()
1391 raise Exception("Reattach() accepted when not connected")
1392 except dbus.exceptions.DBusException, e:
1393 if "NotConnected" not in str(e):
1394 raise Exception("Unexpected error message for invalid Reattach: " + str(e))
1395
1396 def test_dbus_connect_eap(dev, apdev):
1397 """D-Bus AddNetwork and connect to EAP network"""
1398 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1399 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1400
1401 ssid = "ieee8021x-open"
1402 params = hostapd.radius_params()
1403 params["ssid"] = ssid
1404 params["ieee8021x"] = "1"
1405 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1406
1407 class TestDbusConnect(TestDbus):
1408 def __init__(self, bus):
1409 TestDbus.__init__(self, bus)
1410 self.certification_received = False
1411 self.eap_status = False
1412 self.state = 0
1413
1414 def __enter__(self):
1415 gobject.timeout_add(1, self.run_connect)
1416 gobject.timeout_add(15000, self.timeout)
1417 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
1418 "PropertiesChanged")
1419 self.add_signal(self.certification, WPAS_DBUS_IFACE,
1420 "Certification", byte_arrays=True)
1421 self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
1422 "NetworkRequest")
1423 self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
1424 self.loop.run()
1425 return self
1426
1427 def propertiesChanged(self, properties):
1428 logger.debug("propertiesChanged: %s" % str(properties))
1429 if 'State' in properties and properties['State'] == "completed":
1430 if self.state == 0:
1431 self.state = 1
1432 iface.EAPLogoff()
1433 logger.info("Set dNSName constraint")
1434 net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
1435 args = dbus.Dictionary({ 'altsubject_match':
1436 self.server_dnsname },
1437 signature='sv')
1438 net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
1439 dbus_interface=dbus.PROPERTIES_IFACE)
1440 elif self.state == 2:
1441 self.state = 3
1442 iface.Disconnect()
1443 logger.info("Set non-matching dNSName constraint")
1444 net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
1445 args = dbus.Dictionary({ 'altsubject_match':
1446 self.server_dnsname + "FOO" },
1447 signature='sv')
1448 net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
1449 dbus_interface=dbus.PROPERTIES_IFACE)
1450 if 'State' in properties and properties['State'] == "disconnected":
1451 if self.state == 1:
1452 self.state = 2
1453 iface.EAPLogon()
1454 iface.SelectNetwork(self.netw)
1455 if self.state == 3:
1456 self.state = 4
1457 iface.SelectNetwork(self.netw)
1458
1459 def certification(self, args):
1460 logger.debug("certification: %s" % str(args))
1461 self.certification_received = True
1462 if args['depth'] == 0:
1463 # The test server certificate is supposed to have dNSName
1464 if len(args['altsubject']) < 1:
1465 raise Exception("Missing dNSName")
1466 dnsname = args['altsubject'][0]
1467 if not dnsname.startswith("DNS:"):
1468 raise Exception("Expected dNSName not found: " + dnsname)
1469 logger.info("altsubject: " + dnsname)
1470 self.server_dnsname = dnsname
1471
1472 def eap(self, status, parameter):
1473 logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
1474 if status == 'completion' and parameter == 'success':
1475 self.eap_status = True
1476 if self.state == 4 and status == 'remote certificate verification' and parameter == 'AltSubject mismatch':
1477 self.state = 5
1478 self.loop.quit()
1479
1480 def networkRequest(self, path, field, txt):
1481 logger.debug("networkRequest: %s %s %s" % (path, field, txt))
1482 if field == "PASSWORD":
1483 iface.NetworkReply(path, field, "password")
1484
1485 def run_connect(self, *args):
1486 logger.debug("run_connect")
1487 args = dbus.Dictionary({ 'ssid': ssid,
1488 'key_mgmt': 'IEEE8021X',
1489 'eapol_flags': 0,
1490 'eap': 'TTLS',
1491 'anonymous_identity': 'ttls',
1492 'identity': 'pap user',
1493 'ca_cert': 'auth_serv/ca.pem',
1494 'phase2': 'auth=PAP',
1495 'scan_freq': 2412 },
1496 signature='sv')
1497 self.netw = iface.AddNetwork(args)
1498 iface.SelectNetwork(self.netw)
1499 return False
1500
1501 def success(self):
1502 if not self.eap_status or not self.certification_received:
1503 return False
1504 return self.state == 5
1505
1506 with TestDbusConnect(bus) as t:
1507 if not t.success():
1508 raise Exception("Expected signals not seen")
1509
1510 def test_dbus_network(dev, apdev):
1511 """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
1512 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1513 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1514
1515 args = dbus.Dictionary({ 'ssid': "foo",
1516 'key_mgmt': 'WPA-PSK',
1517 'psk': "12345678",
1518 'identity': dbus.ByteArray([ 1, 2 ]),
1519 'priority': dbus.Int32(0),
1520 'scan_freq': dbus.UInt32(2412) },
1521 signature='sv')
1522 netw = iface.AddNetwork(args)
1523 id = int(dev[0].list_networks()[0]['id'])
1524 val = dev[0].get_network(id, "scan_freq")
1525 if val != "2412":
1526 raise Exception("Invalid scan_freq value: " + str(val))
1527 iface.RemoveNetwork(netw)
1528
1529 args = dbus.Dictionary({ 'ssid': "foo",
1530 'key_mgmt': 'NONE',
1531 'scan_freq': "2412 2432",
1532 'freq_list': "2412 2417 2432" },
1533 signature='sv')
1534 netw = iface.AddNetwork(args)
1535 id = int(dev[0].list_networks()[0]['id'])
1536 val = dev[0].get_network(id, "scan_freq")
1537 if val != "2412 2432":
1538 raise Exception("Invalid scan_freq value (2): " + str(val))
1539 val = dev[0].get_network(id, "freq_list")
1540 if val != "2412 2417 2432":
1541 raise Exception("Invalid freq_list value: " + str(val))
1542 iface.RemoveNetwork(netw)
1543 try:
1544 iface.RemoveNetwork(netw)
1545 raise Exception("Invalid RemoveNetwork() accepted")
1546 except dbus.exceptions.DBusException, e:
1547 if "NetworkUnknown" not in str(e):
1548 raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
1549 try:
1550 iface.SelectNetwork(netw)
1551 raise Exception("Invalid SelectNetwork() accepted")
1552 except dbus.exceptions.DBusException, e:
1553 if "NetworkUnknown" not in str(e):
1554 raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
1555
1556 args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
1557 'identity': "testuser", 'scan_freq': '2412' },
1558 signature='sv')
1559 netw1 = iface.AddNetwork(args)
1560 args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
1561 signature='sv')
1562 netw2 = iface.AddNetwork(args)
1563 res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
1564 dbus_interface=dbus.PROPERTIES_IFACE)
1565 if len(res) != 2:
1566 raise Exception("Unexpected number of networks")
1567
1568 net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
1569 res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
1570 dbus_interface=dbus.PROPERTIES_IFACE)
1571 if res != False:
1572 raise Exception("Added network was unexpectedly enabled by default")
1573 net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(True),
1574 dbus_interface=dbus.PROPERTIES_IFACE)
1575 res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
1576 dbus_interface=dbus.PROPERTIES_IFACE)
1577 if res != True:
1578 raise Exception("Set(Enabled,True) did not seem to change property value")
1579 net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(False),
1580 dbus_interface=dbus.PROPERTIES_IFACE)
1581 res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
1582 dbus_interface=dbus.PROPERTIES_IFACE)
1583 if res != False:
1584 raise Exception("Set(Enabled,False) did not seem to change property value")
1585 try:
1586 net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.UInt32(1),
1587 dbus_interface=dbus.PROPERTIES_IFACE)
1588 raise Exception("Invalid Set(Enabled,1) accepted")
1589 except dbus.exceptions.DBusException, e:
1590 if "Error.Failed: wrong property type" not in str(e):
1591 raise Exception("Unexpected error message for invalid Set(Enabled,1): " + str(e))
1592
1593 args = dbus.Dictionary({ 'ssid': "foo1new" }, signature='sv')
1594 net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
1595 dbus_interface=dbus.PROPERTIES_IFACE)
1596 res = net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
1597 dbus_interface=dbus.PROPERTIES_IFACE)
1598 if res['ssid'] != '"foo1new"':
1599 raise Exception("Set(Properties) failed to update ssid")
1600 if res['identity'] != '"testuser"':
1601 raise Exception("Set(Properties) unexpectedly changed unrelated parameter")
1602
1603 iface.RemoveAllNetworks()
1604 res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
1605 dbus_interface=dbus.PROPERTIES_IFACE)
1606 if len(res) != 0:
1607 raise Exception("Unexpected number of networks")
1608 iface.RemoveAllNetworks()
1609
1610 tests = [ dbus.Dictionary({ 'psk': "1234567" }, signature='sv'),
1611 dbus.Dictionary({ 'identity': dbus.ByteArray() },
1612 signature='sv'),
1613 dbus.Dictionary({ 'identity': dbus.Byte(1) }, signature='sv'),
1614 dbus.Dictionary({ 'identity': "" }, signature='sv') ]
1615 for args in tests:
1616 try:
1617 iface.AddNetwork(args)
1618 raise Exception("Invalid AddNetwork args accepted: " + str(args))
1619 except dbus.exceptions.DBusException, e:
1620 if "InvalidArgs" not in str(e):
1621 raise Exception("Unexpected error message for invalid AddNetwork: " + str(e))
1622
1623 def test_dbus_network_oom(dev, apdev):
1624 """D-Bus AddNetwork/RemoveNetwork parameters and OOM error cases"""
1625 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1626 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1627
1628 args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
1629 'identity': "testuser", 'scan_freq': '2412' },
1630 signature='sv')
1631 netw1 = iface.AddNetwork(args)
1632 net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
1633
1634 with alloc_fail_dbus(dev[0], 1,
1635 "wpa_config_get_all;wpas_dbus_getter_network_properties",
1636 "Get"):
1637 net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
1638 dbus_interface=dbus.PROPERTIES_IFACE)
1639
1640 iface.RemoveAllNetworks()
1641
1642 with alloc_fail_dbus(dev[0], 1,
1643 "wpas_dbus_new_decompose_object_path;wpas_dbus_handler_remove_network",
1644 "RemoveNetwork", "InvalidArgs"):
1645 iface.RemoveNetwork(dbus.ObjectPath("/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234"))
1646
1647 with alloc_fail(dev[0], 1, "wpa_dbus_register_object_per_iface;wpas_dbus_register_network"):
1648 args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
1649 signature='sv')
1650 try:
1651 netw = iface.AddNetwork(args)
1652 # Currently, AddNetwork() succeeds even if os_strdup() for path
1653 # fails, so remove the network if that occurs.
1654 iface.RemoveNetwork(netw)
1655 except dbus.exceptions.DBusException, e:
1656 pass
1657
1658 for i in range(1, 3):
1659 with alloc_fail(dev[0], i, "=wpas_dbus_register_network"):
1660 try:
1661 netw = iface.AddNetwork(args)
1662 # Currently, AddNetwork() succeeds even if network registration
1663 # fails, so remove the network if that occurs.
1664 iface.RemoveNetwork(netw)
1665 except dbus.exceptions.DBusException, e:
1666 pass
1667
1668 with alloc_fail_dbus(dev[0], 1,
1669 "=wpa_config_add_network;wpas_dbus_handler_add_network",
1670 "AddNetwork",
1671 "UnknownError: wpa_supplicant could not add a network"):
1672 args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
1673 signature='sv')
1674 netw = iface.AddNetwork(args)
1675
1676 tests = [ (1,
1677 'wpa_dbus_dict_get_entry;set_network_properties;wpas_dbus_handler_add_network',
1678 dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
1679 signature='sv')),
1680 (1, '=set_network_properties;wpas_dbus_handler_add_network',
1681 dbus.Dictionary({ 'ssid': 'foo' }, signature='sv')),
1682 (1, '=set_network_properties;wpas_dbus_handler_add_network',
1683 dbus.Dictionary({ 'eap': 'foo' }, signature='sv')),
1684 (1, '=set_network_properties;wpas_dbus_handler_add_network',
1685 dbus.Dictionary({ 'priority': dbus.UInt32(1) },
1686 signature='sv')),
1687 (1, '=set_network_properties;wpas_dbus_handler_add_network',
1688 dbus.Dictionary({ 'priority': dbus.Int32(1) },
1689 signature='sv')),
1690 (1, '=set_network_properties;wpas_dbus_handler_add_network',
1691 dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
1692 signature='sv')) ]
1693 for (count,funcs,args) in tests:
1694 with alloc_fail_dbus(dev[0], count, funcs, "AddNetwork", "InvalidArgs"):
1695 netw = iface.AddNetwork(args)
1696
1697 if len(if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
1698 dbus_interface=dbus.PROPERTIES_IFACE)) > 0:
1699 raise Exception("Unexpected network block added")
1700 if len(dev[0].list_networks()) > 0:
1701 raise Exception("Unexpected network block visible")
1702
1703 def test_dbus_interface(dev, apdev):
1704 """D-Bus CreateInterface/GetInterface/RemoveInterface parameters and error cases"""
1705 try:
1706 _test_dbus_interface(dev, apdev)
1707 finally:
1708 # Need to force P2P channel list update since the 'lo' interface
1709 # with driver=none ends up configuring default dualband channels.
1710 dev[0].request("SET country US")
1711 ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
1712 if ev is None:
1713 ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
1714 timeout=1)
1715 dev[0].request("SET country 00")
1716 ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
1717 if ev is None:
1718 ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
1719 timeout=1)
1720 subprocess.call(['iw', 'reg', 'set', '00'])
1721
1722 def _test_dbus_interface(dev, apdev):
1723 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1724 wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
1725
1726 params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
1727 signature='sv')
1728 path = wpas.CreateInterface(params)
1729 logger.debug("New interface path: " + str(path))
1730 path2 = wpas.GetInterface("lo")
1731 if path != path2:
1732 raise Exception("Interface object mismatch")
1733
1734 params = dbus.Dictionary({ 'Ifname': 'lo',
1735 'Driver': 'none',
1736 'ConfigFile': 'foo',
1737 'BridgeIfname': 'foo', },
1738 signature='sv')
1739 try:
1740 wpas.CreateInterface(params)
1741 raise Exception("Invalid CreateInterface() accepted")
1742 except dbus.exceptions.DBusException, e:
1743 if "InterfaceExists" not in str(e):
1744 raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
1745
1746 wpas.RemoveInterface(path)
1747 try:
1748 wpas.RemoveInterface(path)
1749 raise Exception("Invalid RemoveInterface() accepted")
1750 except dbus.exceptions.DBusException, e:
1751 if "InterfaceUnknown" not in str(e):
1752 raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
1753
1754 params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none',
1755 'Foo': 123 },
1756 signature='sv')
1757 try:
1758 wpas.CreateInterface(params)
1759 raise Exception("Invalid CreateInterface() accepted")
1760 except dbus.exceptions.DBusException, e:
1761 if "InvalidArgs" not in str(e):
1762 raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
1763
1764 params = dbus.Dictionary({ 'Driver': 'none' }, signature='sv')
1765 try:
1766 wpas.CreateInterface(params)
1767 raise Exception("Invalid CreateInterface() accepted")
1768 except dbus.exceptions.DBusException, e:
1769 if "InvalidArgs" not in str(e):
1770 raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
1771
1772 try:
1773 wpas.GetInterface("lo")
1774 raise Exception("Invalid GetInterface() accepted")
1775 except dbus.exceptions.DBusException, e:
1776 if "InterfaceUnknown" not in str(e):
1777 raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
1778
1779 def test_dbus_interface_oom(dev, apdev):
1780 """D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
1781 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1782 wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
1783
1784 with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interface", "CreateInterface", "InvalidArgs"):
1785 params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
1786 signature='sv')
1787 wpas.CreateInterface(params)
1788
1789 for i in range(1, 1000):
1790 dev[0].request("TEST_ALLOC_FAIL %d:wpa_supplicant_add_iface;wpas_dbus_handler_create_interface" % i)
1791 params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
1792 signature='sv')
1793 try:
1794 npath = wpas.CreateInterface(params)
1795 wpas.RemoveInterface(npath)
1796 logger.info("CreateInterface succeeds after %d allocation failures" % i)
1797 state = dev[0].request('GET_ALLOC_FAIL')
1798 logger.info("GET_ALLOC_FAIL: " + state)
1799 dev[0].dump_monitor()
1800 dev[0].request("TEST_ALLOC_FAIL 0:")
1801 if i < 5:
1802 raise Exception("CreateInterface succeeded during out-of-memory")
1803 if not state.startswith('0:'):
1804 break
1805 except dbus.exceptions.DBusException, e:
1806 pass
1807
1808 for arg in [ 'Driver', 'Ifname', 'ConfigFile', 'BridgeIfname' ]:
1809 with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_handler_create_interface",
1810 "CreateInterface"):
1811 params = dbus.Dictionary({ arg: 'foo' }, signature='sv')
1812 wpas.CreateInterface(params)
1813
1814 def test_dbus_blob(dev, apdev):
1815 """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
1816 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1817 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1818
1819 blob = dbus.ByteArray("\x01\x02\x03")
1820 iface.AddBlob('blob1', blob)
1821 try:
1822 iface.AddBlob('blob1', dbus.ByteArray("\x01\x02\x04"))
1823 raise Exception("Invalid AddBlob() accepted")
1824 except dbus.exceptions.DBusException, e:
1825 if "BlobExists" not in str(e):
1826 raise Exception("Unexpected error message for invalid AddBlob: " + str(e))
1827 res = iface.GetBlob('blob1')
1828 if len(res) != len(blob):
1829 raise Exception("Unexpected blob data length")
1830 for i in range(len(res)):
1831 if res[i] != dbus.Byte(blob[i]):
1832 raise Exception("Unexpected blob data")
1833 res = if_obj.Get(WPAS_DBUS_IFACE, "Blobs",
1834 dbus_interface=dbus.PROPERTIES_IFACE)
1835 if 'blob1' not in res:
1836 raise Exception("Added blob missing from Blobs property")
1837 iface.RemoveBlob('blob1')
1838 try:
1839 iface.RemoveBlob('blob1')
1840 raise Exception("Invalid RemoveBlob() accepted")
1841 except dbus.exceptions.DBusException, e:
1842 if "BlobUnknown" not in str(e):
1843 raise Exception("Unexpected error message for invalid RemoveBlob: " + str(e))
1844 try:
1845 iface.GetBlob('blob1')
1846 raise Exception("Invalid GetBlob() accepted")
1847 except dbus.exceptions.DBusException, e:
1848 if "BlobUnknown" not in str(e):
1849 raise Exception("Unexpected error message for invalid GetBlob: " + str(e))
1850
1851 class TestDbusBlob(TestDbus):
1852 def __init__(self, bus):
1853 TestDbus.__init__(self, bus)
1854 self.blob_added = False
1855 self.blob_removed = False
1856
1857 def __enter__(self):
1858 gobject.timeout_add(1, self.run_blob)
1859 gobject.timeout_add(15000, self.timeout)
1860 self.add_signal(self.blobAdded, WPAS_DBUS_IFACE, "BlobAdded")
1861 self.add_signal(self.blobRemoved, WPAS_DBUS_IFACE, "BlobRemoved")
1862 self.loop.run()
1863 return self
1864
1865 def blobAdded(self, blobName):
1866 logger.debug("blobAdded: %s" % blobName)
1867 if blobName == 'blob2':
1868 self.blob_added = True
1869
1870 def blobRemoved(self, blobName):
1871 logger.debug("blobRemoved: %s" % blobName)
1872 if blobName == 'blob2':
1873 self.blob_removed = True
1874 self.loop.quit()
1875
1876 def run_blob(self, *args):
1877 logger.debug("run_blob")
1878 iface.AddBlob('blob2', dbus.ByteArray("\x01\x02\x04"))
1879 iface.RemoveBlob('blob2')
1880 return False
1881
1882 def success(self):
1883 return self.blob_added and self.blob_removed
1884
1885 with TestDbusBlob(bus) as t:
1886 if not t.success():
1887 raise Exception("Expected signals not seen")
1888
1889 def test_dbus_blob_oom(dev, apdev):
1890 """D-Bus AddNetwork/RemoveNetwork OOM error cases"""
1891 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1892 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1893
1894 for i in range(1, 4):
1895 with alloc_fail_dbus(dev[0], i, "wpas_dbus_handler_add_blob",
1896 "AddBlob"):
1897 iface.AddBlob('blob_no_mem', dbus.ByteArray("\x01\x02\x03\x04"))
1898
1899 def test_dbus_autoscan(dev, apdev):
1900 """D-Bus Autoscan()"""
1901 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1902 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1903
1904 iface.AutoScan("foo")
1905 iface.AutoScan("periodic:1")
1906 iface.AutoScan("")
1907 dev[0].request("AUTOSCAN ")
1908
1909 def test_dbus_autoscan_oom(dev, apdev):
1910 """D-Bus Autoscan() OOM"""
1911 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1912 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1913
1914 with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_autoscan", "AutoScan"):
1915 iface.AutoScan("foo")
1916 dev[0].request("AUTOSCAN ")
1917
1918 def test_dbus_tdls_invalid(dev, apdev):
1919 """D-Bus invalid TDLS operations"""
1920 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1921 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1922
1923 hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
1924 connect_2sta_open(dev, hapd)
1925 addr1 = dev[1].p2p_interface_addr()
1926
1927 try:
1928 iface.TDLSDiscover("foo")
1929 raise Exception("Invalid TDLSDiscover() accepted")
1930 except dbus.exceptions.DBusException, e:
1931 if "InvalidArgs" not in str(e):
1932 raise Exception("Unexpected error message for invalid TDLSDiscover: " + str(e))
1933
1934 try:
1935 iface.TDLSStatus("foo")
1936 raise Exception("Invalid TDLSStatus() accepted")
1937 except dbus.exceptions.DBusException, e:
1938 if "InvalidArgs" not in str(e):
1939 raise Exception("Unexpected error message for invalid TDLSStatus: " + str(e))
1940
1941 res = iface.TDLSStatus(addr1)
1942 if res != "peer does not exist":
1943 raise Exception("Unexpected TDLSStatus response")
1944
1945 try:
1946 iface.TDLSSetup("foo")
1947 raise Exception("Invalid TDLSSetup() accepted")
1948 except dbus.exceptions.DBusException, e:
1949 if "InvalidArgs" not in str(e):
1950 raise Exception("Unexpected error message for invalid TDLSSetup: " + str(e))
1951
1952 try:
1953 iface.TDLSTeardown("foo")
1954 raise Exception("Invalid TDLSTeardown() accepted")
1955 except dbus.exceptions.DBusException, e:
1956 if "InvalidArgs" not in str(e):
1957 raise Exception("Unexpected error message for invalid TDLSTeardown: " + str(e))
1958
1959 try:
1960 iface.TDLSTeardown("00:11:22:33:44:55")
1961 raise Exception("TDLSTeardown accepted for unknown peer")
1962 except dbus.exceptions.DBusException, e:
1963 if "UnknownError: error performing TDLS teardown" not in str(e):
1964 raise Exception("Unexpected error message: " + str(e))
1965
1966 def test_dbus_tdls_oom(dev, apdev):
1967 """D-Bus TDLS operations during OOM"""
1968 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1969 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1970
1971 with alloc_fail_dbus(dev[0], 1, "wpa_tdls_add_peer", "TDLSSetup",
1972 "UnknownError: error performing TDLS setup"):
1973 iface.TDLSSetup("00:11:22:33:44:55")
1974
1975 def test_dbus_tdls(dev, apdev):
1976 """D-Bus TDLS"""
1977 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
1978 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
1979
1980 hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
1981 connect_2sta_open(dev, hapd)
1982
1983 addr1 = dev[1].p2p_interface_addr()
1984
1985 class TestDbusTdls(TestDbus):
1986 def __init__(self, bus):
1987 TestDbus.__init__(self, bus)
1988 self.tdls_setup = False
1989 self.tdls_teardown = False
1990
1991 def __enter__(self):
1992 gobject.timeout_add(1, self.run_tdls)
1993 gobject.timeout_add(15000, self.timeout)
1994 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
1995 "PropertiesChanged")
1996 self.loop.run()
1997 return self
1998
1999 def propertiesChanged(self, properties):
2000 logger.debug("propertiesChanged: %s" % str(properties))
2001
2002 def run_tdls(self, *args):
2003 logger.debug("run_tdls")
2004 iface.TDLSDiscover(addr1)
2005 gobject.timeout_add(100, self.run_tdls2)
2006 return False
2007
2008 def run_tdls2(self, *args):
2009 logger.debug("run_tdls2")
2010 iface.TDLSSetup(addr1)
2011 gobject.timeout_add(500, self.run_tdls3)
2012 return False
2013
2014 def run_tdls3(self, *args):
2015 logger.debug("run_tdls3")
2016 res = iface.TDLSStatus(addr1)
2017 if res == "connected":
2018 self.tdls_setup = True
2019 else:
2020 logger.info("Unexpected TDLSStatus: " + res)
2021 iface.TDLSTeardown(addr1)
2022 gobject.timeout_add(200, self.run_tdls4)
2023 return False
2024
2025 def run_tdls4(self, *args):
2026 logger.debug("run_tdls4")
2027 res = iface.TDLSStatus(addr1)
2028 if res == "peer does not exist":
2029 self.tdls_teardown = True
2030 else:
2031 logger.info("Unexpected TDLSStatus: " + res)
2032 self.loop.quit()
2033 return False
2034
2035 def success(self):
2036 return self.tdls_setup and self.tdls_teardown
2037
2038 with TestDbusTdls(bus) as t:
2039 if not t.success():
2040 raise Exception("Expected signals not seen")
2041
2042 def test_dbus_pkcs11(dev, apdev):
2043 """D-Bus SetPKCS11EngineAndModulePath()"""
2044 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2045 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
2046
2047 try:
2048 iface.SetPKCS11EngineAndModulePath("foo", "bar")
2049 except dbus.exceptions.DBusException, e:
2050 if "Error.Failed: Reinit of the EAPOL" not in str(e):
2051 raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
2052
2053 try:
2054 iface.SetPKCS11EngineAndModulePath("foo", "")
2055 except dbus.exceptions.DBusException, e:
2056 if "Error.Failed: Reinit of the EAPOL" not in str(e):
2057 raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
2058
2059 iface.SetPKCS11EngineAndModulePath("", "bar")
2060 res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
2061 dbus_interface=dbus.PROPERTIES_IFACE)
2062 if res != "":
2063 raise Exception("Unexpected PKCS11EnginePath value: " + res)
2064 res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
2065 dbus_interface=dbus.PROPERTIES_IFACE)
2066 if res != "bar":
2067 raise Exception("Unexpected PKCS11ModulePath value: " + res)
2068
2069 iface.SetPKCS11EngineAndModulePath("", "")
2070 res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
2071 dbus_interface=dbus.PROPERTIES_IFACE)
2072 if res != "":
2073 raise Exception("Unexpected PKCS11EnginePath value: " + res)
2074 res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
2075 dbus_interface=dbus.PROPERTIES_IFACE)
2076 if res != "":
2077 raise Exception("Unexpected PKCS11ModulePath value: " + res)
2078
2079 def test_dbus_apscan(dev, apdev):
2080 """D-Bus Get/Set ApScan"""
2081 try:
2082 _test_dbus_apscan(dev, apdev)
2083 finally:
2084 dev[0].request("AP_SCAN 1")
2085
2086 def _test_dbus_apscan(dev, apdev):
2087 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2088
2089 res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
2090 dbus_interface=dbus.PROPERTIES_IFACE)
2091 if res != 1:
2092 raise Exception("Unexpected initial ApScan value: %d" % res)
2093
2094 for i in range(3):
2095 if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
2096 dbus_interface=dbus.PROPERTIES_IFACE)
2097 res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
2098 dbus_interface=dbus.PROPERTIES_IFACE)
2099 if res != i:
2100 raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
2101
2102 try:
2103 if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
2104 dbus_interface=dbus.PROPERTIES_IFACE)
2105 raise Exception("Invalid Set(ApScan,-1) accepted")
2106 except dbus.exceptions.DBusException, e:
2107 if "Error.Failed: wrong property type" not in str(e):
2108 raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
2109
2110 try:
2111 if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
2112 dbus_interface=dbus.PROPERTIES_IFACE)
2113 raise Exception("Invalid Set(ApScan,123) accepted")
2114 except dbus.exceptions.DBusException, e:
2115 if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
2116 raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
2117
2118 if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
2119 dbus_interface=dbus.PROPERTIES_IFACE)
2120
2121 def test_dbus_fastreauth(dev, apdev):
2122 """D-Bus Get/Set FastReauth"""
2123 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2124
2125 res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
2126 dbus_interface=dbus.PROPERTIES_IFACE)
2127 if res != True:
2128 raise Exception("Unexpected initial FastReauth value: " + str(res))
2129
2130 for i in [ False, True ]:
2131 if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
2132 dbus_interface=dbus.PROPERTIES_IFACE)
2133 res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
2134 dbus_interface=dbus.PROPERTIES_IFACE)
2135 if res != i:
2136 raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
2137
2138 try:
2139 if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
2140 dbus_interface=dbus.PROPERTIES_IFACE)
2141 raise Exception("Invalid Set(FastReauth,-1) accepted")
2142 except dbus.exceptions.DBusException, e:
2143 if "Error.Failed: wrong property type" not in str(e):
2144 raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
2145
2146 if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
2147 dbus_interface=dbus.PROPERTIES_IFACE)
2148
2149 def test_dbus_bss_expire(dev, apdev):
2150 """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
2151 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2152
2153 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
2154 dbus_interface=dbus.PROPERTIES_IFACE)
2155 res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
2156 dbus_interface=dbus.PROPERTIES_IFACE)
2157 if res != 179:
2158 raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
2159
2160 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
2161 dbus_interface=dbus.PROPERTIES_IFACE)
2162 res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
2163 dbus_interface=dbus.PROPERTIES_IFACE)
2164 if res != 3:
2165 raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
2166
2167 try:
2168 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
2169 dbus_interface=dbus.PROPERTIES_IFACE)
2170 raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
2171 except dbus.exceptions.DBusException, e:
2172 if "Error.Failed: wrong property type" not in str(e):
2173 raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
2174
2175 try:
2176 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
2177 dbus_interface=dbus.PROPERTIES_IFACE)
2178 raise Exception("Invalid Set(BSSExpireAge,9) accepted")
2179 except dbus.exceptions.DBusException, e:
2180 if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
2181 raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
2182
2183 try:
2184 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
2185 dbus_interface=dbus.PROPERTIES_IFACE)
2186 raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
2187 except dbus.exceptions.DBusException, e:
2188 if "Error.Failed: wrong property type" not in str(e):
2189 raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
2190
2191 try:
2192 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
2193 dbus_interface=dbus.PROPERTIES_IFACE)
2194 raise Exception("Invalid Set(BSSExpireCount,0) accepted")
2195 except dbus.exceptions.DBusException, e:
2196 if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
2197 raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
2198
2199 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
2200 dbus_interface=dbus.PROPERTIES_IFACE)
2201 if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
2202 dbus_interface=dbus.PROPERTIES_IFACE)
2203
2204 def test_dbus_country(dev, apdev):
2205 """D-Bus Get/Set Country"""
2206 try:
2207 _test_dbus_country(dev, apdev)
2208 finally:
2209 dev[0].request("SET country 00")
2210 subprocess.call(['iw', 'reg', 'set', '00'])
2211
2212 def _test_dbus_country(dev, apdev):
2213 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2214
2215 # work around issues with possible pending regdom event from the end of
2216 # the previous test case
2217 time.sleep(0.2)
2218 dev[0].dump_monitor()
2219
2220 if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
2221 dbus_interface=dbus.PROPERTIES_IFACE)
2222 res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
2223 dbus_interface=dbus.PROPERTIES_IFACE)
2224 if res != "FI":
2225 raise Exception("Unexpected Country value %s (expected FI)" % res)
2226
2227 ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
2228 if ev is None:
2229 # For now, work around separate P2P Device interface event delivery
2230 ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
2231 if ev is None:
2232 raise Exception("regdom change event not seen")
2233 if "init=USER type=COUNTRY alpha2=FI" not in ev:
2234 raise Exception("Unexpected event contents: " + ev)
2235
2236 try:
2237 if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
2238 dbus_interface=dbus.PROPERTIES_IFACE)
2239 raise Exception("Invalid Set(Country,-1) accepted")
2240 except dbus.exceptions.DBusException, e:
2241 if "Error.Failed: wrong property type" not in str(e):
2242 raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
2243
2244 try:
2245 if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
2246 dbus_interface=dbus.PROPERTIES_IFACE)
2247 raise Exception("Invalid Set(Country,F) accepted")
2248 except dbus.exceptions.DBusException, e:
2249 if "Error.Failed: invalid country code" not in str(e):
2250 raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
2251
2252 if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
2253 dbus_interface=dbus.PROPERTIES_IFACE)
2254
2255 ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
2256 if ev is None:
2257 # For now, work around separate P2P Device interface event delivery
2258 ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
2259 if ev is None:
2260 raise Exception("regdom change event not seen")
2261 if "init=CORE type=WORLD" not in ev:
2262 raise Exception("Unexpected event contents: " + ev)
2263
2264 def test_dbus_scan_interval(dev, apdev):
2265 """D-Bus Get/Set ScanInterval"""
2266 try:
2267 _test_dbus_scan_interval(dev, apdev)
2268 finally:
2269 dev[0].request("SCAN_INTERVAL 5")
2270
2271 def _test_dbus_scan_interval(dev, apdev):
2272 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2273
2274 if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
2275 dbus_interface=dbus.PROPERTIES_IFACE)
2276 res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
2277 dbus_interface=dbus.PROPERTIES_IFACE)
2278 if res != 3:
2279 raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
2280
2281 try:
2282 if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
2283 dbus_interface=dbus.PROPERTIES_IFACE)
2284 raise Exception("Invalid Set(ScanInterval,100) accepted")
2285 except dbus.exceptions.DBusException, e:
2286 if "Error.Failed: wrong property type" not in str(e):
2287 raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
2288
2289 try:
2290 if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
2291 dbus_interface=dbus.PROPERTIES_IFACE)
2292 raise Exception("Invalid Set(ScanInterval,-1) accepted")
2293 except dbus.exceptions.DBusException, e:
2294 if "Error.Failed: scan_interval must be >= 0" not in str(e):
2295 raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
2296
2297 if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
2298 dbus_interface=dbus.PROPERTIES_IFACE)
2299
2300 def test_dbus_probe_req_reporting(dev, apdev):
2301 """D-Bus Probe Request reporting"""
2302 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2303
2304 dev[1].p2p_find(social=True)
2305
2306 class TestDbusProbe(TestDbus):
2307 def __init__(self, bus):
2308 TestDbus.__init__(self, bus)
2309 self.reported = False
2310
2311 def __enter__(self):
2312 gobject.timeout_add(1, self.run_test)
2313 gobject.timeout_add(15000, self.timeout)
2314 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
2315 "GroupStarted")
2316 self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
2317 byte_arrays=True)
2318 self.loop.run()
2319 return self
2320
2321 def groupStarted(self, properties):
2322 logger.debug("groupStarted: " + str(properties))
2323 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
2324 properties['interface_object'])
2325 self.iface = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE)
2326 self.iface.SubscribeProbeReq()
2327 self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2328
2329 def probeRequest(self, args):
2330 logger.debug("probeRequest: args=%s" % str(args))
2331 self.reported = True
2332 self.loop.quit()
2333
2334 def run_test(self, *args):
2335 logger.debug("run_test")
2336 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2337 params = dbus.Dictionary({ 'frequency': 2412 })
2338 p2p.GroupAdd(params)
2339 return False
2340
2341 def success(self):
2342 return self.reported
2343
2344 with TestDbusProbe(bus) as t:
2345 if not t.success():
2346 raise Exception("Expected signals not seen")
2347 t.iface.UnsubscribeProbeReq()
2348 try:
2349 t.iface.UnsubscribeProbeReq()
2350 raise Exception("Invalid UnsubscribeProbeReq() accepted")
2351 except dbus.exceptions.DBusException, e:
2352 if "NoSubscription" not in str(e):
2353 raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
2354 t.group_p2p.Disconnect()
2355
2356 with TestDbusProbe(bus) as t:
2357 if not t.success():
2358 raise Exception("Expected signals not seen")
2359 # On purpose, leave ProbeReq subscription in place to test automatic
2360 # cleanup.
2361
2362 dev[1].p2p_stop_find()
2363
2364 def test_dbus_probe_req_reporting_oom(dev, apdev):
2365 """D-Bus Probe Request reporting (OOM)"""
2366 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2367 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
2368
2369 # Need to make sure this process has not already subscribed to avoid false
2370 # failures due to the operation succeeding due to os_strdup() not even
2371 # getting called.
2372 try:
2373 iface.UnsubscribeProbeReq()
2374 was_subscribed = True
2375 except dbus.exceptions.DBusException, e:
2376 was_subscribed = False
2377 pass
2378
2379 with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
2380 "SubscribeProbeReq"):
2381 iface.SubscribeProbeReq()
2382
2383 if was_subscribed:
2384 # On purpose, leave ProbeReq subscription in place to test automatic
2385 # cleanup.
2386 iface.SubscribeProbeReq()
2387
2388 def test_dbus_p2p_invalid(dev, apdev):
2389 """D-Bus invalid P2P operations"""
2390 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2391 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2392
2393 try:
2394 p2p.RejectPeer(path + "/Peers/00112233445566")
2395 raise Exception("Invalid RejectPeer accepted")
2396 except dbus.exceptions.DBusException, e:
2397 if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
2398 raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
2399
2400 try:
2401 p2p.RejectPeer("/foo")
2402 raise Exception("Invalid RejectPeer accepted")
2403 except dbus.exceptions.DBusException, e:
2404 if "InvalidArgs" not in str(e):
2405 raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
2406
2407 tests = [ { },
2408 { 'peer': 'foo' },
2409 { 'foo': "bar" },
2410 { 'iface': "abc" },
2411 { 'iface': 123 } ]
2412 for t in tests:
2413 try:
2414 p2p.RemoveClient(t)
2415 raise Exception("Invalid RemoveClient accepted")
2416 except dbus.exceptions.DBusException, e:
2417 if "InvalidArgs" not in str(e):
2418 raise Exception("Unexpected error message for invalid RemoveClient(): " + str(e))
2419
2420 tests = [ {'DiscoveryType': 'foo'},
2421 {'RequestedDeviceTypes': 'foo'},
2422 {'RequestedDeviceTypes': ['foo']},
2423 {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
2424 '10','11','12','13','14','15','16',
2425 '17']},
2426 {'RequestedDeviceTypes': dbus.Array([], signature="s")},
2427 {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
2428 {'RequestedDeviceTypes': dbus.Array([], signature="i")},
2429 {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
2430 dbus.ByteArray('1234567')]},
2431 {'Foo': dbus.Int16(1)},
2432 {'Foo': dbus.UInt16(1)},
2433 {'Foo': dbus.Int64(1)},
2434 {'Foo': dbus.UInt64(1)},
2435 {'Foo': dbus.Double(1.23)},
2436 {'Foo': dbus.Signature('s')},
2437 {'Foo': 'bar'}]
2438 for t in tests:
2439 try:
2440 p2p.Find(dbus.Dictionary(t))
2441 raise Exception("Invalid Find accepted")
2442 except dbus.exceptions.DBusException, e:
2443 if "InvalidArgs" not in str(e):
2444 raise Exception("Unexpected error message for invalid Find(): " + str(e))
2445
2446 for p in [ "/foo",
2447 "/fi/w1/wpa_supplicant1/Interfaces/1234",
2448 "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
2449 try:
2450 p2p.RemovePersistentGroup(dbus.ObjectPath(p))
2451 raise Exception("Invalid RemovePersistentGroup accepted")
2452 except dbus.exceptions.DBusException, e:
2453 if "InvalidArgs" not in str(e):
2454 raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
2455
2456 try:
2457 dev[0].request("P2P_SET disabled 1")
2458 p2p.Listen(5)
2459 raise Exception("Invalid Listen accepted")
2460 except dbus.exceptions.DBusException, e:
2461 if "UnknownError: Could not start P2P listen" not in str(e):
2462 raise Exception("Unexpected error message for invalid Listen: " + str(e))
2463 finally:
2464 dev[0].request("P2P_SET disabled 0")
2465
2466 test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
2467 test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2468 try:
2469 test_p2p.Listen("foo")
2470 raise Exception("Invalid Listen accepted")
2471 except dbus.exceptions.DBusException, e:
2472 if "InvalidArgs" not in str(e):
2473 raise Exception("Unexpected error message for invalid Listen: " + str(e))
2474
2475 try:
2476 dev[0].request("P2P_SET disabled 1")
2477 p2p.ExtendedListen(dbus.Dictionary({}))
2478 raise Exception("Invalid ExtendedListen accepted")
2479 except dbus.exceptions.DBusException, e:
2480 if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
2481 raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
2482 finally:
2483 dev[0].request("P2P_SET disabled 0")
2484
2485 try:
2486 dev[0].request("P2P_SET disabled 1")
2487 args = { 'duration1': 30000, 'interval1': 102400,
2488 'duration2': 20000, 'interval2': 102400 }
2489 p2p.PresenceRequest(args)
2490 raise Exception("Invalid PresenceRequest accepted")
2491 except dbus.exceptions.DBusException, e:
2492 if "UnknownError: Failed to invoke presence request" not in str(e):
2493 raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
2494 finally:
2495 dev[0].request("P2P_SET disabled 0")
2496
2497 try:
2498 params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
2499 p2p.GroupAdd(params)
2500 raise Exception("Invalid GroupAdd accepted")
2501 except dbus.exceptions.DBusException, e:
2502 if "InvalidArgs" not in str(e):
2503 raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
2504
2505 try:
2506 params = dbus.Dictionary({'persistent_group_object':
2507 dbus.ObjectPath(path),
2508 'frequency': 2412})
2509 p2p.GroupAdd(params)
2510 raise Exception("Invalid GroupAdd accepted")
2511 except dbus.exceptions.DBusException, e:
2512 if "InvalidArgs" not in str(e):
2513 raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
2514
2515 try:
2516 p2p.Disconnect()
2517 raise Exception("Invalid Disconnect accepted")
2518 except dbus.exceptions.DBusException, e:
2519 if "UnknownError: failed to disconnect" not in str(e):
2520 raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
2521
2522 try:
2523 dev[0].request("P2P_SET disabled 1")
2524 p2p.Flush()
2525 raise Exception("Invalid Flush accepted")
2526 except dbus.exceptions.DBusException, e:
2527 if "Error.Failed: P2P is not available for this interface" not in str(e):
2528 raise Exception("Unexpected error message for invalid Flush: " + str(e))
2529 finally:
2530 dev[0].request("P2P_SET disabled 0")
2531
2532 try:
2533 dev[0].request("P2P_SET disabled 1")
2534 args = { 'peer': path,
2535 'join': True,
2536 'wps_method': 'pbc',
2537 'frequency': 2412 }
2538 pin = p2p.Connect(args)
2539 raise Exception("Invalid Connect accepted")
2540 except dbus.exceptions.DBusException, e:
2541 if "Error.Failed: P2P is not available for this interface" not in str(e):
2542 raise Exception("Unexpected error message for invalid Connect: " + str(e))
2543 finally:
2544 dev[0].request("P2P_SET disabled 0")
2545
2546 tests = [ { 'frequency': dbus.Int32(-1) },
2547 { 'wps_method': 'pbc' },
2548 { 'wps_method': 'foo' } ]
2549 for args in tests:
2550 try:
2551 pin = p2p.Connect(args)
2552 raise Exception("Invalid Connect accepted")
2553 except dbus.exceptions.DBusException, e:
2554 if "InvalidArgs" not in str(e):
2555 raise Exception("Unexpected error message for invalid Connect: " + str(e))
2556
2557 try:
2558 dev[0].request("P2P_SET disabled 1")
2559 args = { 'peer': path }
2560 pin = p2p.Invite(args)
2561 raise Exception("Invalid Invite accepted")
2562 except dbus.exceptions.DBusException, e:
2563 if "Error.Failed: P2P is not available for this interface" not in str(e):
2564 raise Exception("Unexpected error message for invalid Invite: " + str(e))
2565 finally:
2566 dev[0].request("P2P_SET disabled 0")
2567
2568 try:
2569 args = { 'foo': 'bar' }
2570 pin = p2p.Invite(args)
2571 raise Exception("Invalid Invite accepted")
2572 except dbus.exceptions.DBusException, e:
2573 if "InvalidArgs" not in str(e):
2574 raise Exception("Unexpected error message for invalid Connect: " + str(e))
2575
2576 tests = [ (path, 'display', "InvalidArgs"),
2577 (dbus.ObjectPath(path + "/Peers/00112233445566"),
2578 'display',
2579 "UnknownError: Failed to send provision discovery request"),
2580 (dbus.ObjectPath(path + "/Peers/00112233445566"),
2581 'keypad',
2582 "UnknownError: Failed to send provision discovery request"),
2583 (dbus.ObjectPath(path + "/Peers/00112233445566"),
2584 'pbc',
2585 "UnknownError: Failed to send provision discovery request"),
2586 (dbus.ObjectPath(path + "/Peers/00112233445566"),
2587 'pushbutton',
2588 "UnknownError: Failed to send provision discovery request"),
2589 (dbus.ObjectPath(path + "/Peers/00112233445566"),
2590 'foo', "InvalidArgs") ]
2591 for (p,method,err) in tests:
2592 try:
2593 p2p.ProvisionDiscoveryRequest(p, method)
2594 raise Exception("Invalid ProvisionDiscoveryRequest accepted")
2595 except dbus.exceptions.DBusException, e:
2596 if err not in str(e):
2597 raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
2598
2599 try:
2600 dev[0].request("P2P_SET disabled 1")
2601 if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
2602 dbus_interface=dbus.PROPERTIES_IFACE)
2603 raise Exception("Invalid Get(Peers) accepted")
2604 except dbus.exceptions.DBusException, e:
2605 if "Error.Failed: P2P is not available for this interface" not in str(e):
2606 raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
2607 finally:
2608 dev[0].request("P2P_SET disabled 0")
2609
2610 def test_dbus_p2p_oom(dev, apdev):
2611 """D-Bus P2P operations and OOM"""
2612 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2613 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2614
2615 with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
2616 "Find", "InvalidArgs"):
2617 p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
2618
2619 with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
2620 "Find", "InvalidArgs"):
2621 p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
2622
2623 with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
2624 "Find", "InvalidArgs"):
2625 p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
2626
2627 with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
2628 "Find", "InvalidArgs"):
2629 p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
2630
2631 with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
2632 "Find", "InvalidArgs"):
2633 p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
2634
2635 with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
2636 "Find", "InvalidArgs"):
2637 p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
2638 dbus.ByteArray('123'),
2639 dbus.ByteArray('123'),
2640 dbus.ByteArray('123'),
2641 dbus.ByteArray('123'),
2642 dbus.ByteArray('123'),
2643 dbus.ByteArray('123'),
2644 dbus.ByteArray('123'),
2645 dbus.ByteArray('123'),
2646 dbus.ByteArray('123'),
2647 dbus.ByteArray('123') ] }))
2648
2649 with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
2650 "Find", "InvalidArgs"):
2651 p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
2652
2653 with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
2654 "Find", "InvalidArgs"):
2655 p2p.Find(dbus.Dictionary({ 'Foo': path }))
2656
2657 with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
2658 "AddService", "InvalidArgs"):
2659 args = { 'service_type': 'bonjour',
2660 'response': dbus.ByteArray(500*'b') }
2661 p2p.AddService(args)
2662
2663 with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
2664 "AddService", "InvalidArgs"):
2665 p2p.AddService(args)
2666
2667 def test_dbus_p2p_discovery(dev, apdev):
2668 """D-Bus P2P discovery"""
2669 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2670 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2671
2672 addr0 = dev[0].p2p_dev_addr()
2673
2674 dev[1].request("SET sec_device_type 1-0050F204-2")
2675 dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
2676 dev[1].p2p_listen()
2677 addr1 = dev[1].p2p_dev_addr()
2678 a1 = binascii.unhexlify(addr1.replace(':',''))
2679
2680 wfd_devinfo = "00001c440028"
2681 dev[2].request("SET wifi_display 1")
2682 dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
2683 wfd = binascii.unhexlify('000006' + wfd_devinfo)
2684 dev[2].p2p_listen()
2685 addr2 = dev[2].p2p_dev_addr()
2686 a2 = binascii.unhexlify(addr2.replace(':',''))
2687
2688 res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
2689 dbus_interface=dbus.PROPERTIES_IFACE)
2690 if 'Peers' not in res:
2691 raise Exception("GetAll result missing Peers")
2692 if len(res['Peers']) != 0:
2693 raise Exception("Unexpected peer(s) in the list")
2694
2695 args = {'DiscoveryType': 'social',
2696 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
2697 'Timeout': dbus.Int32(1) }
2698 p2p.Find(dbus.Dictionary(args))
2699 p2p.StopFind()
2700
2701 class TestDbusP2p(TestDbus):
2702 def __init__(self, bus):
2703 TestDbus.__init__(self, bus)
2704 self.found = False
2705 self.found2 = False
2706 self.lost = False
2707 self.find_stopped = False
2708
2709 def __enter__(self):
2710 gobject.timeout_add(1, self.run_test)
2711 gobject.timeout_add(15000, self.timeout)
2712 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
2713 "DeviceFound")
2714 self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
2715 "DeviceLost")
2716 self.add_signal(self.provisionDiscoveryResponseEnterPin,
2717 WPAS_DBUS_IFACE_P2PDEVICE,
2718 "ProvisionDiscoveryResponseEnterPin")
2719 self.add_signal(self.findStopped, WPAS_DBUS_IFACE_P2PDEVICE,
2720 "FindStopped")
2721 self.loop.run()
2722 return self
2723
2724 def deviceFound(self, path):
2725 logger.debug("deviceFound: path=%s" % path)
2726 res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
2727 dbus_interface=dbus.PROPERTIES_IFACE)
2728 if len(res) < 1:
2729 raise Exception("Unexpected number of peers")
2730 if path not in res:
2731 raise Exception("Mismatch in peer object path")
2732 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
2733 res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
2734 dbus_interface=dbus.PROPERTIES_IFACE,
2735 byte_arrays=True)
2736 logger.debug("peer properties: " + str(res))
2737
2738 if res['DeviceAddress'] == a1:
2739 if 'SecondaryDeviceTypes' not in res:
2740 raise Exception("Missing SecondaryDeviceTypes")
2741 sec = res['SecondaryDeviceTypes']
2742 if len(sec) < 1:
2743 raise Exception("Secondary device type missing")
2744 if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
2745 raise Exception("Secondary device type mismatch")
2746
2747 if 'VendorExtension' not in res:
2748 raise Exception("Missing VendorExtension")
2749 vendor = res['VendorExtension']
2750 if len(vendor) < 1:
2751 raise Exception("Vendor extension missing")
2752 if "\x11\x22\x33\x44" not in vendor:
2753 raise Exception("Secondary device type mismatch")
2754
2755 self.found = True
2756 elif res['DeviceAddress'] == a2:
2757 if 'IEs' not in res:
2758 raise Exception("IEs missing")
2759 if res['IEs'] != wfd:
2760 raise Exception("IEs mismatch")
2761 self.found2 = True
2762 else:
2763 raise Exception("Unexpected peer device address")
2764
2765 if self.found and self.found2:
2766 p2p.StopFind()
2767 p2p.RejectPeer(path)
2768 p2p.ProvisionDiscoveryRequest(path, 'display')
2769
2770 def deviceLost(self, path):
2771 logger.debug("deviceLost: path=%s" % path)
2772 self.lost = True
2773 try:
2774 p2p.RejectPeer(path)
2775 raise Exception("Invalid RejectPeer accepted")
2776 except dbus.exceptions.DBusException, e:
2777 if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
2778 raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
2779 self.loop.quit()
2780
2781 def provisionDiscoveryResponseEnterPin(self, peer_object):
2782 logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
2783 p2p.Flush()
2784
2785 def findStopped(self):
2786 logger.debug("findStopped")
2787 self.find_stopped = True
2788
2789 def run_test(self, *args):
2790 logger.debug("run_test")
2791 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
2792 'Timeout': dbus.Int32(10)}))
2793 return False
2794
2795 def success(self):
2796 return self.found and self.lost and self.found2 and self.find_stopped
2797
2798 with TestDbusP2p(bus) as t:
2799 if not t.success():
2800 raise Exception("Expected signals not seen")
2801
2802 dev[1].request("VENDOR_ELEM_REMOVE 1 *")
2803 dev[1].p2p_stop_find()
2804
2805 p2p.Listen(1)
2806 dev[2].p2p_stop_find()
2807 dev[2].request("P2P_FLUSH")
2808 if not dev[2].discover_peer(addr0):
2809 raise Exception("Peer not found")
2810 p2p.StopFind()
2811 dev[2].p2p_stop_find()
2812
2813 try:
2814 p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
2815 raise Exception("Invalid ExtendedListen accepted")
2816 except dbus.exceptions.DBusException, e:
2817 if "InvalidArgs" not in str(e):
2818 raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
2819
2820 p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
2821 p2p.ExtendedListen(dbus.Dictionary({}))
2822 dev[0].global_request("P2P_EXT_LISTEN")
2823
2824 def test_dbus_p2p_service_discovery(dev, apdev):
2825 """D-Bus P2P service discovery"""
2826 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2827 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2828
2829 addr0 = dev[0].p2p_dev_addr()
2830 addr1 = dev[1].p2p_dev_addr()
2831
2832 bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
2833 bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
2834
2835 args = { 'service_type': 'bonjour',
2836 'query': bonjour_query,
2837 'response': bonjour_response }
2838 p2p.AddService(args)
2839 p2p.FlushService()
2840 p2p.AddService(args)
2841
2842 try:
2843 p2p.DeleteService(args)
2844 raise Exception("Invalid DeleteService() accepted")
2845 except dbus.exceptions.DBusException, e:
2846 if "InvalidArgs" not in str(e):
2847 raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
2848
2849 args = { 'service_type': 'bonjour',
2850 'query': bonjour_query }
2851 p2p.DeleteService(args)
2852 try:
2853 p2p.DeleteService(args)
2854 raise Exception("Invalid DeleteService() accepted")
2855 except dbus.exceptions.DBusException, e:
2856 if "InvalidArgs" not in str(e):
2857 raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
2858
2859 args = { 'service_type': 'upnp',
2860 'version': 0x10,
2861 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
2862 p2p.AddService(args)
2863 p2p.DeleteService(args)
2864 try:
2865 p2p.DeleteService(args)
2866 raise Exception("Invalid DeleteService() accepted")
2867 except dbus.exceptions.DBusException, e:
2868 if "InvalidArgs" not in str(e):
2869 raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
2870
2871 tests = [ { 'service_type': 'foo' },
2872 { 'service_type': 'foo', 'query': bonjour_query },
2873 { 'service_type': 'upnp' },
2874 { 'service_type': 'upnp', 'version': 0x10 },
2875 { 'service_type': 'upnp',
2876 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
2877 { 'version': 0x10,
2878 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
2879 { 'service_type': 'upnp', 'foo': 'bar' },
2880 { 'service_type': 'bonjour' },
2881 { 'service_type': 'bonjour', 'query': 'foo' },
2882 { 'service_type': 'bonjour', 'foo': 'bar' } ]
2883 for args in tests:
2884 try:
2885 p2p.DeleteService(args)
2886 raise Exception("Invalid DeleteService() accepted")
2887 except dbus.exceptions.DBusException, e:
2888 if "InvalidArgs" not in str(e):
2889 raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
2890
2891 tests = [ { 'service_type': 'foo' },
2892 { 'service_type': 'upnp' },
2893 { 'service_type': 'upnp', 'version': 0x10 },
2894 { 'service_type': 'upnp',
2895 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
2896 { 'version': 0x10,
2897 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
2898 { 'service_type': 'upnp', 'foo': 'bar' },
2899 { 'service_type': 'bonjour' },
2900 { 'service_type': 'bonjour', 'query': 'foo' },
2901 { 'service_type': 'bonjour', 'response': 'foo' },
2902 { 'service_type': 'bonjour', 'query': bonjour_query },
2903 { 'service_type': 'bonjour', 'response': bonjour_response },
2904 { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
2905 { 'service_type': 'bonjour', 'foo': 'bar' } ]
2906 for args in tests:
2907 try:
2908 p2p.AddService(args)
2909 raise Exception("Invalid AddService() accepted")
2910 except dbus.exceptions.DBusException, e:
2911 if "InvalidArgs" not in str(e):
2912 raise Exception("Unexpected error message for invalid AddService(): " + str(e))
2913
2914 args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
2915 ref = p2p.ServiceDiscoveryRequest(args)
2916 p2p.ServiceDiscoveryCancelRequest(ref)
2917 try:
2918 p2p.ServiceDiscoveryCancelRequest(ref)
2919 raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
2920 except dbus.exceptions.DBusException, e:
2921 if "InvalidArgs" not in str(e):
2922 raise Exception("Unexpected error message for invalid AddService(): " + str(e))
2923 try:
2924 p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
2925 raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
2926 except dbus.exceptions.DBusException, e:
2927 if "InvalidArgs" not in str(e):
2928 raise Exception("Unexpected error message for invalid AddService(): " + str(e))
2929
2930 args = { 'service_type': 'upnp',
2931 'version': 0x10,
2932 'service': 'ssdp:foo' }
2933 ref = p2p.ServiceDiscoveryRequest(args)
2934 p2p.ServiceDiscoveryCancelRequest(ref)
2935
2936 tests = [ { 'service_type': 'foo' },
2937 { 'foo': 'bar' },
2938 { 'tlv': 'foo' },
2939 { },
2940 { 'version': 0 },
2941 { 'service_type': 'upnp',
2942 'service': 'ssdp:foo' },
2943 { 'service_type': 'upnp',
2944 'version': 0x10 },
2945 { 'service_type': 'upnp',
2946 'version': 0x10,
2947 'service': 'ssdp:foo',
2948 'peer_object': dbus.ObjectPath(path + "/Peers") },
2949 { 'service_type': 'upnp',
2950 'version': 0x10,
2951 'service': 'ssdp:foo',
2952 'peer_object': path + "/Peers" },
2953 { 'service_type': 'upnp',
2954 'version': 0x10,
2955 'service': 'ssdp:foo',
2956 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
2957 for args in tests:
2958 try:
2959 p2p.ServiceDiscoveryRequest(args)
2960 raise Exception("Invalid ServiceDiscoveryRequest accepted")
2961 except dbus.exceptions.DBusException, e:
2962 if "InvalidArgs" not in str(e):
2963 raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
2964
2965 args = { 'foo': 'bar' }
2966 try:
2967 p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
2968 raise Exception("Invalid ServiceDiscoveryResponse accepted")
2969 except dbus.exceptions.DBusException, e:
2970 if "InvalidArgs" not in str(e):
2971 raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
2972
2973 def test_dbus_p2p_service_discovery_query(dev, apdev):
2974 """D-Bus P2P service discovery query"""
2975 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
2976 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
2977
2978 addr0 = dev[0].p2p_dev_addr()
2979 dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
2980 dev[1].p2p_listen()
2981 addr1 = dev[1].p2p_dev_addr()
2982
2983 class TestDbusP2p(TestDbus):
2984 def __init__(self, bus):
2985 TestDbus.__init__(self, bus)
2986 self.done = False
2987
2988 def __enter__(self):
2989 gobject.timeout_add(1, self.run_test)
2990 gobject.timeout_add(15000, self.timeout)
2991 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
2992 "DeviceFound")
2993 self.add_signal(self.serviceDiscoveryResponse,
2994 WPAS_DBUS_IFACE_P2PDEVICE,
2995 "ServiceDiscoveryResponse", byte_arrays=True)
2996 self.loop.run()
2997 return self
2998
2999 def deviceFound(self, path):
3000 logger.debug("deviceFound: path=%s" % path)
3001 args = { 'peer_object': path,
3002 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
3003 p2p.ServiceDiscoveryRequest(args)
3004
3005 def serviceDiscoveryResponse(self, sd_request):
3006 logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
3007 self.done = True
3008 self.loop.quit()
3009
3010 def run_test(self, *args):
3011 logger.debug("run_test")
3012 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
3013 'Timeout': dbus.Int32(10)}))
3014 return False
3015
3016 def success(self):
3017 return self.done
3018
3019 with TestDbusP2p(bus) as t:
3020 if not t.success():
3021 raise Exception("Expected signals not seen")
3022
3023 dev[1].p2p_stop_find()
3024
3025 def test_dbus_p2p_service_discovery_external(dev, apdev):
3026 """D-Bus P2P service discovery with external response"""
3027 try:
3028 _test_dbus_p2p_service_discovery_external(dev, apdev)
3029 finally:
3030 dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
3031
3032 def _test_dbus_p2p_service_discovery_external(dev, apdev):
3033 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3034 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3035
3036 addr0 = dev[0].p2p_dev_addr()
3037 addr1 = dev[1].p2p_dev_addr()
3038 resp = "0300000101"
3039
3040 dev[1].request("P2P_FLUSH")
3041 dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
3042 dev[1].p2p_find(social=True)
3043
3044 class TestDbusP2p(TestDbus):
3045 def __init__(self, bus):
3046 TestDbus.__init__(self, bus)
3047 self.sd = False
3048
3049 def __enter__(self):
3050 gobject.timeout_add(1, self.run_test)
3051 gobject.timeout_add(15000, self.timeout)
3052 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3053 "DeviceFound")
3054 self.add_signal(self.serviceDiscoveryRequest,
3055 WPAS_DBUS_IFACE_P2PDEVICE,
3056 "ServiceDiscoveryRequest")
3057 self.loop.run()
3058 return self
3059
3060 def deviceFound(self, path):
3061 logger.debug("deviceFound: path=%s" % path)
3062
3063 def serviceDiscoveryRequest(self, sd_request):
3064 logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
3065 self.sd = True
3066 args = { 'peer_object': sd_request['peer_object'],
3067 'frequency': sd_request['frequency'],
3068 'dialog_token': sd_request['dialog_token'],
3069 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
3070 p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
3071 self.loop.quit()
3072
3073 def run_test(self, *args):
3074 logger.debug("run_test")
3075 p2p.ServiceDiscoveryExternal(1)
3076 p2p.ServiceUpdate()
3077 p2p.Listen(15)
3078 return False
3079
3080 def success(self):
3081 return self.sd
3082
3083 with TestDbusP2p(bus) as t:
3084 if not t.success():
3085 raise Exception("Expected signals not seen")
3086
3087 ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
3088 if ev is None:
3089 raise Exception("Service discovery timed out")
3090 if addr0 not in ev:
3091 raise Exception("Unexpected address in SD Response: " + ev)
3092 if ev.split(' ')[4] != resp:
3093 raise Exception("Unexpected response data SD Response: " + ev)
3094 dev[1].p2p_stop_find()
3095
3096 p2p.StopFind()
3097 p2p.ServiceDiscoveryExternal(0)
3098
3099 def test_dbus_p2p_autogo(dev, apdev):
3100 """D-Bus P2P autonomous GO"""
3101 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3102 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3103
3104 addr0 = dev[0].p2p_dev_addr()
3105
3106 class TestDbusP2p(TestDbus):
3107 def __init__(self, bus):
3108 TestDbus.__init__(self, bus)
3109 self.first = True
3110 self.waiting_end = False
3111 self.exceptions = False
3112 self.deauthorized = False
3113 self.done = False
3114
3115 def __enter__(self):
3116 gobject.timeout_add(1, self.run_test)
3117 gobject.timeout_add(15000, self.timeout)
3118 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3119 "DeviceFound")
3120 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3121 "GroupStarted")
3122 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3123 "GroupFinished")
3124 self.add_signal(self.persistentGroupAdded,
3125 WPAS_DBUS_IFACE_P2PDEVICE,
3126 "PersistentGroupAdded")
3127 self.add_signal(self.persistentGroupRemoved,
3128 WPAS_DBUS_IFACE_P2PDEVICE,
3129 "PersistentGroupRemoved")
3130 self.add_signal(self.provisionDiscoveryRequestDisplayPin,
3131 WPAS_DBUS_IFACE_P2PDEVICE,
3132 "ProvisionDiscoveryRequestDisplayPin")
3133 self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
3134 "StaAuthorized")
3135 self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
3136 "StaDeauthorized")
3137 self.loop.run()
3138 return self
3139
3140 def groupStarted(self, properties):
3141 logger.debug("groupStarted: " + str(properties))
3142 self.group = properties['group_object']
3143 self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3144 properties['interface_object'])
3145 role = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
3146 dbus_interface=dbus.PROPERTIES_IFACE)
3147 if role != "GO":
3148 self.exceptions = True
3149 raise Exception("Unexpected role reported: " + role)
3150 group = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
3151 dbus_interface=dbus.PROPERTIES_IFACE)
3152 if group != properties['group_object']:
3153 self.exceptions = True
3154 raise Exception("Unexpected Group reported: " + str(group))
3155 go = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
3156 dbus_interface=dbus.PROPERTIES_IFACE)
3157 if go != '/':
3158 self.exceptions = True
3159 raise Exception("Unexpected PeerGO value: " + str(go))
3160 if self.first:
3161 self.first = False
3162 logger.info("Remove persistent group instance")
3163 group_p2p = dbus.Interface(self.g_if_obj,
3164 WPAS_DBUS_IFACE_P2PDEVICE)
3165 group_p2p.Disconnect()
3166 else:
3167 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3168 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
3169
3170 def groupFinished(self, properties):
3171 logger.debug("groupFinished: " + str(properties))
3172 if self.waiting_end:
3173 logger.info("Remove persistent group")
3174 p2p.RemovePersistentGroup(self.persistent)
3175 else:
3176 logger.info("Re-start persistent group")
3177 params = dbus.Dictionary({'persistent_group_object':
3178 self.persistent,
3179 'frequency': 2412})
3180 p2p.GroupAdd(params)
3181
3182 def persistentGroupAdded(self, path, properties):
3183 logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
3184 self.persistent = path
3185
3186 def persistentGroupRemoved(self, path):
3187 logger.debug("persistentGroupRemoved: %s" % path)
3188 self.done = True
3189 self.loop.quit()
3190
3191 def deviceFound(self, path):
3192 logger.debug("deviceFound: path=%s" % path)
3193 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
3194 self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
3195 dbus_interface=dbus.PROPERTIES_IFACE,
3196 byte_arrays=True)
3197 logger.debug('peer properties: ' + str(self.peer))
3198
3199 def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
3200 logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
3201 self.peer_path = peer_object
3202 peer = binascii.unhexlify(peer_object.split('/')[-1])
3203 addr = ""
3204 for p in peer:
3205 if len(addr) > 0:
3206 addr += ':'
3207 addr += '%02x' % ord(p)
3208
3209 params = { 'Role': 'registrar',
3210 'P2PDeviceAddress': self.peer['DeviceAddress'],
3211 'Bssid': self.peer['DeviceAddress'],
3212 'Type': 'pin' }
3213 wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
3214 try:
3215 wps.Start(params)
3216 self.exceptions = True
3217 raise Exception("Invalid WPS.Start() accepted")
3218 except dbus.exceptions.DBusException, e:
3219 if "InvalidArgs" not in str(e):
3220 self.exceptions = True
3221 raise Exception("Unexpected error message: " + str(e))
3222 params = { 'Role': 'registrar',
3223 'P2PDeviceAddress': self.peer['DeviceAddress'],
3224 'Type': 'pin',
3225 'Pin': '12345670' }
3226 logger.info("Authorize peer to connect to the group")
3227 wps.Start(params)
3228
3229 def staAuthorized(self, name):
3230 logger.debug("staAuthorized: " + name)
3231 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
3232 res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
3233 dbus_interface=dbus.PROPERTIES_IFACE,
3234 byte_arrays=True)
3235 logger.debug("Peer properties: " + str(res))
3236 if 'Groups' not in res or len(res['Groups']) != 1:
3237 self.exceptions = True
3238 raise Exception("Unexpected number of peer Groups entries")
3239 if res['Groups'][0] != self.group:
3240 self.exceptions = True
3241 raise Exception("Unexpected peer Groups[0] value")
3242
3243 g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
3244 res = g_obj.GetAll(WPAS_DBUS_GROUP,
3245 dbus_interface=dbus.PROPERTIES_IFACE,
3246 byte_arrays=True)
3247 logger.debug("Group properties: " + str(res))
3248 if 'Members' not in res or len(res['Members']) != 1:
3249 self.exceptions = True
3250 raise Exception("Unexpected number of group members")
3251
3252 ext = dbus.ByteArray("\x11\x22\x33\x44")
3253 # Earlier implementation of this interface was a bit strange. The
3254 # property is defined to have aay signature and that is what the
3255 # getter returned. However, the setter expected there to be a
3256 # dictionary with 'WPSVendorExtensions' as the key surrounding these
3257 # values.. The current implementations maintains support for that
3258 # for backwards compability reasons. Verify that encoding first.
3259 vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
3260 signature='sv')
3261 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
3262 dbus_interface=dbus.PROPERTIES_IFACE)
3263 res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
3264 dbus_interface=dbus.PROPERTIES_IFACE,
3265 byte_arrays=True)
3266 if len(res) != 1:
3267 self.exceptions = True
3268 raise Exception("Unexpected number of vendor extensions")
3269 if res[0] != ext:
3270 self.exceptions = True
3271 raise Exception("Vendor extension value changed")
3272
3273 # And now verify that the more appropriate encoding is accepted as
3274 # well.
3275 res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
3276 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
3277 dbus_interface=dbus.PROPERTIES_IFACE)
3278 res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
3279 dbus_interface=dbus.PROPERTIES_IFACE,
3280 byte_arrays=True)
3281 if len(res) != 2:
3282 self.exceptions = True
3283 raise Exception("Unexpected number of vendor extensions")
3284 if res[0] != res2[0] or res[1] != res2[1]:
3285 self.exceptions = True
3286 raise Exception("Vendor extension value changed")
3287
3288 for i in range(10):
3289 res.append(dbus.ByteArray('\xaa\xbb'))
3290 try:
3291 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
3292 dbus_interface=dbus.PROPERTIES_IFACE)
3293 self.exceptions = True
3294 raise Exception("Invalid Set(WPSVendorExtensions) accepted")
3295 except dbus.exceptions.DBusException, e:
3296 if "Error.Failed" not in str(e):
3297 self.exceptions = True
3298 raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
3299
3300 vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
3301 try:
3302 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
3303 dbus_interface=dbus.PROPERTIES_IFACE)
3304 self.exceptions = True
3305 raise Exception("Invalid Set(WPSVendorExtensions) accepted")
3306 except dbus.exceptions.DBusException, e:
3307 if "InvalidArgs" not in str(e):
3308 self.exceptions = True
3309 raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
3310
3311 vals = [ "foo" ]
3312 try:
3313 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
3314 dbus_interface=dbus.PROPERTIES_IFACE)
3315 self.exceptions = True
3316 raise Exception("Invalid Set(WPSVendorExtensions) accepted")
3317 except dbus.exceptions.DBusException, e:
3318 if "Error.Failed" not in str(e):
3319 self.exceptions = True
3320 raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
3321
3322 vals = [ [ "foo" ] ]
3323 try:
3324 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
3325 dbus_interface=dbus.PROPERTIES_IFACE)
3326 self.exceptions = True
3327 raise Exception("Invalid Set(WPSVendorExtensions) accepted")
3328 except dbus.exceptions.DBusException, e:
3329 if "Error.Failed" not in str(e):
3330 self.exceptions = True
3331 raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
3332
3333 p2p.RemoveClient({ 'peer': self.peer_path })
3334
3335 self.waiting_end = True
3336 group_p2p = dbus.Interface(self.g_if_obj,
3337 WPAS_DBUS_IFACE_P2PDEVICE)
3338 group_p2p.Disconnect()
3339
3340 def staDeauthorized(self, name):
3341 logger.debug("staDeauthorized: " + name)
3342 self.deauthorized = True
3343
3344 def run_test(self, *args):
3345 logger.debug("run_test")
3346 params = dbus.Dictionary({'persistent': True,
3347 'frequency': 2412})
3348 logger.info("Add a persistent group")
3349 p2p.GroupAdd(params)
3350 return False
3351
3352 def success(self):
3353 return self.done and self.deauthorized and not self.exceptions
3354
3355 with TestDbusP2p(bus) as t:
3356 if not t.success():
3357 raise Exception("Expected signals not seen")
3358
3359 dev[1].wait_go_ending_session()
3360
3361 def test_dbus_p2p_autogo_pbc(dev, apdev):
3362 """D-Bus P2P autonomous GO and PBC"""
3363 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3364 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3365
3366 addr0 = dev[0].p2p_dev_addr()
3367
3368 class TestDbusP2p(TestDbus):
3369 def __init__(self, bus):
3370 TestDbus.__init__(self, bus)
3371 self.first = True
3372 self.waiting_end = False
3373 self.done = False
3374
3375 def __enter__(self):
3376 gobject.timeout_add(1, self.run_test)
3377 gobject.timeout_add(15000, self.timeout)
3378 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3379 "DeviceFound")
3380 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3381 "GroupStarted")
3382 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3383 "GroupFinished")
3384 self.add_signal(self.provisionDiscoveryPBCRequest,
3385 WPAS_DBUS_IFACE_P2PDEVICE,
3386 "ProvisionDiscoveryPBCRequest")
3387 self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
3388 "StaAuthorized")
3389 self.loop.run()
3390 return self
3391
3392 def groupStarted(self, properties):
3393 logger.debug("groupStarted: " + str(properties))
3394 self.group = properties['group_object']
3395 self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3396 properties['interface_object'])
3397 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3398 dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
3399
3400 def groupFinished(self, properties):
3401 logger.debug("groupFinished: " + str(properties))
3402 self.done = True
3403 self.loop.quit()
3404
3405 def deviceFound(self, path):
3406 logger.debug("deviceFound: path=%s" % path)
3407 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
3408 self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
3409 dbus_interface=dbus.PROPERTIES_IFACE,
3410 byte_arrays=True)
3411 logger.debug('peer properties: ' + str(self.peer))
3412
3413 def provisionDiscoveryPBCRequest(self, peer_object):
3414 logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
3415 self.peer_path = peer_object
3416 peer = binascii.unhexlify(peer_object.split('/')[-1])
3417 addr = ""
3418 for p in peer:
3419 if len(addr) > 0:
3420 addr += ':'
3421 addr += '%02x' % ord(p)
3422 params = { 'Role': 'registrar',
3423 'P2PDeviceAddress': self.peer['DeviceAddress'],
3424 'Type': 'pbc' }
3425 logger.info("Authorize peer to connect to the group")
3426 wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
3427 wps.Start(params)
3428
3429 def staAuthorized(self, name):
3430 logger.debug("staAuthorized: " + name)
3431 group_p2p = dbus.Interface(self.g_if_obj,
3432 WPAS_DBUS_IFACE_P2PDEVICE)
3433 group_p2p.Disconnect()
3434
3435 def run_test(self, *args):
3436 logger.debug("run_test")
3437 params = dbus.Dictionary({'frequency': 2412})
3438 p2p.GroupAdd(params)
3439 return False
3440
3441 def success(self):
3442 return self.done
3443
3444 with TestDbusP2p(bus) as t:
3445 if not t.success():
3446 raise Exception("Expected signals not seen")
3447
3448 dev[1].wait_go_ending_session()
3449 dev[1].flush_scan_cache()
3450
3451 def test_dbus_p2p_autogo_legacy(dev, apdev):
3452 """D-Bus P2P autonomous GO and legacy STA"""
3453 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3454 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3455
3456 addr0 = dev[0].p2p_dev_addr()
3457
3458 class TestDbusP2p(TestDbus):
3459 def __init__(self, bus):
3460 TestDbus.__init__(self, bus)
3461 self.done = False
3462
3463 def __enter__(self):
3464 gobject.timeout_add(1, self.run_test)
3465 gobject.timeout_add(15000, self.timeout)
3466 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3467 "GroupStarted")
3468 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3469 "GroupFinished")
3470 self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
3471 "StaAuthorized")
3472 self.loop.run()
3473 return self
3474
3475 def groupStarted(self, properties):
3476 logger.debug("groupStarted: " + str(properties))
3477 g_obj = bus.get_object(WPAS_DBUS_SERVICE,
3478 properties['group_object'])
3479 res = g_obj.GetAll(WPAS_DBUS_GROUP,
3480 dbus_interface=dbus.PROPERTIES_IFACE,
3481 byte_arrays=True)
3482 bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
3483
3484 pin = '12345670'
3485 params = { 'Role': 'enrollee',
3486 'Type': 'pin',
3487 'Pin': pin }
3488 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3489 properties['interface_object'])
3490 wps = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_WPS)
3491 wps.Start(params)
3492 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3493 dev1.scan_for_bss(bssid, freq=2412)
3494 dev1.request("WPS_PIN " + bssid + " " + pin)
3495 self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3496
3497 def groupFinished(self, properties):
3498 logger.debug("groupFinished: " + str(properties))
3499 self.done = True
3500 self.loop.quit()
3501
3502 def staAuthorized(self, name):
3503 logger.debug("staAuthorized: " + name)
3504 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3505 dev1.request("DISCONNECT")
3506 self.group_p2p.Disconnect()
3507
3508 def run_test(self, *args):
3509 logger.debug("run_test")
3510 params = dbus.Dictionary({'frequency': 2412})
3511 p2p.GroupAdd(params)
3512 return False
3513
3514 def success(self):
3515 return self.done
3516
3517 with TestDbusP2p(bus) as t:
3518 if not t.success():
3519 raise Exception("Expected signals not seen")
3520
3521 def test_dbus_p2p_join(dev, apdev):
3522 """D-Bus P2P join an autonomous GO"""
3523 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3524 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3525
3526 addr1 = dev[1].p2p_dev_addr()
3527 addr2 = dev[2].p2p_dev_addr()
3528 dev[1].p2p_start_go(freq=2412)
3529 dev1_group_ifname = dev[1].group_ifname
3530 dev[2].p2p_listen()
3531
3532 class TestDbusP2p(TestDbus):
3533 def __init__(self, bus):
3534 TestDbus.__init__(self, bus)
3535 self.done = False
3536 self.peer = None
3537 self.go = None
3538
3539 def __enter__(self):
3540 gobject.timeout_add(1, self.run_test)
3541 gobject.timeout_add(15000, self.timeout)
3542 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3543 "DeviceFound")
3544 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3545 "GroupStarted")
3546 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3547 "GroupFinished")
3548 self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
3549 "InvitationResult")
3550 self.loop.run()
3551 return self
3552
3553 def deviceFound(self, path):
3554 logger.debug("deviceFound: path=%s" % path)
3555 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
3556 res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
3557 dbus_interface=dbus.PROPERTIES_IFACE,
3558 byte_arrays=True)
3559 logger.debug('peer properties: ' + str(res))
3560 if addr2.replace(':','') in path:
3561 self.peer = path
3562 elif addr1.replace(':','') in path:
3563 self.go = path
3564 if self.peer and self.go:
3565 logger.info("Join the group")
3566 p2p.StopFind()
3567 args = { 'peer': self.go,
3568 'join': True,
3569 'wps_method': 'pin',
3570 'frequency': 2412 }
3571 pin = p2p.Connect(args)
3572
3573 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3574 dev1.group_ifname = dev1_group_ifname
3575 dev1.group_request("WPS_PIN any " + pin)
3576
3577 def groupStarted(self, properties):
3578 logger.debug("groupStarted: " + str(properties))
3579 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3580 properties['interface_object'])
3581 role = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
3582 dbus_interface=dbus.PROPERTIES_IFACE)
3583 if role != "client":
3584 raise Exception("Unexpected role reported: " + role)
3585 group = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
3586 dbus_interface=dbus.PROPERTIES_IFACE)
3587 if group != properties['group_object']:
3588 raise Exception("Unexpected Group reported: " + str(group))
3589 go = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
3590 dbus_interface=dbus.PROPERTIES_IFACE)
3591 if go != self.go:
3592 raise Exception("Unexpected PeerGO value: " + str(go))
3593
3594 g_obj = bus.get_object(WPAS_DBUS_SERVICE,
3595 properties['group_object'])
3596 res = g_obj.GetAll(WPAS_DBUS_GROUP,
3597 dbus_interface=dbus.PROPERTIES_IFACE,
3598 byte_arrays=True)
3599 logger.debug("Group properties: " + str(res))
3600
3601 ext = dbus.ByteArray("\x11\x22\x33\x44")
3602 try:
3603 # Set(WPSVendorExtensions) not allowed for P2P Client
3604 g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
3605 dbus_interface=dbus.PROPERTIES_IFACE)
3606 raise Exception("Invalid Set(WPSVendorExtensions) accepted")
3607 except dbus.exceptions.DBusException, e:
3608 if "Error.Failed: Failed to set property" not in str(e):
3609 raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
3610
3611 group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3612 args = { 'duration1': 30000, 'interval1': 102400,
3613 'duration2': 20000, 'interval2': 102400 }
3614 group_p2p.PresenceRequest(args)
3615
3616 args = { 'peer': self.peer }
3617 group_p2p.Invite(args)
3618
3619 def groupFinished(self, properties):
3620 logger.debug("groupFinished: " + str(properties))
3621 self.done = True
3622 self.loop.quit()
3623
3624 def invitationResult(self, result):
3625 logger.debug("invitationResult: " + str(result))
3626 if result['status'] != 1:
3627 raise Exception("Unexpected invitation result: " + str(result))
3628 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3629 dev1.group_ifname = dev1_group_ifname
3630 dev1.remove_group()
3631
3632 def run_test(self, *args):
3633 logger.debug("run_test")
3634 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
3635 return False
3636
3637 def success(self):
3638 return self.done
3639
3640 with TestDbusP2p(bus) as t:
3641 if not t.success():
3642 raise Exception("Expected signals not seen")
3643
3644 dev[2].p2p_stop_find()
3645
3646 def test_dbus_p2p_config(dev, apdev):
3647 """D-Bus Get/Set P2PDeviceConfig"""
3648 try:
3649 _test_dbus_p2p_config(dev, apdev)
3650 finally:
3651 dev[0].request("P2P_SET ssid_postfix ")
3652
3653 def _test_dbus_p2p_config(dev, apdev):
3654 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3655 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3656
3657 res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3658 dbus_interface=dbus.PROPERTIES_IFACE,
3659 byte_arrays=True)
3660 if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
3661 dbus_interface=dbus.PROPERTIES_IFACE)
3662 res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3663 dbus_interface=dbus.PROPERTIES_IFACE,
3664 byte_arrays=True)
3665
3666 if len(res) != len(res2):
3667 raise Exception("Different number of parameters")
3668 for k in res:
3669 if res[k] != res2[k]:
3670 raise Exception("Parameter %s value changes" % k)
3671
3672 changes = { 'SsidPostfix': 'foo',
3673 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
3674 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
3675 if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3676 dbus.Dictionary(changes, signature='sv'),
3677 dbus_interface=dbus.PROPERTIES_IFACE)
3678
3679 res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3680 dbus_interface=dbus.PROPERTIES_IFACE,
3681 byte_arrays=True)
3682 logger.debug("P2PDeviceConfig: " + str(res2))
3683 if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
3684 raise Exception("VendorExtension does not match")
3685 if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
3686 raise Exception("SecondaryDeviceType does not match")
3687
3688 changes = { 'SsidPostfix': '',
3689 'VendorExtension': dbus.Array([], signature="ay"),
3690 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
3691 if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3692 dbus.Dictionary(changes, signature='sv'),
3693 dbus_interface=dbus.PROPERTIES_IFACE)
3694
3695 res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3696 dbus_interface=dbus.PROPERTIES_IFACE,
3697 byte_arrays=True)
3698 logger.debug("P2PDeviceConfig: " + str(res3))
3699 if 'VendorExtension' in res3:
3700 raise Exception("VendorExtension not removed")
3701 if 'SecondaryDeviceTypes' in res3:
3702 raise Exception("SecondaryDeviceType not removed")
3703
3704 try:
3705 dev[0].request("P2P_SET disabled 1")
3706 if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3707 dbus_interface=dbus.PROPERTIES_IFACE,
3708 byte_arrays=True)
3709 raise Exception("Invalid Get(P2PDeviceConfig) accepted")
3710 except dbus.exceptions.DBusException, e:
3711 if "Error.Failed: P2P is not available for this interface" not in str(e):
3712 raise Exception("Unexpected error message for invalid Invite: " + str(e))
3713 finally:
3714 dev[0].request("P2P_SET disabled 0")
3715
3716 try:
3717 dev[0].request("P2P_SET disabled 1")
3718 changes = { 'SsidPostfix': 'foo' }
3719 if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3720 dbus.Dictionary(changes, signature='sv'),
3721 dbus_interface=dbus.PROPERTIES_IFACE)
3722 raise Exception("Invalid Set(P2PDeviceConfig) accepted")
3723 except dbus.exceptions.DBusException, e:
3724 if "Error.Failed: P2P is not available for this interface" not in str(e):
3725 raise Exception("Unexpected error message for invalid Invite: " + str(e))
3726 finally:
3727 dev[0].request("P2P_SET disabled 0")
3728
3729 tests = [ { 'DeviceName': 123 },
3730 { 'SsidPostfix': 123 },
3731 { 'Foo': 'Bar' } ]
3732 for changes in tests:
3733 try:
3734 if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
3735 dbus.Dictionary(changes, signature='sv'),
3736 dbus_interface=dbus.PROPERTIES_IFACE)
3737 raise Exception("Invalid Set(P2PDeviceConfig) accepted")
3738 except dbus.exceptions.DBusException, e:
3739 if "InvalidArgs" not in str(e):
3740 raise Exception("Unexpected error message for invalid Invite: " + str(e))
3741
3742 def test_dbus_p2p_persistent(dev, apdev):
3743 """D-Bus P2P persistent group"""
3744 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3745 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3746
3747 class TestDbusP2p(TestDbus):
3748 def __init__(self, bus):
3749 TestDbus.__init__(self, bus)
3750
3751 def __enter__(self):
3752 gobject.timeout_add(1, self.run_test)
3753 gobject.timeout_add(15000, self.timeout)
3754 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3755 "GroupStarted")
3756 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3757 "GroupFinished")
3758 self.add_signal(self.persistentGroupAdded,
3759 WPAS_DBUS_IFACE_P2PDEVICE,
3760 "PersistentGroupAdded")
3761 self.loop.run()
3762 return self
3763
3764 def groupStarted(self, properties):
3765 logger.debug("groupStarted: " + str(properties))
3766 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3767 properties['interface_object'])
3768 group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3769 group_p2p.Disconnect()
3770
3771 def groupFinished(self, properties):
3772 logger.debug("groupFinished: " + str(properties))
3773 self.loop.quit()
3774
3775 def persistentGroupAdded(self, path, properties):
3776 logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
3777 self.persistent = path
3778
3779 def run_test(self, *args):
3780 logger.debug("run_test")
3781 params = dbus.Dictionary({'persistent': True,
3782 'frequency': 2412})
3783 logger.info("Add a persistent group")
3784 p2p.GroupAdd(params)
3785 return False
3786
3787 def success(self):
3788 return True
3789
3790 with TestDbusP2p(bus) as t:
3791 if not t.success():
3792 raise Exception("Expected signals not seen")
3793 persistent = t.persistent
3794
3795 p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
3796 res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
3797 dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
3798 logger.info("Persistent group Properties: " + str(res))
3799 vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
3800 p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
3801 dbus_interface=dbus.PROPERTIES_IFACE)
3802 res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
3803 dbus_interface=dbus.PROPERTIES_IFACE)
3804 if len(res) != len(res2):
3805 raise Exception("Different number of parameters")
3806 for k in res:
3807 if k != 'ssid' and res[k] != res2[k]:
3808 raise Exception("Parameter %s value changes" % k)
3809 if res2['ssid'] != '"DIRECT-foo"':
3810 raise Exception("Unexpected ssid")
3811
3812 args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
3813 'psk': '1234567890' }, signature='sv')
3814 group = p2p.AddPersistentGroup(args)
3815
3816 groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
3817 dbus_interface=dbus.PROPERTIES_IFACE)
3818 if len(groups) != 2:
3819 raise Exception("Unexpected number of persistent groups: " + str(groups))
3820
3821 p2p.RemoveAllPersistentGroups()
3822
3823 groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
3824 dbus_interface=dbus.PROPERTIES_IFACE)
3825 if len(groups) != 0:
3826 raise Exception("Unexpected number of persistent groups: " + str(groups))
3827
3828 try:
3829 p2p.RemovePersistentGroup(persistent)
3830 raise Exception("Invalid RemovePersistentGroup accepted")
3831 except dbus.exceptions.DBusException, e:
3832 if "NetworkUnknown: There is no such persistent group" not in str(e):
3833 raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
3834
3835 def test_dbus_p2p_reinvoke_persistent(dev, apdev):
3836 """D-Bus P2P reinvoke persistent group"""
3837 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3838 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3839
3840 addr0 = dev[0].p2p_dev_addr()
3841
3842 class TestDbusP2p(TestDbus):
3843 def __init__(self, bus):
3844 TestDbus.__init__(self, bus)
3845 self.first = True
3846 self.waiting_end = False
3847 self.done = False
3848 self.invited = False
3849
3850 def __enter__(self):
3851 gobject.timeout_add(1, self.run_test)
3852 gobject.timeout_add(15000, self.timeout)
3853 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3854 "DeviceFound")
3855 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3856 "GroupStarted")
3857 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
3858 "GroupFinished")
3859 self.add_signal(self.persistentGroupAdded,
3860 WPAS_DBUS_IFACE_P2PDEVICE,
3861 "PersistentGroupAdded")
3862 self.add_signal(self.provisionDiscoveryRequestDisplayPin,
3863 WPAS_DBUS_IFACE_P2PDEVICE,
3864 "ProvisionDiscoveryRequestDisplayPin")
3865 self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
3866 "StaAuthorized")
3867 self.loop.run()
3868 return self
3869
3870 def groupStarted(self, properties):
3871 logger.debug("groupStarted: " + str(properties))
3872 self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
3873 properties['interface_object'])
3874 if not self.invited:
3875 g_obj = bus.get_object(WPAS_DBUS_SERVICE,
3876 properties['group_object'])
3877 res = g_obj.GetAll(WPAS_DBUS_GROUP,
3878 dbus_interface=dbus.PROPERTIES_IFACE,
3879 byte_arrays=True)
3880 bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
3881 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3882 dev1.scan_for_bss(bssid, freq=2412)
3883 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
3884
3885 def groupFinished(self, properties):
3886 logger.debug("groupFinished: " + str(properties))
3887 if self.invited:
3888 self.done = True
3889 self.loop.quit()
3890 else:
3891 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3892 dev1.global_request("SET persistent_reconnect 1")
3893 dev1.p2p_listen()
3894
3895 args = { 'persistent_group_object': dbus.ObjectPath(path),
3896 'peer': self.peer_path }
3897 try:
3898 pin = p2p.Invite(args)
3899 raise Exception("Invalid Invite accepted")
3900 except dbus.exceptions.DBusException, e:
3901 if "InvalidArgs" not in str(e):
3902 raise Exception("Unexpected error message for invalid Invite: " + str(e))
3903
3904 args = { 'persistent_group_object': self.persistent,
3905 'peer': self.peer_path }
3906 pin = p2p.Invite(args)
3907 self.invited = True
3908
3909 self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
3910 timeout=15)
3911 if self.sta_group_ev is None:
3912 raise Exception("P2P-GROUP-STARTED event not seen")
3913
3914 def persistentGroupAdded(self, path, properties):
3915 logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
3916 self.persistent = path
3917
3918 def deviceFound(self, path):
3919 logger.debug("deviceFound: path=%s" % path)
3920 peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
3921 self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
3922 dbus_interface=dbus.PROPERTIES_IFACE,
3923 byte_arrays=True)
3924
3925 def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
3926 logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
3927 self.peer_path = peer_object
3928 peer = binascii.unhexlify(peer_object.split('/')[-1])
3929 addr = ""
3930 for p in peer:
3931 if len(addr) > 0:
3932 addr += ':'
3933 addr += '%02x' % ord(p)
3934 params = { 'Role': 'registrar',
3935 'P2PDeviceAddress': self.peer['DeviceAddress'],
3936 'Bssid': self.peer['DeviceAddress'],
3937 'Type': 'pin',
3938 'Pin': '12345670' }
3939 logger.info("Authorize peer to connect to the group")
3940 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3941 wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
3942 wps.Start(params)
3943 self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
3944 timeout=15)
3945 if self.sta_group_ev is None:
3946 raise Exception("P2P-GROUP-STARTED event not seen")
3947
3948 def staAuthorized(self, name):
3949 logger.debug("staAuthorized: " + name)
3950 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
3951 dev1.group_form_result(self.sta_group_ev)
3952 dev1.remove_group()
3953 ev = dev1.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
3954 if ev is None:
3955 raise Exception("Group removal timed out")
3956 group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3957 group_p2p.Disconnect()
3958
3959 def run_test(self, *args):
3960 logger.debug("run_test")
3961 params = dbus.Dictionary({'persistent': True,
3962 'frequency': 2412})
3963 logger.info("Add a persistent group")
3964 p2p.GroupAdd(params)
3965 return False
3966
3967 def success(self):
3968 return self.done
3969
3970 with TestDbusP2p(bus) as t:
3971 if not t.success():
3972 raise Exception("Expected signals not seen")
3973
3974 def test_dbus_p2p_go_neg_rx(dev, apdev):
3975 """D-Bus P2P GO Negotiation receive"""
3976 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
3977 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
3978 addr0 = dev[0].p2p_dev_addr()
3979
3980 class TestDbusP2p(TestDbus):
3981 def __init__(self, bus):
3982 TestDbus.__init__(self, bus)
3983 self.done = False
3984
3985 def __enter__(self):
3986 gobject.timeout_add(1, self.run_test)
3987 gobject.timeout_add(15000, self.timeout)
3988 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
3989 "DeviceFound")
3990 self.add_signal(self.goNegotiationRequest,
3991 WPAS_DBUS_IFACE_P2PDEVICE,
3992 "GONegotiationRequest",
3993 byte_arrays=True)
3994 self.add_signal(self.goNegotiationSuccess,
3995 WPAS_DBUS_IFACE_P2PDEVICE,
3996 "GONegotiationSuccess",
3997 byte_arrays=True)
3998 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
3999 "GroupStarted")
4000 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4001 "GroupFinished")
4002 self.loop.run()
4003 return self
4004
4005 def deviceFound(self, path):
4006 logger.debug("deviceFound: path=%s" % path)
4007
4008 def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
4009 logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
4010 if dev_passwd_id != 1:
4011 raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
4012 args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
4013 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
4014 try:
4015 p2p.Connect(args)
4016 raise Exception("Invalid Connect accepted")
4017 except dbus.exceptions.DBusException, e:
4018 if "ConnectChannelUnsupported" not in str(e):
4019 raise Exception("Unexpected error message for invalid Connect: " + str(e))
4020
4021 args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
4022 'go_intent': 15, 'persistent': False }
4023 p2p.Connect(args)
4024
4025 def goNegotiationSuccess(self, properties):
4026 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4027
4028 def groupStarted(self, properties):
4029 logger.debug("groupStarted: " + str(properties))
4030 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4031 properties['interface_object'])
4032 group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4033 group_p2p.Disconnect()
4034
4035 def groupFinished(self, properties):
4036 logger.debug("groupFinished: " + str(properties))
4037 self.done = True
4038 self.loop.quit()
4039
4040 def run_test(self, *args):
4041 logger.debug("run_test")
4042 p2p.Listen(10)
4043 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4044 if not dev1.discover_peer(addr0):
4045 raise Exception("Peer not found")
4046 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
4047 return False
4048
4049 def success(self):
4050 return self.done
4051
4052 with TestDbusP2p(bus) as t:
4053 if not t.success():
4054 raise Exception("Expected signals not seen")
4055
4056 def test_dbus_p2p_go_neg_auth(dev, apdev):
4057 """D-Bus P2P GO Negotiation authorized"""
4058 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4059 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4060 addr0 = dev[0].p2p_dev_addr()
4061 dev[1].p2p_listen()
4062
4063 class TestDbusP2p(TestDbus):
4064 def __init__(self, bus):
4065 TestDbus.__init__(self, bus)
4066 self.done = False
4067 self.peer_joined = False
4068 self.peer_disconnected = False
4069
4070 def __enter__(self):
4071 gobject.timeout_add(1, self.run_test)
4072 gobject.timeout_add(15000, self.timeout)
4073 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4074 "DeviceFound")
4075 self.add_signal(self.goNegotiationSuccess,
4076 WPAS_DBUS_IFACE_P2PDEVICE,
4077 "GONegotiationSuccess",
4078 byte_arrays=True)
4079 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4080 "GroupStarted")
4081 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4082 "GroupFinished")
4083 self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
4084 "StaDeauthorized")
4085 self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
4086 "PeerJoined")
4087 self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
4088 "PeerDisconnected")
4089 self.loop.run()
4090 return self
4091
4092 def deviceFound(self, path):
4093 logger.debug("deviceFound: path=%s" % path)
4094 args = { 'peer': path, 'wps_method': 'keypad',
4095 'go_intent': 15, 'authorize_only': True }
4096 try:
4097 p2p.Connect(args)
4098 raise Exception("Invalid Connect accepted")
4099 except dbus.exceptions.DBusException, e:
4100 if "InvalidArgs" not in str(e):
4101 raise Exception("Unexpected error message for invalid Connect: " + str(e))
4102
4103 args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
4104 'go_intent': 15, 'authorize_only': True }
4105 p2p.Connect(args)
4106 p2p.Listen(10)
4107 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4108 if not dev1.discover_peer(addr0):
4109 raise Exception("Peer not found")
4110 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
4111 ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
4112 if ev is None:
4113 raise Exception("Group formation timed out")
4114 self.sta_group_ev = ev
4115
4116 def goNegotiationSuccess(self, properties):
4117 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4118
4119 def groupStarted(self, properties):
4120 logger.debug("groupStarted: " + str(properties))
4121 self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4122 properties['interface_object'])
4123 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4124 dev1.group_form_result(self.sta_group_ev)
4125 dev1.remove_group()
4126
4127 def staDeauthorized(self, name):
4128 logger.debug("staDeuthorized: " + name)
4129 group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4130 group_p2p.Disconnect()
4131
4132 def peerJoined(self, peer):
4133 logger.debug("peerJoined: " + peer)
4134 self.peer_joined = True
4135
4136 def peerDisconnected(self, peer):
4137 logger.debug("peerDisconnected: " + peer)
4138 self.peer_disconnected = True
4139
4140 def groupFinished(self, properties):
4141 logger.debug("groupFinished: " + str(properties))
4142 self.done = True
4143 self.loop.quit()
4144
4145 def run_test(self, *args):
4146 logger.debug("run_test")
4147 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4148 return False
4149
4150 def success(self):
4151 return self.done and self.peer_joined and self.peer_disconnected
4152
4153 with TestDbusP2p(bus) as t:
4154 if not t.success():
4155 raise Exception("Expected signals not seen")
4156
4157 def test_dbus_p2p_go_neg_init(dev, apdev):
4158 """D-Bus P2P GO Negotiation initiation"""
4159 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4160 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4161 addr0 = dev[0].p2p_dev_addr()
4162 dev[1].p2p_listen()
4163
4164 class TestDbusP2p(TestDbus):
4165 def __init__(self, bus):
4166 TestDbus.__init__(self, bus)
4167 self.done = False
4168 self.peer_group_added = False
4169 self.peer_group_removed = False
4170
4171 def __enter__(self):
4172 gobject.timeout_add(1, self.run_test)
4173 gobject.timeout_add(15000, self.timeout)
4174 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4175 "DeviceFound")
4176 self.add_signal(self.goNegotiationSuccess,
4177 WPAS_DBUS_IFACE_P2PDEVICE,
4178 "GONegotiationSuccess",
4179 byte_arrays=True)
4180 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4181 "GroupStarted")
4182 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4183 "GroupFinished")
4184 self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
4185 "PropertiesChanged")
4186 self.loop.run()
4187 return self
4188
4189 def deviceFound(self, path):
4190 logger.debug("deviceFound: path=%s" % path)
4191 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4192 args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
4193 'go_intent': 0 }
4194 p2p.Connect(args)
4195
4196 ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
4197 if ev is None:
4198 raise Exception("Timeout while waiting for GO Neg Request")
4199 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
4200 ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
4201 if ev is None:
4202 raise Exception("Group formation timed out")
4203 self.sta_group_ev = ev
4204
4205 def goNegotiationSuccess(self, properties):
4206 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4207
4208 def groupStarted(self, properties):
4209 logger.debug("groupStarted: " + str(properties))
4210 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4211 properties['interface_object'])
4212 group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4213 group_p2p.Disconnect()
4214 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4215 dev1.group_form_result(self.sta_group_ev)
4216 dev1.remove_group()
4217
4218 def groupFinished(self, properties):
4219 logger.debug("groupFinished: " + str(properties))
4220 self.done = True
4221
4222 def propertiesChanged(self, interface_name, changed_properties,
4223 invalidated_properties):
4224 logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
4225 if interface_name != WPAS_DBUS_P2P_PEER:
4226 return
4227 if "Groups" not in changed_properties:
4228 return
4229 if len(changed_properties["Groups"]) > 0:
4230 self.peer_group_added = True
4231 if len(changed_properties["Groups"]) == 0:
4232 self.peer_group_removed = True
4233 self.loop.quit()
4234
4235 def run_test(self, *args):
4236 logger.debug("run_test")
4237 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4238 return False
4239
4240 def success(self):
4241 return self.done and self.peer_group_added and self.peer_group_removed
4242
4243 with TestDbusP2p(bus) as t:
4244 if not t.success():
4245 raise Exception("Expected signals not seen")
4246
4247 def test_dbus_p2p_group_termination_by_go(dev, apdev):
4248 """D-Bus P2P group removal on GO terminating the group"""
4249 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4250 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4251 addr0 = dev[0].p2p_dev_addr()
4252 dev[1].p2p_listen()
4253
4254 class TestDbusP2p(TestDbus):
4255 def __init__(self, bus):
4256 TestDbus.__init__(self, bus)
4257 self.done = False
4258 self.peer_group_added = False
4259 self.peer_group_removed = False
4260
4261 def __enter__(self):
4262 gobject.timeout_add(1, self.run_test)
4263 gobject.timeout_add(15000, self.timeout)
4264 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4265 "DeviceFound")
4266 self.add_signal(self.goNegotiationSuccess,
4267 WPAS_DBUS_IFACE_P2PDEVICE,
4268 "GONegotiationSuccess",
4269 byte_arrays=True)
4270 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4271 "GroupStarted")
4272 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4273 "GroupFinished")
4274 self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
4275 "PropertiesChanged")
4276 self.loop.run()
4277 return self
4278
4279 def deviceFound(self, path):
4280 logger.debug("deviceFound: path=%s" % path)
4281 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4282 args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
4283 'go_intent': 0 }
4284 p2p.Connect(args)
4285
4286 ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
4287 if ev is None:
4288 raise Exception("Timeout while waiting for GO Neg Request")
4289 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
4290 ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
4291 if ev is None:
4292 raise Exception("Group formation timed out")
4293 self.sta_group_ev = ev
4294
4295 def goNegotiationSuccess(self, properties):
4296 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4297
4298 def groupStarted(self, properties):
4299 logger.debug("groupStarted: " + str(properties))
4300 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4301 properties['interface_object'])
4302 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4303 dev1.group_form_result(self.sta_group_ev)
4304 dev1.remove_group()
4305
4306 def groupFinished(self, properties):
4307 logger.debug("groupFinished: " + str(properties))
4308 self.done = True
4309
4310 def propertiesChanged(self, interface_name, changed_properties,
4311 invalidated_properties):
4312 logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
4313 if interface_name != WPAS_DBUS_P2P_PEER:
4314 return
4315 if "Groups" not in changed_properties:
4316 return
4317 if len(changed_properties["Groups"]) > 0:
4318 self.peer_group_added = True
4319 if len(changed_properties["Groups"]) == 0 and self.peer_group_added:
4320 self.peer_group_removed = True
4321 self.loop.quit()
4322
4323 def run_test(self, *args):
4324 logger.debug("run_test")
4325 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4326 return False
4327
4328 def success(self):
4329 return self.done and self.peer_group_added and self.peer_group_removed
4330
4331 with TestDbusP2p(bus) as t:
4332 if not t.success():
4333 raise Exception("Expected signals not seen")
4334
4335 def test_dbus_p2p_group_idle_timeout(dev, apdev):
4336 """D-Bus P2P group removal on idle timeout"""
4337 try:
4338 dev[0].global_request("SET p2p_group_idle 1")
4339 _test_dbus_p2p_group_idle_timeout(dev, apdev)
4340 finally:
4341 dev[0].global_request("SET p2p_group_idle 0")
4342
4343 def _test_dbus_p2p_group_idle_timeout(dev, apdev):
4344 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4345 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4346 addr0 = dev[0].p2p_dev_addr()
4347 dev[1].p2p_listen()
4348
4349 class TestDbusP2p(TestDbus):
4350 def __init__(self, bus):
4351 TestDbus.__init__(self, bus)
4352 self.done = False
4353 self.peer_group_added = False
4354 self.peer_group_removed = False
4355
4356 def __enter__(self):
4357 gobject.timeout_add(1, self.run_test)
4358 gobject.timeout_add(15000, self.timeout)
4359 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4360 "DeviceFound")
4361 self.add_signal(self.goNegotiationSuccess,
4362 WPAS_DBUS_IFACE_P2PDEVICE,
4363 "GONegotiationSuccess",
4364 byte_arrays=True)
4365 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4366 "GroupStarted")
4367 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4368 "GroupFinished")
4369 self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
4370 "PropertiesChanged")
4371 self.loop.run()
4372 return self
4373
4374 def deviceFound(self, path):
4375 logger.debug("deviceFound: path=%s" % path)
4376 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4377 args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
4378 'go_intent': 0 }
4379 p2p.Connect(args)
4380
4381 ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
4382 if ev is None:
4383 raise Exception("Timeout while waiting for GO Neg Request")
4384 dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
4385 ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
4386 if ev is None:
4387 raise Exception("Group formation timed out")
4388 self.sta_group_ev = ev
4389
4390 def goNegotiationSuccess(self, properties):
4391 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4392
4393 def groupStarted(self, properties):
4394 logger.debug("groupStarted: " + str(properties))
4395 g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4396 properties['interface_object'])
4397 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4398 dev1.group_form_result(self.sta_group_ev)
4399 ifaddr = dev1.group_request("STA-FIRST").splitlines()[0]
4400 # Force disassociation with different reason code so that the
4401 # P2P Client using D-Bus does not get normal group termination event
4402 # from the GO.
4403 dev1.group_request("DEAUTHENTICATE " + ifaddr + " reason=0 test=0")
4404 dev1.remove_group()
4405
4406 def groupFinished(self, properties):
4407 logger.debug("groupFinished: " + str(properties))
4408 self.done = True
4409
4410 def propertiesChanged(self, interface_name, changed_properties,
4411 invalidated_properties):
4412 logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
4413 if interface_name != WPAS_DBUS_P2P_PEER:
4414 return
4415 if "Groups" not in changed_properties:
4416 return
4417 if len(changed_properties["Groups"]) > 0:
4418 self.peer_group_added = True
4419 if len(changed_properties["Groups"]) == 0:
4420 self.peer_group_removed = True
4421 self.loop.quit()
4422
4423 def run_test(self, *args):
4424 logger.debug("run_test")
4425 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4426 return False
4427
4428 def success(self):
4429 return self.done and self.peer_group_added and self.peer_group_removed
4430
4431 with TestDbusP2p(bus) as t:
4432 if not t.success():
4433 raise Exception("Expected signals not seen")
4434
4435 def test_dbus_p2p_wps_failure(dev, apdev):
4436 """D-Bus P2P WPS failure"""
4437 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4438 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4439 addr0 = dev[0].p2p_dev_addr()
4440
4441 class TestDbusP2p(TestDbus):
4442 def __init__(self, bus):
4443 TestDbus.__init__(self, bus)
4444 self.wps_failed = False
4445 self.formation_failure = False
4446
4447 def __enter__(self):
4448 gobject.timeout_add(1, self.run_test)
4449 gobject.timeout_add(15000, self.timeout)
4450 self.add_signal(self.goNegotiationRequest,
4451 WPAS_DBUS_IFACE_P2PDEVICE,
4452 "GONegotiationRequest",
4453 byte_arrays=True)
4454 self.add_signal(self.goNegotiationSuccess,
4455 WPAS_DBUS_IFACE_P2PDEVICE,
4456 "GONegotiationSuccess",
4457 byte_arrays=True)
4458 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4459 "GroupStarted")
4460 self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
4461 "WpsFailed")
4462 self.add_signal(self.groupFormationFailure,
4463 WPAS_DBUS_IFACE_P2PDEVICE,
4464 "GroupFormationFailure")
4465 self.loop.run()
4466 return self
4467
4468 def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
4469 logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
4470 if dev_passwd_id != 1:
4471 raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
4472 args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
4473 'go_intent': 15 }
4474 p2p.Connect(args)
4475
4476 def goNegotiationSuccess(self, properties):
4477 logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
4478
4479 def groupStarted(self, properties):
4480 logger.debug("groupStarted: " + str(properties))
4481 raise Exception("Unexpected GroupStarted")
4482
4483 def wpsFailed(self, name, args):
4484 logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
4485 self.wps_failed = True
4486 if self.formation_failure:
4487 self.loop.quit()
4488
4489 def groupFormationFailure(self, reason):
4490 logger.debug("groupFormationFailure - reason=%s" % reason)
4491 self.formation_failure = True
4492 if self.wps_failed:
4493 self.loop.quit()
4494
4495 def run_test(self, *args):
4496 logger.debug("run_test")
4497 p2p.Listen(10)
4498 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4499 if not dev1.discover_peer(addr0):
4500 raise Exception("Peer not found")
4501 dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
4502 return False
4503
4504 def success(self):
4505 return self.wps_failed and self.formation_failure
4506
4507 with TestDbusP2p(bus) as t:
4508 if not t.success():
4509 raise Exception("Expected signals not seen")
4510
4511 def test_dbus_p2p_two_groups(dev, apdev):
4512 """D-Bus P2P with two concurrent groups"""
4513 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4514 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4515
4516 dev[0].request("SET p2p_no_group_iface 0")
4517 addr0 = dev[0].p2p_dev_addr()
4518 addr1 = dev[1].p2p_dev_addr()
4519 addr2 = dev[2].p2p_dev_addr()
4520 dev[1].p2p_start_go(freq=2412)
4521 dev1_group_ifname = dev[1].group_ifname
4522
4523 class TestDbusP2p(TestDbus):
4524 def __init__(self, bus):
4525 TestDbus.__init__(self, bus)
4526 self.done = False
4527 self.peer = None
4528 self.go = None
4529 self.group1 = None
4530 self.group2 = None
4531 self.groups_removed = False
4532
4533 def __enter__(self):
4534 gobject.timeout_add(1, self.run_test)
4535 gobject.timeout_add(15000, self.timeout)
4536 self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
4537 "PropertiesChanged", byte_arrays=True)
4538 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4539 "DeviceFound")
4540 self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
4541 "GroupStarted")
4542 self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
4543 "GroupFinished")
4544 self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
4545 "PeerJoined")
4546 self.loop.run()
4547 return self
4548
4549 def propertiesChanged(self, interface_name, changed_properties,
4550 invalidated_properties):
4551 logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
4552
4553 def deviceFound(self, path):
4554 logger.debug("deviceFound: path=%s" % path)
4555 if addr2.replace(':','') in path:
4556 self.peer = path
4557 elif addr1.replace(':','') in path:
4558 self.go = path
4559 if self.go and not self.group1:
4560 logger.info("Join the group")
4561 p2p.StopFind()
4562 pin = '12345670'
4563 dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
4564 dev1.group_ifname = dev1_group_ifname
4565 dev1.group_request("WPS_PIN any " + pin)
4566 args = { 'peer': self.go,
4567 'join': True,
4568 'wps_method': 'pin',
4569 'pin': pin,
4570 'frequency': 2412 }
4571 p2p.Connect(args)
4572
4573 def groupStarted(self, properties):
4574 logger.debug("groupStarted: " + str(properties))
4575 prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
4576 dbus_interface=dbus.PROPERTIES_IFACE)
4577 logger.debug("p2pdevice properties: " + str(prop))
4578
4579 g_obj = bus.get_object(WPAS_DBUS_SERVICE,
4580 properties['group_object'])
4581 res = g_obj.GetAll(WPAS_DBUS_GROUP,
4582 dbus_interface=dbus.PROPERTIES_IFACE,
4583 byte_arrays=True)
4584 logger.debug("Group properties: " + str(res))
4585
4586 if not self.group1:
4587 self.group1 = properties['group_object']
4588 self.group1iface = properties['interface_object']
4589 self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4590 self.group1iface)
4591
4592 logger.info("Start autonomous GO")
4593 params = dbus.Dictionary({ 'frequency': 2412 })
4594 p2p.GroupAdd(params)
4595 elif not self.group2:
4596 self.group2 = properties['group_object']
4597 self.group2iface = properties['interface_object']
4598 self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
4599 self.group2iface)
4600 self.g2_bssid = res['BSSID']
4601
4602 if self.group1 and self.group2:
4603 logger.info("Authorize peer to join the group")
4604 a2 = binascii.unhexlify(addr2.replace(':',''))
4605 params = { 'Role': 'enrollee',
4606 'P2PDeviceAddress': dbus.ByteArray(a2),
4607 'Bssid': dbus.ByteArray(a2),
4608 'Type': 'pin',
4609 'Pin': '12345670' }
4610 g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
4611 g_wps.Start(params)
4612
4613 bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
4614 dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
4615 dev2.scan_for_bss(bssid, freq=2412)
4616 dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
4617 ev = dev2.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
4618 if ev is None:
4619 raise Exception("Group join timed out")
4620 self.dev2_group_ev = ev
4621
4622 def groupFinished(self, properties):
4623 logger.debug("groupFinished: " + str(properties))
4624
4625 if self.group1 == properties['group_object']:
4626 self.group1 = None
4627 elif self.group2 == properties['group_object']:
4628 self.group2 = None
4629
4630 if not self.group1 and not self.group2:
4631 self.done = True
4632 self.loop.quit()
4633
4634 def peerJoined(self, peer):
4635 logger.debug("peerJoined: " + peer)
4636 if self.groups_removed:
4637 return
4638 self.check_results()
4639
4640 dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
4641 dev2.group_form_result(self.dev2_group_ev)
4642 dev2.remove_group()
4643
4644 logger.info("Disconnect group2")
4645 group_p2p = dbus.Interface(self.g2_if_obj,
4646 WPAS_DBUS_IFACE_P2PDEVICE)
4647 group_p2p.Disconnect()
4648
4649 logger.info("Disconnect group1")
4650 group_p2p = dbus.Interface(self.g1_if_obj,
4651 WPAS_DBUS_IFACE_P2PDEVICE)
4652 group_p2p.Disconnect()
4653 self.groups_removed = True
4654
4655 def check_results(self):
4656 logger.info("Check results with two concurrent groups in operation")
4657
4658 g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
4659 res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
4660 dbus_interface=dbus.PROPERTIES_IFACE,
4661 byte_arrays=True)
4662
4663 g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
4664 res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
4665 dbus_interface=dbus.PROPERTIES_IFACE,
4666 byte_arrays=True)
4667
4668 logger.info("group1 = " + self.group1)
4669 logger.debug("Group properties: " + str(res1))
4670
4671 logger.info("group2 = " + self.group2)
4672 logger.debug("Group properties: " + str(res2))
4673
4674 prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
4675 dbus_interface=dbus.PROPERTIES_IFACE)
4676 logger.debug("p2pdevice properties: " + str(prop))
4677
4678 if res1['Role'] != 'client':
4679 raise Exception("Group1 role reported incorrectly: " + res1['Role'])
4680 if res2['Role'] != 'GO':
4681 raise Exception("Group2 role reported incorrectly: " + res2['Role'])
4682 if prop['Role'] != 'device':
4683 raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
4684
4685 if len(res2['Members']) != 1:
4686 raise Exception("Unexpected Members value for group 2")
4687
4688 def run_test(self, *args):
4689 logger.debug("run_test")
4690 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4691 return False
4692
4693 def success(self):
4694 return self.done
4695
4696 with TestDbusP2p(bus) as t:
4697 if not t.success():
4698 raise Exception("Expected signals not seen")
4699
4700 dev[1].remove_group()
4701
4702 def test_dbus_p2p_cancel(dev, apdev):
4703 """D-Bus P2P Cancel"""
4704 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4705 p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
4706 try:
4707 p2p.Cancel()
4708 raise Exception("Unexpected p2p.Cancel() success")
4709 except dbus.exceptions.DBusException, e:
4710 pass
4711
4712 addr0 = dev[0].p2p_dev_addr()
4713 dev[1].p2p_listen()
4714
4715 class TestDbusP2p(TestDbus):
4716 def __init__(self, bus):
4717 TestDbus.__init__(self, bus)
4718 self.done = False
4719
4720 def __enter__(self):
4721 gobject.timeout_add(1, self.run_test)
4722 gobject.timeout_add(15000, self.timeout)
4723 self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
4724 "DeviceFound")
4725 self.loop.run()
4726 return self
4727
4728 def deviceFound(self, path):
4729 logger.debug("deviceFound: path=%s" % path)
4730 args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
4731 'go_intent': 0 }
4732 p2p.Connect(args)
4733 p2p.Cancel()
4734 self.done = True
4735 self.loop.quit()
4736
4737 def run_test(self, *args):
4738 logger.debug("run_test")
4739 p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
4740 return False
4741
4742 def success(self):
4743 return self.done
4744
4745 with TestDbusP2p(bus) as t:
4746 if not t.success():
4747 raise Exception("Expected signals not seen")
4748
4749 def test_dbus_introspect(dev, apdev):
4750 """D-Bus introspection"""
4751 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4752
4753 res = if_obj.Introspect(WPAS_DBUS_IFACE,
4754 dbus_interface=dbus.INTROSPECTABLE_IFACE)
4755 logger.info("Initial Introspect: " + str(res))
4756 if res is None or "Introspectable" not in res or "GroupStarted" not in res:
4757 raise Exception("Unexpected initial Introspect response: " + str(res))
4758 if "FastReauth" not in res or "PassiveScan" not in res:
4759 raise Exception("Unexpected initial Introspect response: " + str(res))
4760
4761 with alloc_fail(dev[0], 1, "wpa_dbus_introspect"):
4762 res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
4763 dbus_interface=dbus.INTROSPECTABLE_IFACE)
4764 logger.info("Introspect: " + str(res2))
4765 if res2 is not None:
4766 raise Exception("Unexpected Introspect response")
4767
4768 with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
4769 res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
4770 dbus_interface=dbus.INTROSPECTABLE_IFACE)
4771 logger.info("Introspect: " + str(res2))
4772 if res2 is None:
4773 raise Exception("No Introspect response")
4774 if len(res2) >= len(res):
4775 raise Exception("Unexpected Introspect response")
4776
4777 with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
4778 res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
4779 dbus_interface=dbus.INTROSPECTABLE_IFACE)
4780 logger.info("Introspect: " + str(res2))
4781 if res2 is None:
4782 raise Exception("No Introspect response")
4783 if len(res2) >= len(res):
4784 raise Exception("Unexpected Introspect response")
4785
4786 with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
4787 res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
4788 dbus_interface=dbus.INTROSPECTABLE_IFACE)
4789 logger.info("Introspect: " + str(res2))
4790 if res2 is None:
4791 raise Exception("No Introspect response")
4792 if len(res2) >= len(res):
4793 raise Exception("Unexpected Introspect response")
4794
4795 def test_dbus_ap(dev, apdev):
4796 """D-Bus AddNetwork for AP mode"""
4797 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4798 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
4799
4800 ssid = "test-wpa2-psk"
4801 passphrase = 'qwertyuiop'
4802
4803 class TestDbusConnect(TestDbus):
4804 def __init__(self, bus):
4805 TestDbus.__init__(self, bus)
4806 self.started = False
4807
4808 def __enter__(self):
4809 gobject.timeout_add(1, self.run_connect)
4810 gobject.timeout_add(15000, self.timeout)
4811 self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
4812 self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
4813 "NetworkSelected")
4814 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
4815 "PropertiesChanged")
4816 self.loop.run()
4817 return self
4818
4819 def networkAdded(self, network, properties):
4820 logger.debug("networkAdded: %s" % str(network))
4821 logger.debug(str(properties))
4822
4823 def networkSelected(self, network):
4824 logger.debug("networkSelected: %s" % str(network))
4825 self.network_selected = True
4826
4827 def propertiesChanged(self, properties):
4828 logger.debug("propertiesChanged: %s" % str(properties))
4829 if 'State' in properties and properties['State'] == "completed":
4830 self.started = True
4831 self.loop.quit()
4832
4833 def run_connect(self, *args):
4834 logger.debug("run_connect")
4835 args = dbus.Dictionary({ 'ssid': ssid,
4836 'key_mgmt': 'WPA-PSK',
4837 'psk': passphrase,
4838 'mode': 2,
4839 'frequency': 2412 },
4840 signature='sv')
4841 self.netw = iface.AddNetwork(args)
4842 iface.SelectNetwork(self.netw)
4843 return False
4844
4845 def success(self):
4846 return self.started
4847
4848 with TestDbusConnect(bus) as t:
4849 if not t.success():
4850 raise Exception("Expected signals not seen")
4851 dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
4852
4853 def test_dbus_connect_wpa_eap(dev, apdev):
4854 """D-Bus AddNetwork and connection with WPA+WPA2-Enterprise AP"""
4855 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4856 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
4857
4858 ssid = "test-wpa-eap"
4859 params = hostapd.wpa_eap_params(ssid=ssid)
4860 params["wpa"] = "3"
4861 params["rsn_pairwise"] = "CCMP"
4862 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4863
4864 class TestDbusConnect(TestDbus):
4865 def __init__(self, bus):
4866 TestDbus.__init__(self, bus)
4867 self.done = False
4868
4869 def __enter__(self):
4870 gobject.timeout_add(1, self.run_connect)
4871 gobject.timeout_add(15000, self.timeout)
4872 self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
4873 "PropertiesChanged")
4874 self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
4875 self.loop.run()
4876 return self
4877
4878 def propertiesChanged(self, properties):
4879 logger.debug("propertiesChanged: %s" % str(properties))
4880 if 'State' in properties and properties['State'] == "completed":
4881 self.done = True
4882 self.loop.quit()
4883
4884 def eap(self, status, parameter):
4885 logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
4886
4887 def run_connect(self, *args):
4888 logger.debug("run_connect")
4889 args = dbus.Dictionary({ 'ssid': ssid,
4890 'key_mgmt': 'WPA-EAP',
4891 'eap': 'PEAP',
4892 'identity': 'user',
4893 'password': 'password',
4894 'ca_cert': 'auth_serv/ca.pem',
4895 'phase2': 'auth=MSCHAPV2',
4896 'scan_freq': 2412 },
4897 signature='sv')
4898 self.netw = iface.AddNetwork(args)
4899 iface.SelectNetwork(self.netw)
4900 return False
4901
4902 def success(self):
4903 return self.done
4904
4905 with TestDbusConnect(bus) as t:
4906 if not t.success():
4907 raise Exception("Expected signals not seen")
4908
4909 def test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
4910 """AP_SCAN 2 AP mode and D-Bus Scan()"""
4911 try:
4912 _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev)
4913 finally:
4914 dev[0].request("AP_SCAN 1")
4915
4916 def _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
4917 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4918 iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
4919
4920 if "OK" not in dev[0].request("AP_SCAN 2"):
4921 raise Exception("Failed to set AP_SCAN 2")
4922
4923 id = dev[0].add_network()
4924 dev[0].set_network(id, "mode", "2")
4925 dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
4926 dev[0].set_network(id, "key_mgmt", "NONE")
4927 dev[0].set_network(id, "frequency", "2412")
4928 dev[0].set_network(id, "scan_freq", "2412")
4929 dev[0].set_network(id, "disabled", "0")
4930 dev[0].select_network(id)
4931 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
4932 if ev is None:
4933 raise Exception("AP failed to start")
4934
4935 with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
4936 iface.Scan({'Type': 'active',
4937 'AllowRoam': True,
4938 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
4939 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
4940 "AP-DISABLED"], timeout=5)
4941 if ev is None:
4942 raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
4943 if "AP-DISABLED" in ev:
4944 raise Exception("Unexpected AP-DISABLED event")
4945 if "retry=1" in ev:
4946 # Wait for the retry to scan happen
4947 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
4948 "AP-DISABLED"], timeout=5)
4949 if ev is None:
4950 raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
4951 if "AP-DISABLED" in ev:
4952 raise Exception("Unexpected AP-DISABLED event - retry")
4953
4954 dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
4955 dev[1].request("DISCONNECT")
4956 dev[1].wait_disconnected()
4957 dev[0].request("DISCONNECT")
4958 dev[0].wait_disconnected()
4959
4960 def test_dbus_expectdisconnect(dev, apdev):
4961 """D-Bus ExpectDisconnect"""
4962 (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
4963 wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
4964
4965 params = { "ssid": "test-open" }
4966 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4967 dev[0].connect("test-open", key_mgmt="NONE", scan_freq="2412")
4968
4969 # This does not really verify the behavior other than by going through the
4970 # code path for additional coverage.
4971 wpas.ExpectDisconnect()
4972 dev[0].request("DISCONNECT")
4973 dev[0].wait_disconnected()