eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

commit 6c92f32106f00e2a43366c97f0167722099646ac
parent 4082c86e5243da58b2f491562da77626dbbfd565
Author: illiliti <illiliti@protonmail.com>
Date:   Thu, 21 Apr 2022 19:18:08 +0300

Merge tag '1.27'

Release 1.27

Diffstat:
MAUTHORS | 2++
MChangeLog | 13+++++++++++++
Mautotests/testAP/connection_test.py | 10+---------
Mautotests/testAP/dhcp_config_test.py | 8--------
Mautotests/testAP/dhcp_test.py | 8--------
Mautotests/testAP/failure_test.py | 10+---------
Mautotests/testAPRoam/connection_test.py | 5++---
Mautotests/testBSSBlacklist/connection_test.py | 40++++++++++++++++------------------------
Mautotests/testClientNonInteractive/connect_command_test.py | 28+++++++++-------------------
Mautotests/testDPP/connection_test.py | 5+++--
Mautotests/testDPP/wpas.conf | 2+-
Mautotests/testDisconnectByAP/disconnect_by_ap_test.py | 7+------
Mautotests/testFT-8021x-roam/connection_test.py | 4++--
Mautotests/testFT-FILS/connection_test.py | 21++++++---------------
Mautotests/testHT-VHT/connection_test.py | 15++-------------
Mautotests/testNetconfig/connection_test.py | 23++++++++++++++++-------
Mautotests/testNetconfig/static_test.py | 10+++-------
Mautotests/testOWE-transition/connection_test.py | 23+----------------------
Mautotests/testOWE/connection_test.py | 2+-
Mautotests/testP2P/connection_test.py | 4+++-
Mautotests/testPSK-roam/connection_test.py | 29++++-------------------------
Mautotests/testPSK-roam/roam_ap_disconnect_test.py | 2+-
Mautotests/testPreauth-roam/connection_test.py | 4++--
Mautotests/testRRM/connection_test.py | 32+++++++++++---------------------
Mautotests/testRSSIAgent/connection_test.py | 13+------------
Mautotests/testRoamRetry/fast_retry_test.py | 13++++++-------
Mautotests/testRoamRetry/stop_retry_test.py | 7+++----
Mautotests/testSAE-AntiClogging/clogging_test.py | 10+---------
Mautotests/testSAE-roam/connection_test.py | 30+++++++++++++-----------------
Mautotests/testSAE/connection_test.py | 14+-------------
Mautotests/testWPA2-ext-key-id/connection_test.py | 2++
Mautotests/util/hostapd.py | 68++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mautotests/util/hwsim.py | 1+
Mautotests/util/iwd.py | 50++++++++++++++++++++++++--------------------------
Mautotests/util/testutil.py | 16+++++++++++-----
Mautotests/util/wpas.py | 5++++-
Mclient/ap.c | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mclient/daemon.c | 22+++++++++++++++-------
Mclient/display.h | 4++--
Mconfigure.ac | 4++--
Mdoc/access-point-api.txt | 22++++++++++++++++++++++
Mdoc/hwsim-radio-api.txt | 32++++++++++++++++++++++++--------
Mdoc/test-runner.txt | 34++++++++++++++++++++++++----------
Mmonitor/nlmon.c | 90++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Msrc/ap.c | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/band.c | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Msrc/band.h | 1+
Msrc/dpp-util.c | 4++--
Msrc/dpp.c | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Msrc/eapol.c | 2+-
Msrc/ie.h | 48+++++++++++++++++++++++++++++++-----------------
Msrc/json.c | 2++
Msrc/knownnetworks.c | 4+++-
Msrc/netdev.c | 9+++++++--
Msrc/network.c | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Msrc/p2p.c | 10+++++++---
Msrc/rrm.c | 4++--
Msrc/scan.c | 23++++++++++++++++++++++-
Msrc/scan.h | 3+++
Msrc/station.c | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Msrc/storage.c | 1+
Msrc/util.c | 53+++++++++++++++++++++++++++++++++++++++++------------
Msrc/wiphy.c | 21+++++++++++++++++++++
Msrc/wiphy.h | 17+++++++++++------
Msrc/wsc.c | 1+
Mtools/hwsim.c | 8++++++++
Atools/run-tests | 1013+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/runner.py | 540+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/test-runner | 1886+------------------------------------------------------------------------------
Mtools/test_runner_kernel_config | 17+++++++++++++++++
Atools/utils.py | 519+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Munit/test-band.c | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mwired/ethdev.c | 25+++++++++++++++++--------
Mwired/network.c | 5++++-
74 files changed, 3460 insertions(+), 2361 deletions(-)

diff --git a/AUTHORS b/AUTHORS @@ -34,3 +34,5 @@ Matt Oberle <matt.r.oberle@gmail.com> Marc-Antoine Perennou <Marc-Antoine@Perennou.com> Torsten Schmitz <noreply.torsten@gmail.com> Diederik de Haas <didi.debian@cknow.org> +VladimĂ­r Dudr <vladimir@tango-dj.cz> +Emmanuel VAUTRIN <Emmanuel.VAUTRIN@cpexterne.org> diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,16 @@ +ver 1.27: + Fix issue with hidden networks on connection error. + Fix issue with directed roams if already trying to roam. + Fix issue with checking for connected in FT frame event. + +ver 1.26: + Fix issue with handling BSS that changed frequency. + Fix issue with handling frequencies in neighbor report. + Fix issue with operating classes for 802.11ax standard. + Fix issue with enforcing of MFPR for 6 GHz frequencies. + Add support for band defined in the WiFi 6E amendment. + Add support for scanning while in AP mode. + ver 1.25: Fix issue with handling abort of periodic scans. Fix issue with handling connection when link goes down. diff --git a/autotests/testAP/connection_test.py b/autotests/testAP/connection_test.py @@ -47,16 +47,8 @@ class Test(unittest.TestCase): dev1.start_ap('TestAP2', 'Password2') try: - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - dev2.scan() - condition = 'obj.scanning' - wd.wait_for_object_condition(dev2, condition) - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - networks = {} - networks['TestAP1'] = dev2.get_ordered_network('TestAP1') + networks['TestAP1'] = dev2.get_ordered_network('TestAP1', full_scan=True) networks['TestAP2'] = dev2.get_ordered_network('TestAP2', full_scan=True) self.assertEqual(networks['TestAP1'].type, NetworkType.psk) diff --git a/autotests/testAP/dhcp_config_test.py b/autotests/testAP/dhcp_config_test.py @@ -29,14 +29,6 @@ class Test(unittest.TestCase): dev1.start_ap('APConfig') try: - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - dev2.scan() - condition = 'obj.scanning' - wd.wait_for_object_condition(dev2, condition) - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - networks = {} networks['APConfig'] = dev2.get_ordered_network('APConfig', full_scan=True) diff --git a/autotests/testAP/dhcp_test.py b/autotests/testAP/dhcp_test.py @@ -26,14 +26,6 @@ class Test(unittest.TestCase): dev4.start_ap('TestAP4', 'Password4') try: - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - dev2.scan() - condition = 'obj.scanning' - wd.wait_for_object_condition(dev2, condition) - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - networks = {} networks['TestAP2'] = dev2.get_ordered_network('TestAP2', full_scan=True) diff --git a/autotests/testAP/failure_test.py b/autotests/testAP/failure_test.py @@ -48,16 +48,8 @@ class Test(unittest.TestCase): dev1.start_ap('TestAP2', 'Password2') try: - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - dev2.scan() - condition = 'obj.scanning' - wd.wait_for_object_condition(dev2, condition) - condition = 'not obj.scanning' - wd.wait_for_object_condition(dev2, condition) - networks = {} - networks['TestAP1'] = dev2.get_ordered_network('TestAP1') + networks['TestAP1'] = dev2.get_ordered_network('TestAP1', full_scan=True) networks['TestAP2'] = dev2.get_ordered_network('TestAP2', full_scan=True) self.assertEqual(networks['TestAP1'].type, NetworkType.psk) diff --git a/autotests/testAPRoam/connection_test.py b/autotests/testAPRoam/connection_test.py @@ -36,7 +36,6 @@ class Test(unittest.TestCase): bss_hostapd[0].wait_for_event('AP-STA-CONNECTED') - self.assertTrue(bss_hostapd[0].list_sta()) self.assertFalse(bss_hostapd[1].list_sta()) bss_hostapd[0].send_bss_transition(device.address, @@ -51,8 +50,8 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertEqual(device.state, iwd.DeviceState.connected) - self.assertTrue(bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) + device.disconnect() condition = 'not obj.connected' diff --git a/autotests/testBSSBlacklist/connection_test.py b/autotests/testBSSBlacklist/connection_test.py @@ -33,7 +33,7 @@ class Test(unittest.TestCase): dev1, dev2 = wd.list_devices(2) - ordered_network = dev1.get_ordered_network("TestBlacklist") + ordered_network = dev1.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -45,12 +45,12 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(dev1, condition) - self.assertIn(dev1.address, bss_hostapd[2].list_sta()) + bss_hostapd[2].wait_for_event('AP-STA-CONNECTED %s' % dev1.address) # dev1 now connected, this should max out the first AP, causing the next # connection to fail to this AP. - ordered_network = dev2.get_ordered_network("TestBlacklist") + ordered_network = dev2.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -64,7 +64,7 @@ class Test(unittest.TestCase): # We should have temporarily blacklisted the first BSS, and connected # to this one. - self.assertIn(dev2.address, bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % dev2.address) # Now check that the first BSS is still not blacklisted. We can # disconnect dev1, opening up the AP for more connections @@ -83,7 +83,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(dev2, condition) - self.assertIn(dev2.address, bss_hostapd[2].list_sta()) + bss_hostapd[2].wait_for_event('AP-STA-CONNECTED %s' % dev2.address) wd.unregister_psk_agent(psk_agent) @@ -101,7 +101,7 @@ class Test(unittest.TestCase): devices = wd.list_devices(1) device = devices[0] - ordered_network = device.get_ordered_network("TestBlacklist") + ordered_network = device.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -110,11 +110,11 @@ class Test(unittest.TestCase): # Have both APs drop all packets, both should get blacklisted rule0.drop = True - rule0.enable = True + rule0.enabled = True rule1.drop = True - rule1.enable = True + rule1.enabled = True rule2.drop = True - rule2.enable = True + rule2.enabled = True with self.assertRaises(iwd.FailedEx): ordered_network.network_object.connect() @@ -134,7 +134,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertIn(device.address, bss_hostapd[0].list_sta()) + bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) wd.unregister_psk_agent(psk_agent) @@ -148,7 +148,7 @@ class Test(unittest.TestCase): devices = wd.list_devices(1) device = devices[0] - ordered_network = device.get_ordered_network("TestBlacklist") + ordered_network = device.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -188,7 +188,7 @@ class Test(unittest.TestCase): devices[1].disconnect() - ordered_network = device.get_ordered_network("TestBlacklist") + ordered_network = device.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -214,7 +214,7 @@ class Test(unittest.TestCase): # should automatically try the next BSS in the list, which is # bss_hostapd[1] self.assertNotIn(device.address, bss_hostapd[0].list_sta()) - self.assertIn(device.address, bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) rule0.drop = False @@ -234,7 +234,7 @@ class Test(unittest.TestCase): # Same as before, make sure we didn't connect to the blacklisted AP. self.assertNotIn(device.address, bss_hostapd[0].list_sta()) - self.assertIn(device.address, bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) # Wait for the blacklist to expire (10 seconds) elapsed = time.time() - start @@ -244,15 +244,7 @@ class Test(unittest.TestCase): device.disconnect() - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network("TestBlacklist") + ordered_network = device.get_ordered_network("TestBlacklist", full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -264,7 +256,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertIn(device.address, bss_hostapd[0].list_sta()) + bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) self.wd.unregister_psk_agent(psk_agent) diff --git a/autotests/testClientNonInteractive/connect_command_test.py b/autotests/testClientNonInteractive/connect_command_test.py @@ -11,13 +11,9 @@ import subprocess from config import ctx class Test(unittest.TestCase): - def check_connection_success(self, ssid): device = self.wd.list_devices(1)[0] - condition = 'not obj.scanning' - self.wd.wait_for_object_condition(device, condition) - ordered_network = device.get_ordered_network(ssid) condition = 'obj.state == DeviceState.connected' @@ -28,9 +24,14 @@ class Test(unittest.TestCase): condition = 'not obj.connected' self.wd.wait_for_object_condition(ordered_network.network_object, condition) + def establish_network(self, ssid): + device = self.wd.list_devices(1)[0] + device.get_ordered_network(ssid) + def test_connection_with_passphrase(self): ssid = 'ssidPassphrase' + self.establish_network(ssid) device = self.wd.list_devices(1)[0] # Use --dontaks cmd-line option @@ -45,6 +46,7 @@ class Test(unittest.TestCase): def test_connection_with_username_and_password(self): ssid = 'ssidUNameAndPWord' + self.establish_network(ssid) device = self.wd.list_devices(1)[0] ctx.start_process(['iwctl', '-u', 'user', '-p', 'password', 'station', \ @@ -54,6 +56,7 @@ class Test(unittest.TestCase): def test_connection_with_password(self): ssid = 'ssidPWord' + self.establish_network(ssid) device = self.wd.list_devices(1)[0] ctx.start_process(['iwctl', '-p', 'password', 'station', device.name, 'connect', ssid], @@ -64,6 +67,7 @@ class Test(unittest.TestCase): def test_connection_failure(self): ssid = 'ssidPassphrase' + self.establish_network(ssid) device = self.wd.list_devices(1)[0] with self.assertRaises(subprocess.CalledProcessError): @@ -73,14 +77,13 @@ class Test(unittest.TestCase): def test_invalid_command_line_option(self): ssid = 'ssidPassphrase' + self.establish_network(ssid) device = self.wd.list_devices(1)[0] with self.assertRaises(subprocess.CalledProcessError): ctx.start_process(['iwctl', '-z', 'station', device.name, 'connect', ssid], check=True) def test_invalid_command(self): - device = self.wd.list_devices(1)[0] - with self.assertRaises(subprocess.CalledProcessError): ctx.start_process(['iwctl', 'inexistent', 'command'], check=True) @@ -91,19 +94,6 @@ class Test(unittest.TestCase): cls.wd = IWD() - device = cls.wd.list_devices(1)[0] - - condition = 'not obj.scanning' - cls.wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'obj.scanning' - cls.wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - cls.wd.wait_for_object_condition(device, condition) - @classmethod def tearDownClass(cls): IWD.clear_storage() diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -80,7 +80,7 @@ class Test(unittest.TestCase): self.wpas.dpp_enrollee_start(uri) - self.wpas.wait_for_event('DPP-CONF-RECEIVED') + self.wpas.wait_for_event('DPP-CONF-RECEIVED', timeout=30) def test_iwd_as_configurator_initiator(self): self.hapd.reload() @@ -96,7 +96,7 @@ class Test(unittest.TestCase): self.device.dpp_start_configurator(uri) - self.hapd.wait_for_event('AP-STA-CONNECTED 42:00:00:00:00:00') + self.wpas.wait_for_event('DPP-CONF-RECEIVED', timeout=30) def setUp(self): self.wd = IWD(True) @@ -118,6 +118,7 @@ class Test(unittest.TestCase): self.device.disconnect() self.device.dpp_stop() self.wpas.dpp_configurator_remove() + self.wpas.clean_up() self.wd = None self.device = None diff --git a/autotests/testDPP/wpas.conf b/autotests/testDPP/wpas.conf @@ -1,5 +1,5 @@ ctrl_interface=/tmp/rad1-p2p-wpas -update_config=1 +update_config=0 pmf=2 dpp_config_processing=2 diff --git a/autotests/testDisconnectByAP/disconnect_by_ap_test.py b/autotests/testDisconnectByAP/disconnect_by_ap_test.py @@ -21,12 +21,7 @@ class Test(unittest.TestCase): hostapd = HostapdCLI(config='ssidOpen.conf') - device.scan() - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network('ssidOpen') + ordered_network = device.get_ordered_network('ssidOpen', full_scan=True) ordered_network.network_object.connect() diff --git a/autotests/testFT-8021x-roam/connection_test.py b/autotests/testFT-8021x-roam/connection_test.py @@ -27,7 +27,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) self.assertFalse(self.bss_hostapd[1].list_sta()) testutil.test_iface_operstate(device.name) @@ -46,7 +46,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(self.bss_hostapd[1].list_sta()) + self.bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[1].ifname, device.name) diff --git a/autotests/testFT-FILS/connection_test.py b/autotests/testFT-FILS/connection_test.py @@ -13,21 +13,10 @@ class Test(unittest.TestCase): def validate_connection(self, wd): device = wd.list_devices(1)[0] - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - # Scanning is unavoidable in this case since both FILS-SHA256 and # FILS-SHA384 are tested. Without a new scan the cached scan results # would cause IWD to choose an incorrect AKM for the second test. - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network('TestFT') + ordered_network = device.get_ordered_network('TestFT', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.eap) @@ -39,7 +28,8 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) + self.assertFalse(self.bss_hostapd[1].list_sta()) testutil.test_iface_operstate(device.name) @@ -62,7 +52,8 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) + self.assertFalse(self.bss_hostapd[1].list_sta()) testutil.test_iface_operstate(device.name) @@ -88,7 +79,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(self.bss_hostapd[1].list_sta()) + self.bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[1].ifname, device.name) diff --git a/autotests/testHT-VHT/connection_test.py b/autotests/testHT-VHT/connection_test.py @@ -14,22 +14,11 @@ from hostapd import HostapdCLI class Test(unittest.TestCase): def do_connect(self, wd, device, hostapd): - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - # # Scanning must be explicitly done to get updated RSSI values. Therefore - # scan_if_needed is set false because of the previous scan. + # full_scan is set. # - ordered_network = device.get_ordered_network('testSSID', scan_if_needed=False) + ordered_network = device.get_ordered_network('testSSID', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) diff --git a/autotests/testNetconfig/connection_test.py b/autotests/testNetconfig/connection_test.py @@ -12,10 +12,20 @@ from hostapd import HostapdCLI import testutil from config import ctx import os, time +import subprocess class Test(unittest.TestCase): def test_connection_success(self): + def check_addr(device): + try: + subprocess.check_output('ip addr show ' + device.name + \ + ' | grep \'inet6 3ffe:501:ffff:100::\'', shell=True) + except: + return False + + return True + wd = IWD(True) psk_agent = PSKAgent("secret123") @@ -39,9 +49,8 @@ class Test(unittest.TestCase): testutil.test_iface_operstate() testutil.test_ifaces_connected() - time.sleep(2) - ret = os.system('ip addr show ' + device.name + ' | grep \'inet6 3ffe:501:ffff:100::\'') - self.assertEqual(os.waitstatus_to_exitcode(ret), 0) + ctx.non_block_wait(check_addr, 10, device, + exception=Exception("IPv6 address was not set")) device.disconnect() @@ -69,15 +78,15 @@ class Test(unittest.TestCase): # TODO: This could be moved into test-runner itself if other tests ever # require this functionality (p2p, FILS, etc.). Since its simple # enough it can stay here for now. - ctx.start_process(['ip', 'addr','add','dev', hapd.ifname, - '192.168.1.1/255.255.255.0']).wait() + ctx.start_process(['ip', 'addr','add', '192.168.1.1/255.255.255.0', + 'dev', hapd.ifname,]).wait() ctx.start_process(['touch', '/tmp/dhcpd.leases']).wait() cls.dhcpd_pid = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcpd.leases', hapd.ifname], cleanup=remove_lease4) - ctx.start_process(['ip', 'addr', 'add', 'dev', hapd.ifname, - '3ffe:501:ffff:100::1/64']).wait() + ctx.start_process(['ip', 'addr', 'add', '3ffe:501:ffff:100::1/64', + 'dev', hapd.ifname]).wait() ctx.start_process(['touch', '/tmp/dhcpd6.leases']).wait() cls.dhcpd6_pid = ctx.start_process(['dhcpd', '-6', '-f', '-cf', '/tmp/dhcpd-v6.conf', '-lf', '/tmp/dhcpd6.leases', diff --git a/autotests/testNetconfig/static_test.py b/autotests/testNetconfig/static_test.py @@ -47,12 +47,7 @@ class Test(unittest.TestCase): testutil.test_ip_address_match(dev1.name, '192.168.1.10') - dev2.scan() - - condition = 'not obj.scanning' - wd_ns0.wait_for_object_condition(dev2, condition) - - ordered_network = dev2.get_ordered_network('ssidTKIP', scan_if_needed=True) + ordered_network = dev2.get_ordered_network('ssidTKIP') condition = 'not obj.connected' wd_ns0.wait_for_object_condition(ordered_network.network_object, condition) @@ -86,7 +81,8 @@ class Test(unittest.TestCase): # TODO: This could be moved into test-runner itself if other tests ever # require this functionality (p2p, FILS, etc.). Since its simple # enough it can stay here for now. - ctx.start_process(['ip', 'addr','add', hapd.ifname, '192.168.1.1/255.255.255.0']).wait() + ctx.start_process(['ip', 'addr','add', '192.168.1.1/255.255.255.0', + 'dev', hapd.ifname]).wait() ctx.start_process(['touch', '/tmp/dhcpd.leases']).wait() cls.dhcpd_pid = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcpd.leases', diff --git a/autotests/testOWE-transition/connection_test.py b/autotests/testOWE-transition/connection_test.py @@ -20,18 +20,7 @@ class Test(unittest.TestCase): if not autoconnect: if not connect_hidden: - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - network = device.get_ordered_network('transition', scan_if_needed=False) + network = device.get_ordered_network('transition', full_scan=True) network.network_object.connect() else: @@ -241,16 +230,6 @@ class Test(unittest.TestCase): self.rule0.signal = -4000 self.rule0.enabled = True - devices = self.wd.list_devices(1) - device = devices[0] - - device.scan() - condition = 'obj.scanning' - self.wd.wait_for_object_condition(device, condition) - condition = 'not obj.scanning' - self.wd.wait_for_object_condition(device, condition) - - self.validate(self.wd, self.hapd_owe) def setUp(self): diff --git a/autotests/testOWE/connection_test.py b/autotests/testOWE/connection_test.py @@ -60,7 +60,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(hapd1.list_sta()) + hapd1.wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(hapd1.ifname, device.name) diff --git a/autotests/testP2P/connection_test.py b/autotests/testP2P/connection_test.py @@ -11,6 +11,8 @@ import testutil from config import ctx from wpas import Wpas +from utils import Process + class Test(unittest.TestCase): leases_path = '/tmp/dhcp.lease' @@ -110,7 +112,7 @@ class Test(unittest.TestCase): self.assertEqual(wpas.p2p_group['go_ip_addr'], '192.168.1.1') extra_params = [] - if ctx.is_verbose('dhclient'): + if Process.is_verbose('dhclient'): extra_params.append('-v') dhcp = ctx.start_process(['dhclient', '-d', '--no-pid', '-cf', '/dev/null', '-lf', self.leases_path, diff --git a/autotests/testPSK-roam/connection_test.py b/autotests/testPSK-roam/connection_test.py @@ -16,20 +16,7 @@ class Test(unittest.TestCase): def validate_connection(self, wd, over_ds=False): device = wd.list_devices(1)[0] - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - # Scanning is unavoidable in this case since several hostapd - # configurations are tested and changed mid-test - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network('TestFT') + ordered_network = device.get_ordered_network('TestFT', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -44,15 +31,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) - - # list_sta actually reports any authenticated stations. Due to the - # nature of FT-over-DS IWD should authenticate to all stations with - # the same mobility domain. This means both APs should show our station. - if over_ds: - self.assertTrue(self.bss_hostapd[1].list_sta()) - else: - self.assertFalse(self.bss_hostapd[1].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[0].ifname, device.name) @@ -73,7 +52,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(self.bss_hostapd[1].list_sta()) + self.bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[1].ifname, device.name) @@ -93,7 +72,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[0].ifname, device.name) diff --git a/autotests/testPSK-roam/roam_ap_disconnect_test.py b/autotests/testPSK-roam/roam_ap_disconnect_test.py @@ -32,8 +32,8 @@ class Test(unittest.TestCase): # Since both BSS's have low signal, the roam should fail and trigger # another roam scan. - device.wait_for_event('no-roam-candidates', timeout=30) device.wait_for_event('roam-scan-triggered', timeout=30) + device.wait_for_event('no-roam-candidates', timeout=30) # Hostapd sends disconnect self.bss_hostapd[0].disable() diff --git a/autotests/testPreauth-roam/connection_test.py b/autotests/testPreauth-roam/connection_test.py @@ -49,7 +49,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(bss_hostapd[0].list_sta()) + bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) self.assertFalse(bss_hostapd[1].list_sta()) testutil.test_iface_operstate(device.name) @@ -70,7 +70,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(bss_hostapd[1].ifname, device.name) diff --git a/autotests/testRRM/connection_test.py b/autotests/testRRM/connection_test.py @@ -11,8 +11,6 @@ from iwd import NetworkType from hostapd import HostapdCLI import testutil -from time import sleep - # Table beacon with wildcard BSSID basic_beacon = '51000000000002ffffffffffff020100' # Table beacon with wildcard BSSID and SSID filter @@ -53,51 +51,43 @@ class Test(unittest.TestCase): hapd.wait_for_event('AP-STA-CONNECTED') + wd.wait(1) + # This should return both APs hapd.req_beacon(device.address, basic_beacon) for e in ['BEACON-RESP-RX', 'BEACON-RESP-RX']: - event = hapd.wait_for_event(e) - if event: - print(event) + hapd.wait_for_event(e) - sleep(0.5) + wd.wait(1) # This should return just ssidRRM hapd.req_beacon(device.address, beacon_with_ssid) - event = hapd.wait_for_event('BEACON-RESP-RX') - if event: - print(event) + hapd.wait_for_event('BEACON-RESP-RX') - sleep(0.5) + wd.wait(1) # This should passive scan on channel 11, returning otherSSID hapd.req_beacon(device.address, beacon_passive) # TODO: See if we are scanning here (scan not initiated from station) - event = hapd.wait_for_event('BEACON-RESP-RX') - if event: - print(event) + hapd.wait_for_event('BEACON-RESP-RX') - sleep(0.5) + wd.wait(1) # This should active scan on channel 11, returning otherSSID hapd.req_beacon(device.address, beacon_active) # TODO: See if we are scanning here (scan not initiated from station) - event = hapd.wait_for_event('BEACON-RESP-RX') - if event: - print(event) + hapd.wait_for_event('BEACON-RESP-RX') - sleep(0.5) + wd.wait(1) # This should passive scan on channel 11, returning otherSSID hapd.req_beacon(device.address, beacon_passive_duration) # TODO: See if we are scanning here (scan not initiated from station) - event = hapd.wait_for_event('BEACON-RESP-RX') - if event: - print(event) + hapd.wait_for_event('BEACON-RESP-RX') device.disconnect() diff --git a/autotests/testRSSIAgent/connection_test.py b/autotests/testRSSIAgent/connection_test.py @@ -31,18 +31,7 @@ class Test(unittest.TestCase): agent.calls = 0 device.register_signal_agent(agent, [-20, -40, -60, -80]) - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network('TestOpen') + ordered_network = device.get_ordered_network('TestOpen', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.open) self.assertEqual(ordered_network.signal_strength, -4000) diff --git a/autotests/testRoamRetry/fast_retry_test.py b/autotests/testRoamRetry/fast_retry_test.py @@ -63,7 +63,7 @@ class Test(unittest.TestCase): devices = wd.list_devices(1) device = devices[0] - ordered_network = device.get_ordered_network('TestRoamRetry') + ordered_network = device.get_ordered_network('TestRoamRetry', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -75,18 +75,18 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(bss_hostapd[0].list_sta()) - self.assertFalse(bss_hostapd[1].list_sta()) + bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) wd.wait(5) # Now push the signal LOW, wait for iwd to attempt a roam, fail, and - # schedule another attempt for 60 seconds later + # schedule another attempt rule0.signal = -8000 device.wait_for_event('no-roam-candidates') self.assertEqual(device.state, iwd.DeviceState.connected) + self.assertTrue(bss_hostapd[0].list_sta()) self.assertFalse(bss_hostapd[1].list_sta()) @@ -101,12 +101,11 @@ class Test(unittest.TestCase): wd.wait(1) # Assert low signal for BSS 0, check that iwd starts transition to BSS 1 - # in less than 10 seconds. rule0.signal = -8000 rule1.signal = -2000 condition = 'obj.state == DeviceState.roaming' - wd.wait_for_object_condition(device, condition, max_wait=15) + wd.wait_for_object_condition(device, condition) # Check that iwd is on BSS 1 once out of roaming state and doesn't # go through 'disconnected', 'autoconnect', 'connecting' in between @@ -114,7 +113,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) device.disconnect() diff --git a/autotests/testRoamRetry/stop_retry_test.py b/autotests/testRoamRetry/stop_retry_test.py @@ -62,7 +62,7 @@ class Test(unittest.TestCase): devices = wd.list_devices(1) device = devices[0] - ordered_network = device.get_ordered_network('TestRoamRetry') + ordered_network = device.get_ordered_network('TestRoamRetry', full_scan=True) self.assertEqual(ordered_network.type, NetworkType.psk) @@ -74,8 +74,7 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(bss_hostapd[0].list_sta()) - self.assertFalse(bss_hostapd[1].list_sta()) + bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) # Now push the signal below the RSSI threshold and check that iwd # connects to BSS 1 @@ -90,7 +89,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(bss_hostapd[1].list_sta()) + bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) # Now make sure that we don't roam anymore. In order to catch this via # DeviceState, a suitable roaming target needs to be available. So jack diff --git a/autotests/testSAE-AntiClogging/clogging_test.py b/autotests/testSAE-AntiClogging/clogging_test.py @@ -21,16 +21,8 @@ class Test(unittest.TestCase): devices = wd.list_devices(4) self.assertIsNotNone(devices) - for d in devices: - d.disconnect() - d.scan() - wd.wait_for_object_condition(d, 'obj.scanning') - - for d in devices: - wd.wait_for_object_condition(d, 'not obj.scanning') - for i in range(len(devices)): - network = devices[i].get_ordered_network('ssidSAE-Clogging') + network = devices[i].get_ordered_network('ssidSAE-Clogging', full_scan=True) self.assertEqual(network.type, NetworkType.psk) networks.append(network) diff --git a/autotests/testSAE-roam/connection_test.py b/autotests/testSAE-roam/connection_test.py @@ -16,16 +16,9 @@ class Test(unittest.TestCase): def validate_connection(self, wd, ft=True): device = wd.list_devices(1)[0] - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'obj.scanning' - wd.wait_for_object_condition(device, condition) - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) + # This won't guarantee all BSS's are found, but at least ensures that + # at least one will be. + device.get_ordered_network('TestFT', full_scan=True) self.assertFalse(self.bss_hostapd[0].list_sta()) self.assertFalse(self.bss_hostapd[1].list_sta()) @@ -35,7 +28,8 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) - self.assertTrue(self.bss_hostapd[0].list_sta()) + self.bss_hostapd[0].wait_for_event('AP-STA-CONNECTED %s' % device.address) + self.assertFalse(self.bss_hostapd[1].list_sta()) testutil.test_iface_operstate(device.name) @@ -54,7 +48,7 @@ class Test(unittest.TestCase): to_condition = 'obj.state == DeviceState.connected' wd.wait_for_object_change(device, from_condition, to_condition) - self.assertTrue(self.bss_hostapd[1].list_sta()) + self.bss_hostapd[1].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[1].ifname, device.name) @@ -72,8 +66,10 @@ class Test(unittest.TestCase): condition = 'obj.state != DeviceState.roaming' wd.wait_for_object_condition(device, condition) - self.assertEqual(device.state, iwd.DeviceState.connected) - self.assertTrue(self.bss_hostapd[2].list_sta()) + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + self.bss_hostapd[2].wait_for_event('AP-STA-CONNECTED %s' % device.address) testutil.test_iface_operstate(device.name) testutil.test_ifaces_connected(self.bss_hostapd[2].ifname, device.name) @@ -124,13 +120,13 @@ class Test(unittest.TestCase): HostapdCLI(config='ft-sae-2.conf'), HostapdCLI(config='ft-psk-3.conf') ] - ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[0].ifname, 'down']) + ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[0].ifname, 'down']).wait() ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[0].ifname, \ 'addr', '12:00:00:00:00:01', 'up']).wait() - ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[1].ifname, 'down']) + ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[1].ifname, 'down']).wait() ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[1].ifname, \ 'addr', '12:00:00:00:00:02', 'up']).wait() - ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[2].ifname, 'down']) + ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[2].ifname, 'down']).wait() ctx.start_process(['ip', 'link', 'set', 'dev', cls.bss_hostapd[2].ifname, \ 'addr', '12:00:00:00:00:03', 'up']).wait() diff --git a/autotests/testSAE/connection_test.py b/autotests/testSAE/connection_test.py @@ -23,19 +23,7 @@ class Test(unittest.TestCase): device.disconnect() - wd.wait_for_object_condition(device, 'not obj.scanning') - - device.debug_scan([2412]) - - wd.wait_for_object_condition(device, 'obj.scanning') - wd.wait_for_object_condition(device, 'not obj.scanning') - - # - # An explicit scan was done prior due to hostapd options changing. - # Because of this scan_if_needed is set to False to avoid a redundant - # scan - # - network = device.get_ordered_network('ssidSAE', scan_if_needed=False) + network = device.get_ordered_network('ssidSAE', full_scan=True) self.assertEqual(network.type, NetworkType.psk) diff --git a/autotests/testWPA2-ext-key-id/connection_test.py b/autotests/testWPA2-ext-key-id/connection_test.py @@ -50,6 +50,8 @@ class Test(unittest.TestCase): testutil.test_iface_operstate() testutil.test_ifaces_connected() + wd.wait(0.5) + device.disconnect() condition = 'not obj.connected' diff --git a/autotests/util/hostapd.py b/autotests/util/hostapd.py @@ -81,27 +81,48 @@ class HostapdCLI(object): self.ctrl_sock.connect(self.socket_path + '/' + self.ifname) + self.events = [] + self.io_watch = GLib.io_add_watch(self.ctrl_sock, GLib.IO_IN, self._handle_data_in) + if 'OK' not in self._ctrl_request('ATTACH'): raise Exception('ATTACH failed') ctrl_count = ctrl_count + 1 - def _poll_event(self, event): - if not self._data_available(0.25): - return False + def _handle_data_in(self, sock, *args): + newdata = sock.recv(4096) + + decoded = newdata.decode('utf-8') + if len(decoded) >= 3 and decoded[0] == '<' and decoded[2] == '>': + decoded = decoded[3:] + while len(decoded) and decoded[-1] == '\n': + decoded = decoded[:-1] + + self.events.insert(0, decoded) + + return True - data = self.ctrl_sock.recv(4096).decode('utf-8') - if event in data: - return data + def _poll_event(self, event): + # Look through the list (most recent is first) until the even is found. + # Once found consume this event and any older ones as to not + # accidentally trigger a false positive later on. + for idx, e in enumerate(self.events): + if event in e: + self.events = self.events[:idx] + return e return False def wait_for_event(self, event, timeout=10): + if event == 'AP-ENABLED': + if self.enabled: + return 'AP-ENABLED' + return ctx.non_block_wait(self._poll_event, timeout, event, exception=TimeoutError("waiting for event")) - def _data_available(self, timeout=2): - [r, w, e] = select.select([self.ctrl_sock], [], [], timeout) + def _data_available(self): + [r, w, e] = select.select([self.ctrl_sock], [], []) if r: return True return False @@ -228,25 +249,28 @@ class HostapdCLI(object): ctx.start_process(cmd).wait() self.wait_for_event('AP-CSA-FINISHED') - @property - def bssid(self): + def _get_status(self): + ret = {} + cmd = self.cmdline + ['status'] proc = ctx.start_process(cmd) proc.wait() - status = proc.out.split('\n') + status = proc.out.strip().split('\n') - bssid = [x for x in status if x.startswith('bssid')] - bssid = bssid[0].split('=') - return bssid[1] + for kv in status: + k, v = kv.split('=') + ret[k] = v + + return ret @property - def frequency(self): - cmd = self.cmdline + ['status'] - proc = ctx.start_process(cmd) - proc.wait() - status = proc.out.split('\n') + def bssid(self): + return self._get_status()['bssid[0]'] - frequency = [x for x in status if x.startswith('freq')][0] - frequency = frequency.split('=')[1] + @property + def frequency(self): + return int(self._get_status()['freq']) - return int(frequency) + @property + def enabled(self): + return self._get_status()['state'] == 'ENABLED' diff --git a/autotests/util/hwsim.py b/autotests/util/hwsim.py @@ -314,6 +314,7 @@ class RadioList(collections.Mapping): args = dbus.Dictionary({ 'Name': name, 'P2P': p2p_device, + 'NoVirtualInterface': True, }, signature='sv') if iftype_disable: diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -232,16 +232,14 @@ class StationDebug(IWDDBusAbstract): _iface_name = IWD_STATION_DEBUG_INTERFACE def __init__(self, *args, **kwargs): - self._last_event = None - self._last_event_data = [] + self._events = [] IWDDBusAbstract.__init__(self, *args, **kwargs) self._iface.connect_to_signal("Event", self._event_handler) def _event_handler(self, event, data): - self._last_event = event - self._last_event_data = data + self._events.insert(0, (event, data)) @property def autoconnect(self): @@ -257,19 +255,18 @@ class StationDebug(IWDDBusAbstract): frequencies = dbus.Array([dbus.UInt16(f) for f in frequencies]) self._iface.Scan(frequencies) - def wait_for_event(self, event, timeout=10): - try: - if self._last_event is not None: - return self._last_event_data + def _poll_event(self, event): + for idx, e in enumerate(self._events): + if event == e[0]: + # Consume any older events + self._events = self._events[:idx] + return True - ctx.non_block_wait(lambda s, e : s._last_event == e, timeout, self, event, - exception=TimeoutError("waiting for StationDebug.Event")) + return False - return self._last_event_data - finally: - # Consume the event - self._last_event_data = None - self._last_event = None + def wait_for_event(self, event, timeout=10): + return ctx.non_block_wait(self._poll_event, timeout, event, + exception=TimeoutError("waiting for event")) class DeviceProvisioning(IWDDBusAbstract): ''' @@ -492,17 +489,18 @@ class Device(IWDDBusAbstract): main sorting factor. ''' ordered_networks = [] - for bus_obj in self._station.GetOrderedNetworks(): - ordered_network = OrderedNetwork(bus_obj, self._bus, self._namespace) - ordered_networks.append(ordered_network) - - names = [x.name for x in ordered_networks] - - # all() will always return true if 'list' is empty - if all(x in names for x in list) and len(names) > 0: - return ordered_networks - elif not scan_if_needed: - return None + if not full_scan: + for bus_obj in self._station.GetOrderedNetworks(): + ordered_network = OrderedNetwork(bus_obj, self._bus, self._namespace) + ordered_networks.append(ordered_network) + + names = [x.name for x in ordered_networks] + + # all() will always return true if 'list' is empty + if all(x in names for x in list) and len(names) > 0: + return ordered_networks + elif not scan_if_needed: + return None condition = 'not obj.scanning' IWD._wait_for_object_condition(self, condition) diff --git a/autotests/util/testutil.py b/autotests/util/testutil.py @@ -134,10 +134,7 @@ SIOCGIFADDR = 0x8915 IFF_UP = 1 << 0 IFF_RUNNING = 1 << 6 -def test_iface_operstate(intf=None): - if not intf: - intf = iwd.IWD.get_instance().list_devices()[0].name - +def _test_operstate(intf): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) try: @@ -146,10 +143,19 @@ def test_iface_operstate(intf=None): # IFF_LOWER_UP and IFF_DORMANT not returned by SIOCGIFFLAGS if flags & (IFF_UP | IFF_RUNNING) != IFF_UP | IFF_RUNNING: - raise Exception(intf + ' operstate wrong') + return False + + return True finally: sock.close() +def test_iface_operstate(intf=None): + if not intf: + intf = iwd.IWD.get_instance().list_devices()[0].name + + ctx.non_block_wait(_test_operstate, 10, intf, + exception=Exception(intf + ' operstate wrong')) + def test_ip_address_match(intf, ip): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -3,8 +3,11 @@ import os import socket from gi.repository import GLib from config import ctx + import binascii +from utils import Process + ctrl_count = 0 class Wpas: @@ -31,7 +34,7 @@ class Wpas: self.io_watch = None cmd = ['wpa_supplicant', '-i', self.interface.name, '-c', self.config_path] - if ctx.is_verbose('wpa_supplicant-dbg'): + if Process.is_verbose('wpa_supplicant-dbg'): cmd += ['-d'] self.wpa_supplicant = ctx.start_process(cmd) diff --git a/client/ap.c b/client/ap.c @@ -35,6 +35,7 @@ struct ap { bool started; char *name; + bool scanning; }; static void *ap_create(void) @@ -104,9 +105,31 @@ static void update_name(void *data, struct l_dbus_message_iter *variant) ap->name = l_strdup(name); } +static void update_scanning(void *data, struct l_dbus_message_iter *variant) +{ + struct ap *ap = data; + bool value; + + if (!l_dbus_message_iter_get_variant(variant, "b", &value)) { + ap->scanning = false; + + return; + } + + ap->scanning = value; +} + +static const char *get_scanning_tostr(const void *data) +{ + const struct ap *ap = data; + + return ap->scanning ? "yes" : "no"; +} + static const struct proxy_interface_property ap_properties[] = { { "Started", "b", update_started, get_started_tostr }, { "Name", "s", update_name, get_name_tostr }, + { "Scanning", "b", update_scanning, get_scanning_tostr }, { } }; @@ -301,6 +324,95 @@ static enum cmd_status cmd_start_profile(const char *device_name, return CMD_STATUS_TRIGGERED; } +static enum cmd_status cmd_scan(const char *device_name, char **argv, int argc) +{ + const struct proxy_interface *ap_i; + + ap_i = device_proxy_find(device_name, IWD_ACCESS_POINT_INTERFACE); + if (!ap_i) { + display("No ap on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(ap_i, "Scan", "", + check_errors_method_callback); + + return CMD_STATUS_TRIGGERED; +} + +static void ap_display_network(struct l_dbus_message_iter *iter, + const char *margin, int name_width, + int value_width) +{ + const char *key; + struct l_dbus_message_iter variant; + + while (l_dbus_message_iter_next_entry(iter, &key, &variant)) { + const char *s; + int16_t n; + + if (!strcmp(key, "Name") || !strcmp(key, "Type")) { + if (!l_dbus_message_iter_get_variant(&variant, "s", &s)) + goto parse_error; + + display("%s%-*s%-*s\n", margin, name_width, key, + value_width, s); + } else if (!strcmp(key, "SignalStrength")) { + if (!l_dbus_message_iter_get_variant(&variant, "n", &n)) + goto parse_error; + + display("%s%-*s%-*i\n", margin, name_width, key, + value_width, n); + } + } + + return; + +parse_error: + display("Error displaying network results"); +} + +static void ap_get_networks_callback(struct l_dbus_message *message, + void *user_data) +{ + struct l_dbus_message_iter array; + struct l_dbus_message_iter iter; + + if (dbus_message_has_error(message)) + return; + + if (!l_dbus_message_get_arguments(message, "aa{sv}", &array)) { + display("Failed to parse GetDiagnostics message"); + return; + } + + display_table_header("Networks", " %-*s%-*s", + 20, "Property", 20, "Value"); + while (l_dbus_message_iter_next_entry(&array, &iter)) { + ap_display_network(&iter, " ", 20, 20); + display("\n"); + } + + display_table_footer(); +} + +static enum cmd_status cmd_get_networks(const char *device_name, char **argv, + int argc) +{ + const struct proxy_interface *ap_i; + + ap_i = device_proxy_find(device_name, IWD_ACCESS_POINT_INTERFACE); + if (!ap_i) { + display("No ap on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(ap_i, "GetOrderedNetworks", "", + ap_get_networks_callback); + + return CMD_STATUS_TRIGGERED; +} + static const struct command ap_commands[] = { { NULL, "list", NULL, cmd_list, "List devices in AP mode", true }, { "<wlan>", "start", "<\"network name\"> <passphrase>", cmd_start, @@ -311,6 +423,9 @@ static const struct command ap_commands[] = { { "<wlan>", "stop", NULL, cmd_stop, "Stop a started access\n" "\t\t\t\t\t\t point" }, { "<wlan>", "show", NULL, cmd_show, "Show AP info", false }, + { "<wlan>", "scan", NULL, cmd_scan, "Start an AP scan", false }, + { "<wlan>", "get-networks", NULL, cmd_get_networks, + "Get network list after scanning", false }, { } }; diff --git a/client/daemon.c b/client/daemon.c @@ -57,24 +57,26 @@ static void get_info_callback(struct l_dbus_message *message, void *user_data) if (dbus_message_has_error(message)) return; - if (!l_dbus_message_get_arguments(message, "a{sv}", &iter)) { - l_error("Failed to parse GetInfo message"); - return; - } + if (!l_dbus_message_get_arguments(message, "a{sv}", &iter)) + goto parse_failed; while (l_dbus_message_iter_next_entry(&iter, &key, &variant)) { if (strcmp(key, "NetworkConfigurationEnabled")) continue; - l_dbus_message_iter_get_variant(&variant, "b", - &netconfig_enabled); + if (!l_dbus_message_iter_get_variant(&variant, "b", + &netconfig_enabled)) + goto parse_failed; + break; } if (!command_is_interactive_mode()) return; - l_dbus_message_get_arguments(message, "a{sv}", &iter); + if (!l_dbus_message_get_arguments(message, "a{sv}", &iter)) + goto parse_failed; + display("NetworkConfigurationEnabled: %s\n", netconfig_enabled ? "enabled" : "disabled"); @@ -90,6 +92,12 @@ static void get_info_callback(struct l_dbus_message *message, void *user_data) display("%s: %s\n", key, sval); } } + + return; + +parse_failed: + l_error("Failed to parse GetInfo message"); + return; } static bool daemon_get_info(void) diff --git a/client/display.h b/client/display.h @@ -23,8 +23,8 @@ struct command; struct command_family; -#define COLOR_BOLDGRAY "\x1B[1;30m" -#define COLOR_GRAY "\x1b[37m" +#define COLOR_BOLDGRAY "\x1B[1;90m" +#define COLOR_GRAY "\x1b[90m" #define COLOR_GREEN "\x1b[32m" #define COLOR_RED "\x1B[0;91m" #define COLOR_BLUE "\x1B[94m" diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ(2.60) -AC_INIT(iwd, 1.25) +AC_INIT(iwd, 1.27) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR(build-aux) @@ -268,7 +268,7 @@ if (test "${enable_external_ell}" = "yes"); then test "${enable_monitor}" != "no" || test "${enable_wired}" = "yes" || test "${enable_hwsim}" = "yes"); then - ell_min_version="0.49" + ell_min_version="0.50" else ell_min_version="0.5" fi diff --git a/doc/access-point-api.txt b/doc/access-point-api.txt @@ -37,6 +37,24 @@ Methods void Start(string ssid, string psk) net.connman.iwd.AlreadyExists net.connman.iwd.NotFound + void Scan() + + Schedule a network scan. + + Possible errors: net.connman.iwd.NotAvailable + net.connman.iwd.NotSupported + net.connman.iwd.Busy + net.connman.iwd.Failed + + array(dict) GetOrderedNetworks() + + Gets the list of networks found after scanning sorted + based on signal strength. Each item in the array is a + dictionary containing the network Name, SignalStrength, + and Security. + + Possible errors: net.connman.iwd.NotAvailable + Properties boolean Started [readonly] Reflects whether an access point has been started. @@ -45,3 +63,7 @@ Properties boolean Started [readonly] The SSID being broadcast for a started AP (omitted if AP has not been started) + + boolean Scanning [readonly] + + Reflects whether the access point is scanning. diff --git a/doc/hwsim-radio-api.txt b/doc/hwsim-radio-api.txt @@ -5,17 +5,33 @@ Service net.connman.hwsim Interface net.connman.hwsim.RadioManager [Experimental] Object path / -Methods object CreateRadio(string name, boolean p2p_device) +Methods object CreateRadio(dict) Add one virtual radio device to the simulator, a path to a new object with the net.connman.hwsim.Radio interface is returned. - The radio is created with one network interface of - the type "managed" (Station) and optionally one - P2P Device interface. The name parameter may be - an empty string or a requested name for the radio - and its wiphy. If empty, the kernel will use a - default name. If non-empty, the kernel may still - use the default name if the requested name can not + + This API takes a dictionary of arguments (all optional) + with keys: + + string Name - Name of radio + bool P2P - Create a P2P device + string InterfaceTypeDisable - List of disabled + interface types (comma + separated) + string CipherTypeDisable - List of disabled + cipher types (comma + separated) + string NoVirtualInterface - Don't create an + interface for this + radio. + + The radio is created with one network interface (unless + NoVirtualInterface is used) of the type "managed" + (Station) and optionally one P2P Device interface. + The name parameter may be an empty string or a requested + name for the radio and its wiphy. If empty, the kernel + will use a default name. If non-empty, the kernel may + still use the default name if the requested name can not be used. Service net.connman.hwsim diff --git a/doc/test-runner.txt b/doc/test-runner.txt @@ -8,7 +8,6 @@ test-runner is an automated test execution tool for IWD. It is capable of creating the emulated environments representing a variety of network topologies and run the automated tests of IWD functionality. - Software Prerequisites ====================== @@ -30,6 +29,7 @@ OS: 12. phonesim (optional) 13. wpa_supplicant 2.9 14. radvd 2.18 + 15. dhcpd Note: The version for hostapd is listed as 'recent'. Older hostapd versions will work but we are continually adopting new features from hostapd and using @@ -54,34 +54,48 @@ In addition, the following Python packages are required: Building Kernel =============== +test-runner can work both in a fully virtualized environment (QEMU) or inside +a UML (User Mode Linux) instance. Its recommended using UML as its both faster +and more reliable than QEMU for timing specific scenarios. When building the +kernel for UML its important to always specify ARCH=um for any build command. +The default architectures seem to muck with the kernel config that UML needs +and will likely result in a UML binary that won't run under test-runner. + The test-runner tool requires a kernel that is at least build with these minimal options for a successful boot and execution: <arch>_defconfig Default kernel configuration kvm_guest.config Default configuration for - kvm guests + kvm guests (QEMU only) <iwd>/tools/test_runner_kernel_config The test-runner specific configuration These configurations should be installed as .config in the kernel source -directory. To make a x86_64 guest kernel the sequence of commands may look +directory. To build a x86_64 UML kernel the sequence of commands may look as follows: $ cd linux-X.X.X - $ make x86_64_defconfig - - $ make kvm_guest.config + $ make ARCH=um x86_64_defconfig - $ sh <iwd>/tools/test_runner_kernel_config + $ ARCH=um sh <iwd>/tools/test_runner_kernel_config - $ make olddefconfig + $ make ARCH=um olddefconfig After that a default kernel with the required options can be built: - $ make -j$(nproc) + $ make ARCH=um -j$(nproc) + +If you do need to build a QEMU kernel you can remove ARCH=um and make the +kvm_guest.config target as well. + +After building (for UML) there should be a 'linux' executable at the root of the +repository, this is the UML binary that should be supplied to test-runner with +the --kernel,-k option. + +For QEMU it is instead a kernel image located at arch/boot/<arch>/bzImage. Note: If your host distribution does not contain a regulatory.db you may get an error similar to this when building the kernel: @@ -136,7 +150,7 @@ tests shipped with IWD: $ cd <iwd>/tools - $ sudo ./test-runner + $ sudo ./test-runner -k <kernel binary> One can specify a particular set of test configurations to be executed by using '-A <dir1,dir2>' parameter. An absolute path is necessary for the test diff --git a/monitor/nlmon.c b/monitor/nlmon.c @@ -5455,6 +5455,93 @@ static void print_wiphy_bands(unsigned int level, const char *label, } } +static void print_reg_rule_flags(unsigned int level, const char *label, + const void *data, uint16_t size) +{ + uint32_t flag; + + flag = l_get_u32(data); + + if (!flag) + return; + + print_attr(level, "%s: len %u", label, size); + + if (flag & NL80211_RRF_NO_OFDM) + print_attr(level + 1, "No ODFM"); + if (flag & NL80211_RRF_NO_CCK) + print_attr(level + 1, "No CCK"); + if (flag & NL80211_RRF_NO_INDOOR) + print_attr(level + 1, "No Indoor"); + if (flag & NL80211_RRF_NO_OUTDOOR) + print_attr(level + 1, "No Outdoor"); + if (flag & NL80211_RRF_DFS) + print_attr(level + 1, "DFS"); + if (flag & NL80211_RRF_PTP_ONLY) + print_attr(level + 1, "PTP Only"); + if (flag & NL80211_RRF_PTMP_ONLY) + print_attr(level + 1, "PTMP Only"); + if (flag & NL80211_RRF_NO_IR) + print_attr(level + 1, "No IR"); + if (flag & __NL80211_RRF_NO_IBSS) + print_attr(level + 1, "No IBSS"); + if (flag & NL80211_RRF_AUTO_BW) + print_attr(level + 1, "Auto BW"); + if (flag & NL80211_RRF_IR_CONCURRENT) + print_attr(level + 1, "IR Concurrent"); + if (flag & NL80211_RRF_NO_HT40MINUS) + print_attr(level + 1, "No HT40-"); + if (flag & NL80211_RRF_NO_HT40PLUS) + print_attr(level + 1, "No HT40+"); + if (flag & NL80211_RRF_NO_80MHZ) + print_attr(level + 1, "No 80MHz"); + if (flag & NL80211_RRF_NO_160MHZ) + print_attr(level + 1, "No 160MHz"); + if (flag & NL80211_RRF_NO_HE) + print_attr(level + 1, "No HE"); +} + +static void print_u32_div_1000(unsigned int level, const char *label, + const void *data, uint16_t size) +{ + uint32_t val = l_get_u32(data) / 1000; + + print_attr(level, "%s: %u MHz", label, val); +} + +static const struct attr_entry reg_rule_table[] = { + { NL80211_ATTR_REG_RULE_FLAGS, "Flags", ATTR_CUSTOM, + { .function = print_reg_rule_flags } }, + { NL80211_ATTR_FREQ_RANGE_START, "Frequency Start", ATTR_CUSTOM, + { .function = print_u32_div_1000 } }, + { NL80211_ATTR_FREQ_RANGE_END, "Frequency End", ATTR_CUSTOM, + { .function = print_u32_div_1000 } }, + { NL80211_ATTR_FREQ_RANGE_MAX_BW, "Frequency Range Max BW", ATTR_CUSTOM, + { .function = print_u32_div_1000 } }, + { NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN, "Max Antenna Gain", ATTR_U32 }, + { NL80211_ATTR_POWER_RULE_MAX_EIRP, "Max EIRP", ATTR_U32 }, + { NL80211_ATTR_DFS_CAC_TIME, "DFS CAC Time", ATTR_U32 }, + { } +}; + +static void print_reg_rules(unsigned int level, const char *label, + const void *data, uint16_t size) +{ + const struct nlattr *nla; + uint16_t nla_type; + + print_attr(level, "%s: len %u", label, size); + + for (nla = data; NLA_OK(nla, size); nla = NLA_NEXT(nla, size)) { + nla_type = nla->nla_type & NLA_TYPE_MASK; + print_attr(level + 1, "Rule %u: len %u", nla_type, + NLA_PAYLOAD(nla)); + + print_attributes(level + 2, reg_rule_table, + NLA_DATA(nla), NLA_PAYLOAD(nla)); + } +} + static void print_eapol_key(unsigned int level, const void *data, uint32_t size) { const struct eapol_key *ek = (struct eapol_key *)data; @@ -6004,7 +6091,8 @@ static const struct attr_entry attr_table[] = { { NL80211_ATTR_REG_ALPHA2, "Regulatory Alpha2", ATTR_STRING }, { NL80211_ATTR_REG_RULES, - "Regulatory Rules" }, + "Regulatory Rules", ATTR_CUSTOM, + { .function = print_reg_rules } }, { NL80211_ATTR_MESH_CONFIG, "Mesh Configuration" }, { NL80211_ATTR_BSS_BASIC_RATES, diff --git a/src/ap.c b/src/ap.c @@ -58,6 +58,7 @@ #include "src/storage.h" #include "src/diagnostic.h" #include "src/band.h" +#include "src/common.h" struct ap_state { struct netdev *netdev; @@ -99,11 +100,16 @@ struct ap_state { uint8_t netconfig_gateway4_mac[6]; uint8_t netconfig_dns4_mac[6]; + uint32_t scan_id; + struct l_dbus_message *scan_pending; + struct l_queue *networks; + bool started : 1; bool gtk_set : 1; bool netconfig_set_addr4 : 1; bool in_event : 1; bool free_pending : 1; + bool scanning : 1; }; struct sta_state { @@ -136,10 +142,76 @@ struct ap_wsc_pbc_probe_record { uint64_t timestamp; }; +struct ap_network { + char ssid[33]; + int16_t signal; + enum security security; +}; + static char **global_addr4_strs; static uint32_t netdev_watch; static struct l_netlink *rtnl; +static bool network_match_ssid(const void *a, const void *b) +{ + const struct ap_network *network = a; + const char *ssid = b; + + return !strcmp(network->ssid, ssid); +} + +static int network_signal_compare(const void *a, const void *b, void *user) +{ + const struct ap_network *new_network = a; + const struct ap_network *network = b; + + return (network->signal > new_network->signal) ? 1 : -1; +} + +static struct ap_network *ap_network_find(struct ap_state *ap, + struct scan_bss *bss) +{ + char ssid[33]; + + memcpy(ssid, bss->ssid, bss->ssid_len); + ssid[bss->ssid_len] = '\0'; + + return l_queue_find(ap->networks, network_match_ssid, ssid); +} + +static void ap_network_append(struct ap_state *ap, struct scan_bss *bss) +{ + struct ap_network *network; + enum security security; + + if (util_ssid_is_hidden(bss->ssid_len, bss->ssid)) + return; + + network = ap_network_find(ap, bss); + if (!network) { + if (scan_bss_get_security(bss, &security) < 0) + return; + + network = l_new(struct ap_network, 1); + network->signal = bss->signal_strength; + network->security = security; + + memcpy(network->ssid, bss->ssid, bss->ssid_len); + network->ssid[bss->ssid_len] = '\0'; + + goto insert; + } + + if (bss->signal_strength <= network->signal) + return; + + l_queue_remove(ap->networks, network); + network->signal = bss->signal_strength; + +insert: + l_queue_insert(ap->networks, network, network_signal_compare, NULL); +} + static void ap_stop_handshake(struct sta_state *sta) { if (sta->sm) { @@ -257,6 +329,16 @@ static void ap_reset(struct ap_state *ap) l_dhcp_server_destroy(ap->netconfig_dhcp); ap->netconfig_dhcp = NULL; } + + if (ap->scan_id) { + scan_cancel(netdev_get_wdev_id(ap->netdev), ap->scan_id); + ap->scan_id = 0; + } + + if (ap->networks) { + l_queue_destroy(ap->networks, l_free); + ap->networks = NULL; + } } static bool ap_event_done(struct ap_state *ap, bool prev_in_event) @@ -3207,6 +3289,7 @@ struct ap_state *ap_start(struct netdev *netdev, struct l_settings *config, ap->ciphers = wiphy_select_cipher(wiphy, 0xffff); ap->group_cipher = wiphy_select_cipher(wiphy, 0xffff); ap->beacon_interval = 100; + ap->networks = l_queue_new(); wsc_uuid_from_addr(netdev_get_address(netdev), ap->wsc_uuid_r); @@ -3670,6 +3753,147 @@ error: return dbus_error_from_errno(err, message); } +static void ap_set_scanning(struct ap_state *ap, bool scanning) +{ + if (ap->scanning == scanning) + return; + + ap->scanning = scanning; + + l_dbus_property_changed(dbus_get_bus(), netdev_get_path(ap->netdev), + IWD_AP_INTERFACE, "Scanning"); +} + +static void ap_scan_triggered(int err, void *user_data) +{ + struct ap_state *ap = user_data; + struct l_dbus_message *reply; + + if (err < 0) { + reply = dbus_error_from_errno(err, ap->scan_pending); + dbus_pending_reply(&ap->scan_pending, reply); + return; + } + + l_debug("AP scan triggered for %s", netdev_get_name(ap->netdev)); + + reply = l_dbus_message_new_method_return(ap->scan_pending); + l_dbus_message_set_arguments(reply, ""); + dbus_pending_reply(&ap->scan_pending, reply); + + ap_set_scanning(ap, true); +} + +static bool ap_scan_notify(int err, struct l_queue *bss_list, + const struct scan_freq_set *freqs, + void *user_data) +{ + struct ap_state *ap = user_data; + const struct l_queue_entry *bss_entry; + + ap_set_scanning(ap, false); + + /* Remove all networks, then re-populate with fresh BSS list */ + l_queue_clear(ap->networks, l_free); + + for (bss_entry = l_queue_get_entries(bss_list); bss_entry; + bss_entry = bss_entry->next) { + struct scan_bss *bss = bss_entry->data; + + ap_network_append(ap, bss); + } + + l_debug(""); + + return false; +} + +static void ap_scan_destroy(void *user_data) +{ + struct ap_state *ap = user_data; + + ap->scan_id = 0; +} + +static struct l_dbus_message *ap_dbus_scan(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct ap_if_data *ap_if = user_data; + uint64_t wdev_id = netdev_get_wdev_id(ap_if->netdev); + struct scan_parameters params = { 0}; + + if (wiphy_has_feature(wiphy_find_by_wdev(wdev_id), + NL80211_FEATURE_AP_SCAN)) + params.ap_scan = true; + + /* + * TODO: There is really nothing preventing scanning while stopped. + * The only consideration would be if a scan is ongoing and the + * AP is started. Queuing Start() as wiphy work may be required to + * handle this case if needed. For now just limit to started APs. + */ + if (!ap_if->ap || !ap_if->ap->started) + return dbus_error_not_available(message); + + if (ap_if->ap->scan_id) + return dbus_error_busy(message); + + ap_if->ap->scan_id = scan_active_full(wdev_id, &params, + ap_scan_triggered, + ap_scan_notify, + ap_if->ap, ap_scan_destroy); + if (!ap_if->ap->scan_id) + return dbus_error_failed(message); + + ap_if->ap->scan_pending = l_dbus_message_ref(message); + + return NULL; +} + +static void dbus_append_network(struct l_dbus_message_builder *builder, + struct ap_network *network) +{ + l_dbus_message_builder_enter_array(builder, "{sv}"); + dbus_append_dict_basic(builder, "Name", 's', network->ssid); + dbus_append_dict_basic(builder, "SignalStrength", 'n', + &network->signal); + dbus_append_dict_basic(builder, "Type", 's', + security_to_str(network->security)); + l_dbus_message_builder_leave_array(builder); +} + +static struct l_dbus_message *ap_dbus_get_networks(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct ap_if_data *ap_if = user_data; + struct l_dbus_message *reply; + struct l_dbus_message_builder *builder; + const struct l_queue_entry *entry; + + if (!ap_if->ap || !ap_if->ap->started) + return dbus_error_not_available(message); + + reply = l_dbus_message_new_method_return(message); + builder = l_dbus_message_builder_new(reply); + + l_dbus_message_builder_enter_array(builder, "a{sv}"); + + for (entry = l_queue_get_entries(ap_if->ap->networks); entry; + entry = entry->next) { + struct ap_network *network = entry->data; + + dbus_append_network(builder, network); + } + + l_dbus_message_builder_leave_array(builder); + l_dbus_message_builder_finalize(builder); + l_dbus_message_builder_destroy(builder); + + return reply; +} + static bool ap_dbus_property_get_started(struct l_dbus *dbus, struct l_dbus_message *message, struct l_dbus_message_builder *builder, @@ -3699,6 +3923,24 @@ static bool ap_dbus_property_get_name(struct l_dbus *dbus, return true; } +static bool ap_dbus_property_get_scanning(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct ap_if_data *ap_if = user_data; + bool bval; + + if (!ap_if->ap || !ap_if->ap->started) + return false; + + bval = ap_if->ap->scanning; + + l_dbus_message_builder_append_basic(builder, 'b', &bval); + + return true; +} + static void ap_setup_interface(struct l_dbus_interface *interface) { l_dbus_interface_method(interface, "Start", 0, ap_dbus_start, "", @@ -3707,11 +3949,17 @@ static void ap_setup_interface(struct l_dbus_interface *interface) l_dbus_interface_method(interface, "StartProfile", 0, ap_dbus_start_profile, "", "s", "ssid"); + l_dbus_interface_method(interface, "Scan", 0, ap_dbus_scan, "", ""); + l_dbus_interface_method(interface, "GetOrderedNetworks", 0, + ap_dbus_get_networks, "aa{sv}", + "", "networks"); l_dbus_interface_property(interface, "Started", 0, "b", ap_dbus_property_get_started, NULL); l_dbus_interface_property(interface, "Name", 0, "s", ap_dbus_property_get_name, NULL); + l_dbus_interface_property(interface, "Scanning", 0, "b", + ap_dbus_property_get_scanning, NULL); } static void ap_destroy_interface(void *user_data) diff --git a/src/band.c b/src/band.c @@ -325,8 +325,7 @@ static bool find_best_mcs_vht(uint8_t max_index, enum ofdm_channel_width width, */ for (i = max_index; i >= 0; i--) - if (band_ofdm_rate(i, width, rssi, - nss, sgi, out_data_rate)) + if (band_ofdm_rate(i, width, rssi, nss, sgi, out_data_rate)) return true; return false; @@ -489,8 +488,8 @@ static int band_channel_info_get_bandwidth(const struct band_chandef *info) struct operating_class_info { uint32_t starting_frequency; uint32_t flags; - uint8_t channel_set[20]; - uint8_t center_frequencies[8]; + uint8_t channel_set[60]; + uint8_t center_frequencies[30]; uint16_t channel_spacing; uint8_t operating_class; }; @@ -598,20 +597,20 @@ static const struct operating_class_info e4_operating_classes[] = { { .operating_class = 125, .starting_frequency = 5000, - .channel_set = { 149, 153, 157, 161, 165, 169, 173}, + .channel_set = { 149, 153, 157, 161, 165, 169, 173, 177 }, .channel_spacing = 20, }, { .operating_class = 126, .starting_frequency = 5000, - .channel_set = { 149, 157, 165}, + .channel_set = { 149, 157, 165, 173 }, .channel_spacing = 40, .flags = PRIMARY_CHANNEL_LOWER, }, { .operating_class = 127, .starting_frequency = 5000, - .channel_set = { 153, 161, 169 }, + .channel_set = { 153, 161, 169, 177 }, .channel_spacing = 40, .flags = PRIMARY_CHANNEL_UPPER, }, @@ -619,21 +618,68 @@ static const struct operating_class_info e4_operating_classes[] = { .operating_class = 128, .starting_frequency = 5000, .channel_spacing = 80, - .center_frequencies = { 42, 58, 106, 122, 138, 155 }, + .center_frequencies = { 42, 58, 106, 122, 138, 155, 171 }, }, { .operating_class = 129, .starting_frequency = 5000, .channel_spacing = 160, - .center_frequencies = { 50, 114 }, + .center_frequencies = { 50, 114, 163 }, }, { .operating_class = 130, .starting_frequency = 5000, .channel_spacing = 80, - .center_frequencies = { 42, 58, 106, 122, 138, 155 }, + .center_frequencies = { 42, 58, 106, 122, 138, 155, 171 }, .flags = PLUS80, }, + { + .operating_class = 131, + .starting_frequency = 5950, + .channel_spacing = 20, + .channel_set = { 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, + 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, + 97, 101, 105, 109, 113, 117, 121, 125, 129, 133, + 137, 141, 145, 149, 153, 157, 161, 165, 169, + 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 233 }, + }, + { + .operating_class = 132, + .starting_frequency = 5950, + .channel_spacing = 40, + .center_frequencies = { 3, 11, 19, 27, 35, 43, 51, 59, 67, 75, + 83, 91, 99, 107, 115, 123, 131, 139, + 147, 155, 163, 171, 179, 187, 195, 203, + 211, 219, 227 }, + }, + { + .operating_class = 133, + .starting_frequency = 5950, + .channel_spacing = 80, + .center_frequencies = { 7, 23, 39, 55, 71, 87, 103, 119, 135, + 151, 167, 183, 199, 215 }, + }, + { + .operating_class = 134, + .starting_frequency = 5950, + .channel_spacing = 160, + .center_frequencies = { 15, 47, 79, 111, 143, 175, 207 }, + }, + { + .operating_class = 135, + .starting_frequency = 5950, + .channel_spacing = 80, + .center_frequencies = { 7, 23, 39, 55, 71, 87, 102, 119, 135, + 151, 167, 183, 199, 215 }, + .flags = PLUS80, + }, + { + .operating_class = 136, + .starting_frequency = 5950, + .channel_spacing = 20, + .center_frequencies = { 2 }, + } }; static const struct operating_class_info *e4_find_opclass(uint32_t opclass) @@ -856,8 +902,12 @@ int oci_verify(const uint8_t oci[static 3], const struct band_chandef *own) * on 40 Mhz channels. If the STA is operating on 40 Mhz while the * peer is operating on 80 or 160 Mhz wide channels, then only the * primary channel validation is performed + * + * With 6GHz operating classes there is no concept of upper/lower 40mhz + * channels, therefore this special handling list not needed. */ - if (own_bandwidth == 40 && oci_bandwidth == 40) { + if (own_bandwidth == 40 && oci_bandwidth == 40 && + info->operating_class < 131) { uint32_t behavior; /* @@ -970,6 +1020,25 @@ uint8_t band_freq_to_channel(uint32_t freq, enum band_freq *out_band) return channel; } + if (freq > 5950 && freq <= 7115) { + if (freq % 5) + return 0; + + channel = (freq - 5950) / 5; + + if (out_band) + *out_band = BAND_FREQ_6_GHZ; + + return channel; + } + + if (freq == 5935) { + if (out_band) + *out_band = BAND_FREQ_6_GHZ; + + return 2; + } + return 0; } @@ -991,6 +1060,22 @@ uint32_t band_channel_to_freq(uint8_t channel, enum band_freq band) return 4000 + 5 * channel; } + if (band == BAND_FREQ_6_GHZ) { + /* operating class 136 */ + if (channel == 2) + return 5935; + + /* Channels increment by 4, starting with 1 */ + if (channel % 4 != 1) + return 0; + + if (channel < 1 || channel > 233) + return 0; + + /* operating classes 131, 132, 133, 134, 135 */ + return 5950 + 5 * channel; + } + return 0; } @@ -1046,10 +1131,11 @@ static const uint8_t oper_class_jp_to_global[] = { /* 128 - 130 is a 1 to 1 mapping */ }; -/* Annex E, table E-4 (only 2.4GHz and 4.9 / 5GHz bands) */ +/* Annex E, table E-4 (only 2.4GHz, 4.9 / 5GHz, and 6GHz bands) */ static const enum band_freq oper_class_to_band_global[] = { [81 ... 84] = BAND_FREQ_2_4_GHZ, [104 ... 130] = BAND_FREQ_5_GHZ, + [131 ... 136] = BAND_FREQ_6_GHZ, }; /* Annex E, table E-5 */ diff --git a/src/band.h b/src/band.h @@ -39,6 +39,7 @@ enum band_chandef_width { enum band_freq { BAND_FREQ_2_4_GHZ = 0x1, BAND_FREQ_5_GHZ = 0x2, + BAND_FREQ_6_GHZ = 0x4, }; struct band_chandef { diff --git a/src/dpp-util.c b/src/dpp-util.c @@ -408,6 +408,8 @@ size_t dpp_append_wrapped_data(const void *ad0, size_t ad0_len, va_arg(va, void*); } + va_end(va); + if (to_len < attrs_len + 4 + 16) return false; @@ -415,8 +417,6 @@ size_t dpp_append_wrapped_data(const void *ad0, size_t ad0_len, ptr = plaintext; - va_end(va); - va_start(va, num_attrs); /* Build up plaintext attributes */ diff --git a/src/dpp.c b/src/dpp.c @@ -55,6 +55,7 @@ #include "src/nl80211util.h" #define DPP_FRAME_MAX_RETRIES 5 +#define DPP_FRAME_RETRY_TIMEOUT 1 static uint32_t netdev_watch; static struct l_genl_family *nl80211; @@ -138,12 +139,40 @@ struct dpp_sm { uint32_t connect_scan_id; uint64_t frame_cookie; uint8_t frame_retry; + void *frame_pending; + size_t frame_size; + struct l_timeout *retry_timeout; struct l_dbus_message *pending; bool mcast_support : 1; + bool roc_started : 1; }; +static void *dpp_serialize_iovec(struct iovec *iov, size_t iov_len, + size_t *out_len) +{ + unsigned int i; + size_t size = 0; + uint8_t *ret; + + for (i = 0; i < iov_len; i++) + size += iov[i].iov_len; + + ret = l_malloc(size); + size = 0; + + for (i = 0; i < iov_len; i++) { + memcpy(ret + size, iov[i].iov_base, iov[i].iov_len); + size += iov[i].iov_len; + } + + if (out_len) + *out_len = size; + + return ret; +} + static void dpp_free_auth_data(struct dpp_sm *dpp) { if (dpp->own_proto_public) { @@ -209,6 +238,16 @@ static void dpp_reset(struct dpp_sm *dpp) dpp->peer_asn1 = NULL; } + if (dpp->frame_pending) { + l_free(dpp->frame_pending); + dpp->frame_pending = NULL; + } + + if (dpp->retry_timeout) { + l_timeout_remove(dpp->retry_timeout); + dpp->retry_timeout = NULL; + } + dpp->state = DPP_STATE_NOTHING; dpp->new_freq = 0; dpp->frame_retry = 0; @@ -250,9 +289,10 @@ static void dpp_free(struct dpp_sm *dpp) static void dpp_send_frame_cb(struct l_genl_msg *msg, void *user_data) { struct dpp_sm *dpp = user_data; + int err = l_genl_msg_get_error(msg); - if (l_genl_msg_get_error(msg) < 0) { - l_error("Error sending frame"); + if (err < 0) { + l_error("Error sending frame (%d)", err); return; } @@ -267,6 +307,19 @@ static void dpp_send_frame(struct dpp_sm *dpp, { struct l_genl_msg *msg; + /* + * A received frame could potentially come in after the ROC session has + * ended. In this case the frame needs to be stored until ROC is started + * and sent at that time. The offchannel_id is also checked since + * this is not applicable when DPP is in a responder role waiting + * on the currently connected channel i.e. offchannel is never used. + */ + if (!dpp->roc_started && dpp->offchannel_id) { + dpp->frame_pending = dpp_serialize_iovec(iov, iov_len, + &dpp->frame_size); + return; + } + msg = l_genl_msg_new_sized(NL80211_CMD_FRAME, 512); l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dpp->wdev_id); l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, 4, &freq); @@ -281,6 +334,20 @@ static void dpp_send_frame(struct dpp_sm *dpp, } } +static void dpp_frame_retry(struct dpp_sm *dpp) +{ + struct iovec iov; + + iov.iov_base = dpp->frame_pending; + iov.iov_len = dpp->frame_size; + + dpp_send_frame(dpp, &iov, 1, dpp->current_freq); + + l_free(dpp->frame_pending); + dpp->frame_pending = NULL; +} + + static size_t dpp_build_header(const uint8_t *src, const uint8_t *dest, enum dpp_frame_type type, uint8_t buf[static 32]) @@ -1294,7 +1361,7 @@ static void dpp_presence_announce(struct dpp_sm *dpp) dpp_send_frame(dpp, iov, 2, dpp->current_freq); } -static void dpp_send_authenticate_request(struct dpp_sm *dpp) +static bool dpp_send_authenticate_request(struct dpp_sm *dpp) { uint8_t hdr[32]; uint8_t attrs[256]; @@ -1305,6 +1372,12 @@ static void dpp_send_authenticate_request(struct dpp_sm *dpp) struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); struct scan_bss *bss = station_get_connected_bss(station); + /* Got disconnected by the time the peer was discovered */ + if (!bss) { + dpp_reset(dpp); + return false; + } + l_ecc_point_get_data(dpp->own_proto_public, i_proto_key, sizeof(i_proto_key)); @@ -1337,6 +1410,8 @@ static void dpp_send_authenticate_request(struct dpp_sm *dpp) iov[1].iov_len = ptr - attrs; dpp_send_frame(dpp, iov, 2, dpp->current_freq); + + return true; } static void dpp_roc_started(void *user_data) @@ -1352,6 +1427,20 @@ static void dpp_roc_started(void *user_data) * the authenticate response now. */ + dpp->roc_started = true; + + /* + * The retry timer indicates a frame was not acked in which case we + * should not change any state or send any frames until that expires. + */ + if (dpp->retry_timeout) + return; + + if (dpp->frame_pending) { + dpp_frame_retry(dpp); + return; + } + switch (dpp->state) { case DPP_STATE_PRESENCE: if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) @@ -1401,6 +1490,7 @@ static void dpp_presence_timeout(int error, void *user_data) struct dpp_sm *dpp = user_data; dpp->offchannel_id = 0; + dpp->roc_started = false; /* * If cancelled this is likely due to netdev going down or from Stop(). @@ -1948,7 +2038,8 @@ static void dpp_handle_presence_announcement(struct dpp_sm *dpp, dpp->state = DPP_STATE_AUTHENTICATING; - dpp_send_authenticate_request(dpp); + if (!dpp_send_authenticate_request(dpp)) + return; /* * Should we wait for an ACK then go offchannel? @@ -2005,6 +2096,25 @@ static bool match_wdev(const void *a, const void *b) return *wdev_id == dpp->wdev_id; } +static void dpp_frame_timeout(struct l_timeout *timeout, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + l_timeout_remove(timeout); + dpp->retry_timeout = NULL; + + /* + * ROC has not yet started (in between an ROC timeout and starting a + * new session), this will most likely result in the frame failing to + * send. Just bail out now and the roc_started callback will take care + * of sending this out. + */ + if (!dpp->roc_started) + return; + + dpp_frame_retry(dpp); +} + static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) { struct dpp_sm *dpp; @@ -2043,11 +2153,19 @@ static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) return; } - l_debug("No ACK from peer, re-transmitting"); + /* This should never happen */ + if (L_WARN_ON(dpp->frame_pending)) + return; + + l_debug("No ACK from peer, re-transmitting in %us", + DPP_FRAME_RETRY_TIMEOUT); dpp->frame_retry++; - dpp_send_frame(dpp, &iov, 1, dpp->current_freq); + dpp->frame_pending = l_memdup(iov.iov_base, iov.iov_len); + dpp->frame_size = iov.iov_len; + dpp->retry_timeout = l_timeout_create(DPP_FRAME_RETRY_TIMEOUT, + dpp_frame_timeout, dpp, NULL); } static void dpp_unicast_notify(struct l_genl_msg *msg, void *user_data) @@ -2427,6 +2545,8 @@ static struct l_dbus_message *dpp_start_configurator_common( if (!dpp->mcast_support) dpp->state = DPP_STATE_AUTHENTICATING; + + dpp->new_freq = bss->frequency; } else dpp->current_freq = bss->frequency; diff --git a/src/eapol.c b/src/eapol.c @@ -706,7 +706,7 @@ static struct eapol_key *eapol_create_common( struct eapol_key *out_frame = l_malloc(to_alloc + extra_len + extra_key_len); - memset(out_frame, 0, to_alloc + extra_len); + memset(out_frame, 0, to_alloc + extra_len + extra_key_len); out_frame->header.protocol_version = protocol; out_frame->header.packet_type = 0x3; diff --git a/src/ie.h b/src/ie.h @@ -336,23 +336,37 @@ enum ie_rsn_akm_suite { IE_RSN_AKM_SUITE_OSEN = 0x40000, }; -#define IE_AKM_IS_SAE(akm) \ - ((akm == IE_RSN_AKM_SUITE_SAE_SHA256) || \ - (akm == IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256)) - -#define IE_AKM_IS_FT(akm) \ - (akm & (IE_RSN_AKM_SUITE_FT_OVER_8021X | \ - IE_RSN_AKM_SUITE_FT_USING_PSK | \ - IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256 | \ - IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384 | \ - IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256 | \ - IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384)) - -#define IE_AKM_IS_FILS(akm) \ - ((akm == IE_RSN_AKM_SUITE_FILS_SHA256) || \ - (akm == IE_RSN_AKM_SUITE_FILS_SHA384) || \ - (akm == IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256) || \ - (akm == IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384)) +static inline bool IE_AKM_IS_SAE(uint32_t akm) +{ + return akm & (IE_RSN_AKM_SUITE_SAE_SHA256 | + IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256); +} + +static inline bool IE_AKM_IS_FT(uint32_t akm) +{ + return akm & (IE_RSN_AKM_SUITE_FT_OVER_8021X | + IE_RSN_AKM_SUITE_FT_USING_PSK | + IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256 | + IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384 | + IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256 | + IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384); +} + +static inline bool IE_AKM_IS_FILS(uint32_t akm) +{ + return (akm) & (IE_RSN_AKM_SUITE_FILS_SHA256 | + IE_RSN_AKM_SUITE_FILS_SHA384 | + IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256 | + IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384); +} + +static inline bool IE_AKM_IS_8021X(uint32_t akm) +{ + return akm & (IE_RSN_AKM_SUITE_8021X | + IE_RSN_AKM_SUITE_FT_OVER_8021X | + IE_RSN_AKM_SUITE_8021X_SHA256 | + IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384); +} #define IE_LEN(ie) \ ((ie) ? (ie)[1] + 2 : 0) diff --git a/src/json.c b/src/json.c @@ -279,6 +279,8 @@ done: return true; error: + va_end(va); + l_queue_destroy(args, l_free); return false; } diff --git a/src/knownnetworks.c b/src/knownnetworks.c @@ -45,6 +45,7 @@ #include "src/scan.h" #include "src/util.h" #include "src/watchlist.h" +#include "src/band.h" static struct l_queue *known_networks; static size_t num_known_hidden_networks; @@ -866,7 +867,8 @@ static struct l_queue *known_frequencies_from_string(char *freq_set_str) t = strtoul(freq_set_str, &freq_set_str, 10); - if (unlikely(errno == ERANGE || !t || t > 6000)) + if (unlikely(errno == ERANGE || !t || + !band_freq_to_channel(t, NULL))) goto error; known_freq = l_new(struct known_frequency, 1); diff --git a/src/netdev.c b/src/netdev.c @@ -4525,6 +4525,9 @@ static void netdev_ft_response_frame_event(const struct mmpdu_header *hdr, size_t ies_len; struct ft_ds_finder finder; + if (!netdev->connected) + return; + ret = ft_over_ds_parse_action_response(body, body_len, &spa, &aa, &ies, &ies_len); if (ret < 0) @@ -4987,8 +4990,7 @@ static void netdev_sa_query_req_frame_event(const struct mmpdu_header *hdr, uint16_t transaction; const uint8_t *oci; struct netdev *netdev = user_data; - bool ocvc = netdev->handshake->supplicant_ocvc && - netdev->handshake->authenticator_ocvc; + bool ocvc; if (body_len < 4) { l_debug("SA Query request too short"); @@ -4998,6 +5000,9 @@ static void netdev_sa_query_req_frame_event(const struct mmpdu_header *hdr, if (!netdev->connected) return; + ocvc = netdev->handshake->supplicant_ocvc && + netdev->handshake->authenticator_ocvc; + /* only care about SA Queries from our connected AP */ if (memcmp(hdr->address_2, netdev->handshake->aa, 6)) return; diff --git a/src/network.c b/src/network.c @@ -55,6 +55,7 @@ #include "src/util.h" #include "src/erp.h" #include "src/handshake.h" +#include "src/band.h" #define SAE_PT_SETTING "SAE-PT-Group%u" @@ -84,6 +85,7 @@ struct network { bool is_hs20:1; bool anqp_pending:1; /* Set if there is a pending ANQP request */ bool owe_hidden_pending:1; + bool provisioning_hidden:1; uint8_t transition_disable; /* Temporary cache until info is set */ bool have_transition_disable:1; int rank; @@ -187,6 +189,8 @@ void network_connected(struct network *network) network_secret_check_cacheable, network); l_queue_clear(network->blacklist, NULL); + + network->provisioning_hidden = false; } void network_disconnected(struct network *network) @@ -194,6 +198,9 @@ void network_disconnected(struct network *network) network_settings_close(network); l_queue_clear(network->blacklist, NULL); + + if (network->provisioning_hidden) + station_hide_network(network->station, network); } /* First 64 entries calculated by 1 / pow(n, 0.3) for n >= 1 */ @@ -776,6 +783,7 @@ int network_can_connect_bss(struct network *network, const struct scan_bss *bss) struct network_config *config = info ? &info->config : NULL; bool can_transition_disable = wiphy_can_transition_disable(wiphy); struct ie_rsn_info rsn; + enum band_freq band; int ret; switch (security) { @@ -787,6 +795,9 @@ int network_can_connect_bss(struct network *network, const struct scan_bss *bss) return -ENOSYS; } + if (!band_freq_to_channel(bss->frequency, &band)) + return -ENOTSUP; + memset(&rsn, 0, sizeof(rsn)); ret = scan_bss_get_rsn_info(bss, &rsn); if (ret < 0) { @@ -799,6 +810,13 @@ int network_can_connect_bss(struct network *network, const struct scan_bss *bss) * We assume the spec means us to check bit 3 here */ if (ret == -ENOENT && security == SECURITY_NONE) { + /* + * 802.11ax 12.12.2 - STA shall not use Open System + * authentication without encryption + */ + if (band == BAND_FREQ_6_GHZ) + return -EPERM; + if (!config) return 0; @@ -816,26 +834,21 @@ int network_can_connect_bss(struct network *network, const struct scan_bss *bss) return ret; } - if (!config || !config->have_transition_disable) + if (!config || !config->have_transition_disable) { + if (band == BAND_FREQ_6_GHZ) + goto mfp_no_tkip; + goto no_transition_disable; + } if (!can_transition_disable) { + if (band == BAND_FREQ_6_GHZ) + return -EPERM; + l_debug("HW not capable of Transition Disable, skip"); goto no_transition_disable; } - /* - * WPA3 Specification, v3, Section 8: - * - Disable use of WEP and TKIP - * - Disallow association without negotiation of PMF - */ - rsn.pairwise_ciphers &= ~IE_RSN_CIPHER_SUITE_TKIP; - - if (!rsn.group_management_cipher) - return -EPERM; - - rsn.mfpr = true; - /* WPA3-Personal */ if (test_bit(&config->transition_disable, 0)) { rsn.akm_suites &= ~IE_RSN_AKM_SUITE_PSK; @@ -853,6 +866,31 @@ int network_can_connect_bss(struct network *network, const struct scan_bss *bss) return -EPERM; } +mfp_no_tkip: + /* + * WPA3 Specification, v3, Section 8: + * - Disable use of WEP and TKIP + * - Disallow association without negotiation of PMF + */ + rsn.pairwise_ciphers &= ~IE_RSN_CIPHER_SUITE_TKIP; + + if (!rsn.group_management_cipher) + return -EPERM; + + rsn.mfpr = true; + + /* 802.11ax Section 12.12.2 */ + if (band == BAND_FREQ_6_GHZ) { + /* STA shall not use the following cipher suite selectors */ + rsn.pairwise_ciphers &= ~IE_RSN_CIPHER_SUITE_USE_GROUP_CIPHER; + + /* Basically the STA must use OWE, SAE, or 8021x */ + if (!IE_AKM_IS_SAE(rsn.akm_suites) && + !IE_AKM_IS_8021X(rsn.akm_suites) && + (!(rsn.akm_suites & IE_RSN_AKM_SUITE_OWE))) + return -EPERM; + } + no_transition_disable: if (!wiphy_select_cipher(wiphy, rsn.pairwise_ciphers)) return -ENOTSUP; @@ -1213,6 +1251,9 @@ static void passphrase_callback(enum agent_result result, err: network_settings_close(network); + + if (network->provisioning_hidden) + station_hide_network(station, network); } static struct l_dbus_message *network_connect_psk(struct network *network, @@ -1637,8 +1678,10 @@ struct l_dbus_message *network_connect_new_hidden_network( switch (network_get_security(network)) { case SECURITY_PSK: + network->provisioning_hidden = true; return network_connect_psk(network, bss, message); case SECURITY_NONE: + network->provisioning_hidden = true; station_connect_network(station, network, bss, message); return NULL; default: diff --git a/src/p2p.c b/src/p2p.c @@ -3659,11 +3659,15 @@ static bool p2p_peer_update_existing(struct scan_bss *bss, * Some property changes may need to be notified here. */ - if (peer->device_addr == peer->bss->addr) - peer->device_addr = bss->addr; - else + if (bss->source_frame == SCAN_BSS_PROBE_RESP) peer->device_addr = bss->p2p_probe_resp_info->device_info.device_addr; + else if (bss->source_frame == SCAN_BSS_PROBE_REQ && !l_memeqzero( + bss->p2p_probe_req_info->device_info.device_addr, 6)) + peer->device_addr = + bss->p2p_probe_req_info->device_info.device_addr; + else + peer->device_addr = bss->addr; scan_bss_free(peer->bss); peer->bss = bss; diff --git a/src/rrm.c b/src/rrm.c @@ -46,9 +46,9 @@ #include "linux/nl80211.h" /* Limit requests per second */ -#define MAX_REQUESTS_PER_SEC 2 +#define MAX_REQUESTS_PER_SEC 2ULL /* Microseconds between requests */ -#define MIN_MICROS_BETWEEN_REQUESTS (1000000 / MAX_REQUESTS_PER_SEC) +#define MIN_MICROS_BETWEEN_REQUESTS (1000000ULL / MAX_REQUESTS_PER_SEC) /* 802.11-2016 Table 9-90 */ #define REPORT_DETAIL_NO_FIELDS_OR_ELEMS 0 diff --git a/src/scan.c b/src/scan.c @@ -362,7 +362,8 @@ static struct l_genl_msg *scan_build_cmd(struct scan_context *sc, if (params->freqs) scan_build_attr_scan_frequencies(msg, params->freqs); - if (params->flush && !ignore_flush_flag) + if (params->flush && !ignore_flush_flag && wiphy_has_feature(sc->wiphy, + NL80211_FEATURE_SCAN_FLUSH)) flags |= NL80211_SCAN_FLAG_FLUSH; if (!is_passive && params->randomize_mac_addr_hint && @@ -390,6 +391,9 @@ static struct l_genl_msg *scan_build_cmd(struct scan_context *sc, NL80211_EXT_FEATURE_SCAN_RANDOM_SN)) flags |= NL80211_SCAN_FLAG_RANDOM_SN; + if (params->ap_scan) + flags |= NL80211_SCAN_FLAG_AP; + if (flags) l_genl_msg_append_attr(msg, NL80211_ATTR_SCAN_FLAGS, 4, &flags); @@ -1680,6 +1684,23 @@ int scan_bss_get_rsn_info(const struct scan_bss *bss, struct ie_rsn_info *info) return 0; } +int scan_bss_get_security(const struct scan_bss *bss, enum security *security) +{ + int ret; + struct ie_rsn_info info; + + ret = scan_bss_get_rsn_info(bss, &info); + if (ret < 0) { + if (ret != -ENOENT) + return ret; + + *security = security_determine(bss->capability, NULL); + } else + *security = security_determine(bss->capability, &info); + + return 0; +} + int scan_bss_rank_compare(const void *a, const void *b, void *user_data) { const struct scan_bss *new_bss = a, *bss = b; diff --git a/src/scan.h b/src/scan.h @@ -28,6 +28,7 @@ struct p2p_probe_req; struct p2p_beacon; struct mmpdu_header; struct wiphy; +enum security; enum scan_state { SCAN_STATE_NOT_RUNNING, @@ -97,6 +98,7 @@ struct scan_parameters { bool randomize_mac_addr_hint : 1; bool no_cck_rates : 1; bool duration_mandatory : 1; + bool ap_scan : 1; const uint8_t *ssid; /* Used for direct probe request */ size_t ssid_len; const uint8_t *source_mac; @@ -161,6 +163,7 @@ void scan_bss_free(struct scan_bss *bss); int scan_bss_rank_compare(const void *a, const void *b, void *user); int scan_bss_get_rsn_info(const struct scan_bss *bss, struct ie_rsn_info *info); +int scan_bss_get_security(const struct scan_bss *bss, enum security *security); struct scan_bss *scan_bss_new_from_probe_req(const struct mmpdu_header *mpdu, const uint8_t *body, diff --git a/src/station.c b/src/station.c @@ -348,25 +348,6 @@ static int bss_signal_strength_compare(const void *a, const void *b, void *user) return (bss->signal_strength > new_bss->signal_strength) ? 1 : -1; } -static int station_parse_bss_security(struct station *station, - struct scan_bss *bss, - enum security *security_out) -{ - struct ie_rsn_info info; - int r; - - r = scan_bss_get_rsn_info(bss, &info); - if (r < 0) { - if (r != -ENOENT) - return r; - - *security_out = security_determine(bss->capability, NULL); - } else - *security_out = security_determine(bss->capability, &info); - - return 0; -} - /* * Returns the network object the BSS was added to or NULL if ignored. */ @@ -402,7 +383,7 @@ static struct network *station_add_seen_bss(struct station *station, return NULL; } - if (station_parse_bss_security(station, bss, &security) < 0) + if (scan_bss_get_security(bss, &security) < 0) return NULL; /* Hidden OWE transition network */ @@ -1014,9 +995,13 @@ static int station_build_handshake_rsn(struct handshake_state *hs, struct ie_rsn_info info; uint8_t *ap_ie; bool disable_ocv; + enum band_freq band; memset(&info, 0, sizeof(info)); + if (!band_freq_to_channel(bss->frequency, &band)) + goto not_supported; + memset(&bss_info, 0, sizeof(bss_info)); scan_bss_get_rsn_info(bss, &bss_info); @@ -1063,12 +1048,31 @@ static int station_build_handshake_rsn(struct handshake_state *hs, switch (mfp_setting) { case 0: - break; + if (band != BAND_FREQ_6_GHZ) + break; + + l_error("MFP turned off by [General].ManagementFrameProtection," + " 6GHz frequencies are disabled"); + goto not_supported; case 1: info.group_management_cipher = wiphy_select_cipher(wiphy, bss_info.group_management_cipher); info.mfpc = info.group_management_cipher != 0; + + if (band != BAND_FREQ_6_GHZ) + break; + + if (!info.mfpc) + goto not_supported; + + /* + * 802.11ax Section 12.12.2 + * The STA shall use management frame protection + * (MFPR=1) when using RSN. + */ + info.mfpr = true; + break; case 2: info.group_management_cipher = @@ -1146,10 +1150,7 @@ build_ie: * a reference now so it remains valid (in case of expiration) until * FILS starts. */ - if (hs->akm_suite & (IE_RSN_AKM_SUITE_FILS_SHA256 | - IE_RSN_AKM_SUITE_FILS_SHA384 | - IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256 | - IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384)) + if (IE_AKM_IS_FILS(hs->akm_suite)) hs->erp_cache = erp_cache; else if (erp_cache) erp_cache_put(erp_cache); @@ -1627,12 +1628,6 @@ static void station_reset_connection_state(struct station *station) if (!network) return; - if (station->state == STATION_STATE_CONNECTED || - station->state == STATION_STATE_CONNECTING || - station->state == STATION_STATE_CONNECTING_AUTO || - station->state == STATION_STATE_ROAMING) - network_disconnected(network); - station_roam_state_clear(station); /* Refresh the ordered network list */ @@ -1652,6 +1647,17 @@ static void station_reset_connection_state(struct station *station) l_dbus_object_remove_interface(dbus, netdev_get_path(station->netdev), IWD_STATION_DIAGNOSTIC_INTERFACE); #endif + + /* + * Perform this step last since calling network_disconnected() might + * result in the removal of the network (for example if provisioning + * a new hidden network fails with an incorrect pasword). + */ + if (station->state == STATION_STATE_CONNECTED || + station->state == STATION_STATE_CONNECTING || + station->state == STATION_STATE_CONNECTING_AUTO || + station->state == STATION_STATE_ROAMING) + network_disconnected(network); } static void station_disassociated(struct station *station) @@ -1729,6 +1735,8 @@ static void parse_neighbor_report(struct station *station, struct scan_freq_set *freq_set_md, *freq_set_no_md; uint32_t current_freq = 0; struct handshake_state *hs = netdev_get_handshake(station->netdev); + const struct scan_freq_set *supported = + wiphy_get_supported_freqs(station->wiphy); freq_set_md = scan_freq_set_new(); freq_set_no_md = scan_freq_set_new(); @@ -1765,6 +1773,10 @@ static void parse_neighbor_report(struct station *station, if (!(band & wiphy_get_supported_bands(station->wiphy))) continue; + /* Skip if frequency is not supported */ + if (!scan_freq_set_contains(supported, freq)) + continue; + if (!memcmp(info.addr, station->connected_bss->addr, ETH_ALEN)) { /* @@ -2329,7 +2341,7 @@ static bool station_roam_scan_notify(int err, struct l_queue *bss_list, memcmp(bss->ssid, hs->ssid, hs->ssid_len)) goto next; - if (station_parse_bss_security(station, bss, &security) < 0) + if (scan_bss_get_security(bss, &security) < 0) goto next; if (security != orig_security) @@ -2375,8 +2387,12 @@ next: bss = network_bss_find_by_addr(network, best_bss->addr); if (bss) { - scan_bss_free(best_bss); - best_bss = bss; + network_bss_update(network, best_bss); + l_queue_remove(station->bss_list, bss); + scan_bss_free(bss); + + l_queue_insert(station->bss_list, best_bss, + scan_bss_rank_compare, NULL); } else { network_bss_add(network, best_bss); l_queue_push_tail(station->bss_list, best_bss); @@ -2618,9 +2634,12 @@ static void station_ap_directed_roam(struct station *station, valid_interval = l_get_u8(body + pos); pos++; - l_debug("roam: BSS transition received from AP: " + l_debug("roam: BSS transition received from AP: " MAC", " "Disassociation Time: %u, " - "Validity interval: %u", dtimer, valid_interval); + "Validity interval: %u, Address3: " MAC, + MAC_STR(hdr->address_2), + dtimer, valid_interval, + MAC_STR(hdr->address_3)); /* check req_mode for optional values */ if (req_mode & WNM_REQUEST_MODE_TERMINATION_IMMINENT) { @@ -2645,6 +2664,36 @@ static void station_ap_directed_roam(struct station *station, pos += url_len; } + if (station->state != STATION_STATE_CONNECTED) { + l_debug("roam: unexpected AP directed roam -- ignore"); + return; + } + + /* + * Sanitize the frame to check that it is from our current AP. + * + * 802.11-2020 Section 9.3.3.1 about Address2: + * "If the STA is an AP with dot11MultiBSSDImplemented set to false, + * then this address is the BSSID." + * + * Address3: + * "If the STA is an AP or PCP, the Address 3 field is the same as the + * Address 2 field." + * + * For now check that Address2 & Address3 is the same as the connected + * BSS address. + */ + if (memcmp(hdr->address_2, station->connected_bss, ETH_ALEN) || + memcmp(hdr->address_2, hdr->address_3, ETH_ALEN)) { + l_debug("roam: AP directed roam not from our AP -- ignore"); + return; + } + + if (station->preparing_roam) { + l_debug("roam: roam attempt already in progress -- ignore"); + return; + } + station->ap_directed_roaming = true; station->preparing_roam = true; @@ -3213,6 +3262,8 @@ next: } if (network_psk && network_open) { + station_hide_network(station, network_psk); + station_hide_network(station, network_open); dbus_pending_reply(&msg, dbus_error_service_set_overlap(msg)); return true; } @@ -3485,7 +3536,7 @@ static struct l_dbus_message *station_dbus_get_hidden_access_points( int16_t signal_strength = bss->signal_strength; enum security security; - if (station_parse_bss_security(station, bss, &security) < 0) + if (scan_bss_get_security(bss, &security) < 0) continue; l_dbus_message_builder_enter_struct(builder, "sns"); @@ -4258,7 +4309,7 @@ static struct network *station_find_network_from_bss(struct station *station, memcpy(ssid, bss->ssid, bss->ssid_len); ssid[bss->ssid_len] = '\0'; - if (station_parse_bss_security(station, bss, &security) < 0) + if (scan_bss_get_security(bss, &security) < 0) return NULL; return station_network_find(station, ssid, security); diff --git a/src/storage.c b/src/storage.c @@ -44,6 +44,7 @@ #include <ell/ell.h> #include "ell/useful.h" +#include "src/missing.h" #include "src/common.h" #include "src/storage.h" #include "src/crypto.h" diff --git a/src/util.c b/src/util.c @@ -314,6 +314,7 @@ bool util_ip_prefix_tohl(const char *ip, uint8_t *prefix_out, struct scan_freq_set { uint16_t channels_2ghz; struct l_uintset *channels_5ghz; + struct l_uintset *channels_6ghz; }; struct scan_freq_set *scan_freq_set_new(void) @@ -322,6 +323,7 @@ struct scan_freq_set *scan_freq_set_new(void) /* 802.11-2012, 8.4.2.10 hints that 200 is the largest channel number */ ret->channels_5ghz = l_uintset_new_from_range(1, 200); + ret->channels_6ghz = l_uintset_new_from_range(1, 233); return ret; } @@ -329,6 +331,7 @@ struct scan_freq_set *scan_freq_set_new(void) void scan_freq_set_free(struct scan_freq_set *freqs) { l_uintset_free(freqs->channels_5ghz); + l_uintset_free(freqs->channels_6ghz); l_free(freqs); } @@ -347,6 +350,8 @@ bool scan_freq_set_add(struct scan_freq_set *freqs, uint32_t freq) return true; case BAND_FREQ_5_GHZ: return l_uintset_put(freqs->channels_5ghz, channel); + case BAND_FREQ_6_GHZ: + return l_uintset_put(freqs->channels_6ghz, channel); } return false; @@ -366,6 +371,8 @@ bool scan_freq_set_contains(const struct scan_freq_set *freqs, uint32_t freq) return freqs->channels_2ghz & (1 << (channel - 1)); case BAND_FREQ_5_GHZ: return l_uintset_contains(freqs->channels_5ghz, channel); + case BAND_FREQ_6_GHZ: + return l_uintset_contains(freqs->channels_6ghz, channel); } return false; @@ -384,10 +391,15 @@ uint32_t scan_freq_set_get_bands(struct scan_freq_set *freqs) if (l_uintset_find_min(freqs->channels_5ghz) <= max) bands |= BAND_FREQ_5_GHZ; + max = l_uintset_get_max(freqs->channels_6ghz); + + if (l_uintset_find_min(freqs->channels_6ghz) <= max) + bands |= BAND_FREQ_6_GHZ; + return bands; } -static void scan_channels_5ghz_add(uint32_t channel, void *user_data) +static void scan_channels_add(uint32_t channel, void *user_data) { struct l_uintset *to = user_data; @@ -399,37 +411,41 @@ void scan_freq_set_merge(struct scan_freq_set *to, { to->channels_2ghz |= from->channels_2ghz; - l_uintset_foreach(from->channels_5ghz, scan_channels_5ghz_add, + l_uintset_foreach(from->channels_5ghz, scan_channels_add, to->channels_5ghz); + l_uintset_foreach(from->channels_6ghz, scan_channels_add, + to->channels_6ghz); } bool scan_freq_set_isempty(const struct scan_freq_set *set) { - if (set->channels_2ghz == 0 && l_uintset_isempty(set->channels_5ghz)) + if (set->channels_2ghz == 0 && l_uintset_isempty(set->channels_5ghz) && + l_uintset_isempty(set->channels_6ghz)) return true; return false; } -struct channels_5ghz_foreach_data { +struct channels_foreach_data { scan_freq_set_func_t func; + enum band_freq band; void *user_data; }; -static void scan_channels_5ghz_frequency(uint32_t channel, void *user_data) +static void scan_channels_foreach(uint32_t channel, void *user_data) { - const struct channels_5ghz_foreach_data *channels_5ghz_data = user_data; + const struct channels_foreach_data *channels_data = user_data; uint32_t freq; - freq = band_channel_to_freq(channel, BAND_FREQ_5_GHZ); + freq = band_channel_to_freq(channel, channels_data->band); - channels_5ghz_data->func(freq, channels_5ghz_data->user_data); + channels_data->func(freq, channels_data->user_data); } void scan_freq_set_foreach(const struct scan_freq_set *freqs, scan_freq_set_func_t func, void *user_data) { - struct channels_5ghz_foreach_data data = { }; + struct channels_foreach_data data = { }; uint8_t channel; uint32_t freq; @@ -437,10 +453,14 @@ void scan_freq_set_foreach(const struct scan_freq_set *freqs, return; data.func = func; + data.band = BAND_FREQ_5_GHZ; data.user_data = user_data; - l_uintset_foreach(freqs->channels_5ghz, scan_channels_5ghz_frequency, - &data); + l_uintset_foreach(freqs->channels_5ghz, scan_channels_foreach, &data); + + data.band = BAND_FREQ_6_GHZ; + + l_uintset_foreach(freqs->channels_6ghz, scan_channels_foreach, &data); if (!freqs->channels_2ghz) return; @@ -468,6 +488,14 @@ void scan_freq_set_constrain(struct scan_freq_set *set, l_uintset_free(set->channels_5ghz); set->channels_5ghz = intersection; + intersection = l_uintset_intersect(constraint->channels_6ghz, + set->channels_6ghz); + if (!intersection) + return; + + l_uintset_free(set->channels_6ghz); + set->channels_6ghz = intersection; + set->channels_2ghz &= constraint->channels_2ghz; } @@ -487,7 +515,8 @@ uint32_t *scan_freq_set_to_fixed_array(const struct scan_freq_set *set, uint32_t *freqs; count = __builtin_popcount(set->channels_2ghz) + - l_uintset_size(set->channels_5ghz); + l_uintset_size(set->channels_5ghz) + + l_uintset_size(set->channels_6ghz); if (!count) return NULL; diff --git a/src/wiphy.c b/src/wiphy.c @@ -106,6 +106,7 @@ struct wiphy { struct scan_freq_set *supported_freqs; struct band *band_2g; struct band *band_5g; + struct band *band_6g; char *model_str; char *vendor_str; char *driver_str; @@ -350,6 +351,11 @@ static void wiphy_free(void *data) wiphy->band_5g = NULL; } + if (wiphy->band_6g) { + band_free(wiphy->band_6g); + wiphy->band_6g = NULL; + } + scan_freq_set_free(wiphy->supported_freqs); watchlist_destroy(&wiphy->state_watches); l_free(wiphy->model_str); @@ -436,6 +442,9 @@ uint32_t wiphy_get_supported_bands(struct wiphy *wiphy) if (wiphy->band_5g) bands |= BAND_FREQ_5_GHZ; + if (wiphy->band_6g) + bands |= BAND_FREQ_6_GHZ; + return bands; } @@ -739,6 +748,9 @@ const uint8_t *wiphy_get_supported_rates(struct wiphy *wiphy, unsigned int band, case NL80211_BAND_5GHZ: bandp = wiphy->band_5g; break; + case NL80211_BAND_6GHZ: + bandp = wiphy->band_6g; + break; default: return NULL; } @@ -789,6 +801,9 @@ int wiphy_estimate_data_rate(struct wiphy *wiphy, case BAND_FREQ_5_GHZ: bandp = wiphy->band_5g; break; + case BAND_FREQ_6_GHZ: + bandp = wiphy->band_6g; + break; default: return -ENOTSUP; } @@ -979,6 +994,9 @@ static void wiphy_print_basic_info(struct wiphy *wiphy) if (wiphy->band_5g) wiphy_print_band_info(wiphy->band_5g, "5Ghz Band"); + if (wiphy->band_6g) + wiphy_print_band_info(wiphy->band_6g, "6GHz Band"); + if (wiphy->supported_ciphers) { int len = 0; @@ -1193,6 +1211,9 @@ static void parse_supported_bands(struct wiphy *wiphy, case NL80211_BAND_5GHZ: bandp = &wiphy->band_5g; break; + case NL80211_BAND_6GHZ: + bandp = &wiphy->band_6g; + break; default: continue; } diff --git a/src/wiphy.h b/src/wiphy.h @@ -45,11 +45,13 @@ struct wiphy_radio_work_item { const struct wiphy_radio_work_item_ops *ops; }; -#define WIPHY_WORK_PRIORITY_FRAME 0 -#define WIPHY_WORK_PRIORITY_OFFCHANNEL 0 -#define WIPHY_WORK_PRIORITY_CONNECT 1 -#define WIPHY_WORK_PRIORITY_SCAN 2 -#define WIPHY_WORK_PRIORITY_PERIODIC_SCAN 3 +enum { + WIPHY_WORK_PRIORITY_FRAME = 0, + WIPHY_WORK_PRIORITY_OFFCHANNEL = 0, + WIPHY_WORK_PRIORITY_CONNECT = 1, + WIPHY_WORK_PRIORITY_SCAN = 2, + WIPHY_WORK_PRIORITY_PERIODIC_SCAN = 3, +}; enum wiphy_state_watch_event { WIPHY_STATE_WATCH_EVENT_POWERED, @@ -70,7 +72,10 @@ enum ie_rsn_akm_suite wiphy_select_akm(struct wiphy *wiphy, bool fils_capable_hint); struct wiphy *wiphy_find(int wiphy_id); -#define wiphy_find_by_wdev(w) wiphy_find(w >> 32) +static inline struct wiphy *wiphy_find_by_wdev(uint64_t w) +{ + return wiphy_find(w >> 32); +} bool wiphy_is_blacklisted(const struct wiphy *wiphy); diff --git a/src/wsc.c b/src/wsc.c @@ -308,6 +308,7 @@ static inline enum wsc_rf_band freq_to_rf_band(uint32_t freq) case BAND_FREQ_2_4_GHZ: return WSC_RF_BAND_2_4_GHZ; case BAND_FREQ_5_GHZ: + case BAND_FREQ_6_GHZ: return WSC_RF_BAND_5_0_GHZ; } diff --git a/tools/hwsim.c b/tools/hwsim.c @@ -1707,6 +1707,7 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, bool p2p = false; const char *disabled_iftypes = NULL; const char *disabled_ciphers = NULL; + bool no_vif = false; struct radio_info_rec *radio; if (!l_dbus_message_get_arguments(message, "a{sv}", &dict)) @@ -1727,6 +1728,10 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, else if (!strcmp(key, "CipherTypeDisable")) ret = l_dbus_message_iter_get_variant(&variant, "s", &disabled_ciphers); + else if (!strcmp(key, "NoVirtualInterface")) + ret = l_dbus_message_iter_get_variant(&variant, "b", + &no_vif); + if (!ret) goto invalid; } @@ -1765,6 +1770,9 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, } + if (no_vif) + l_genl_msg_append_attr(new_msg, HWSIM_ATTR_NO_VIF, 0, NULL); + radio = l_new(struct radio_info_rec, 1); radio->pending = l_dbus_message_ref(message); radio->name = l_strdup(name); diff --git a/tools/run-tests b/tools/run-tests @@ -0,0 +1,1013 @@ +#!/usr/bin/python3 + +import os +import shutil +import sys +import subprocess +import atexit +import time +import unittest +import importlib +from unittest.result import TestResult +import multiprocessing +import re +import traceback + +from configparser import ConfigParser +from prettytable import PrettyTable +from termcolor import colored +from glob import glob +from collections import namedtuple +import dbus.mainloop.glib +from gi.repository import GLib + +from runner import Runner +from utils import Process, Namespace, BarChart + +config = None +intf_id = 0 + +TEST_MAX_TIMEOUT = 240 + +dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + +def dbg(*s, **kwargs): + ''' + Allows prints if stdout has been re-directed + ''' + print(*s, **kwargs, file=sys.__stdout__) + +def exit_vm(): + if config: + for p in Process.get_all(): + print("Process %s still running!" % p.args[0]) + p.kill() + + if config.ctx and config.ctx.results: + success = print_results(config.ctx.results) + else: + success = False + + if config.ctx.args.result: + result = 'PASS' if success else 'FAIL' + with open(config.ctx.args.result, 'w') as f: + f.write(result) + + os.sync() + + runner.stop() + +class Interface: + def __init__(self, name, config): + self.name = name + self.ctrl_interface = '/var/run/hostapd/' + name + self.config = config + + def __del__(self): + Process(['iw', 'dev', self.name, 'del']).wait() + + def set_interface_state(self, state): + Process(['ip', 'link', 'set', self.name, state]).wait() + +class Radio: + def __init__(self, name): + self.name = name + # hostapd will reset this if this radio is used by it + self.use = 'iwd' + self.interface = None + + def __del__(self): + print("Removing radio %s" % self.name) + self.interface = None + + def create_interface(self, config, use): + global intf_id + + ifname = 'wln%s' % intf_id + + intf_id += 1 + + self.interface = Interface(ifname, config) + self.use = use + + Process(['iw', 'phy', self.name, 'interface', 'add', ifname, + 'type', 'managed']).wait() + + return self.interface + + def __str__(self): + ret = self.name + ':\n' + ret += '\tUsed By: %s ' % self.use + if self.interface: + ret += '(%s)' % self.interface.name + + ret += '\n' + + return ret + +class VirtualRadio(Radio): + ''' + A subclass of 'Radio' specific to mac80211_hwsim radios. + + TODO: Using D-Bus to create and destroy radios is more desireable + than the command line. + ''' + + def __init__(self, name, cfg=None): + global config + + self.disable_cipher = None + self.disable_iftype = None + + self.hwsim = config.hwsim.Hwsim() + + if cfg: + self.disable_iftype = cfg.get('iftype_disable', None) + self.disable_cipher = cfg.get('cipher_disable', None) + + self._radio = self.hwsim.radios.create(name, p2p_device=True, + iftype_disable=self.disable_iftype, + cipher_disable=self.disable_cipher) + + super().__init__(self._radio.name) + + def __del__(self): + super().__del__() + + # If the radio was moved into a namespace this will fail + try: + self._radio.remove() + except: + pass + + self._radio = None + + def __str__(self): + ret = super().__str__() + + if self.disable_iftype: + ret += '\tDisabled interface types: %s\n' % self.disable_iftype + + if self.disable_cipher: + ret += '\tDisabled ciphers: %s\n' % self.disable_cipher + + ret += '\tPath: %s' % self._radio.path + + ret += '\n' + + return ret + +class HostapdInstance: + ''' + A single instance of hostapd. In reality all hostapd instances + are started as a single process. This class just makes things + convenient for communicating with one of the hostapd APs. + ''' + def __init__(self, config, radio): + self.radio = radio + self.config = config + self.cli = None + + self.intf = radio.create_interface(self.config, 'hostapd') + self.intf.set_interface_state('up') + + def __del__(self): + print("Removing HostapdInstance %s" % self.config) + self.intf.set_interface_state('down') + self.radio = None + self.intf = None + + def __str__(self): + ret = 'Hostapd (%s)\n' % self.intf.name + ret += '\tConfig: %s\n' % self.config + + return ret + +class Hostapd: + ''' + A set of running hostapd instances. This is really just a single + process since hostapd can be started with multiple config files. + ''' + def __init__(self, radios, configs, radius): + if len(configs) != len(radios): + raise Exception("Config (%d) and radio (%d) list length not equal" % \ + (len(configs), len(radios))) + + print("Initializing hostapd instances") + + Process(['ip', 'link', 'set', 'eth0', 'up']).wait() + Process(['ip', 'link', 'set', 'eth1', 'up']).wait() + + self.global_ctrl_iface = '/var/run/hostapd/ctrl' + + self.instances = [HostapdInstance(c, r) for c, r in zip(configs, radios)] + + ifaces = [rad.interface.name for rad in radios] + ifaces = ','.join(ifaces) + + args = ['hostapd', '-g', self.global_ctrl_iface] + + if ifaces: + args.extend(['-i', ifaces]) + + # + # Config files should already be present in /tmp. This appends + # ctrl_interface and does any variable replacement. Currently + # this is just any $ifaceN occurrences. + # + for c in configs: + full_path = '/tmp/%s' % c + args.append(full_path) + + self._rewrite_config(full_path) + + if radius: + args.append(radius) + + if Process.is_verbose('hostapd'): + args.append('-d') + + self.process = Process(args) + + self.process.wait_for_socket(self.global_ctrl_iface, 30) + + for hapd in self.instances: + self.process.wait_for_socket(hapd.intf.ctrl_interface, 30) + + def attach_cli(self): + global config + + for hapd in self.instances: + hapd.cli = config.hostapd.HostapdCLI(config=hapd.config) + + def _rewrite_config(self, config): + ''' + Replaces any $ifaceN values with the correct interface + names as well as appends the ctrl_interface path to + the config file. + ''' + with open(config, 'r+') as f: + data = f.read() + to_replace = [] + for match in re.finditer(r'\$iface[0-9]+', data): + tag = data[match.start():match.end()] + idx = tag.split('iface')[1] + + to_replace.append((tag, self.instances[int(idx)].intf.name)) + + for r in to_replace: + data = data.replace(r[0], r[1], 1) + + data += '\nctrl_interface=/var/run/hostapd\n' + + f.write(data) + + def __getitem__(self, config): + if not config: + return self.instances[0] + + for hapd in self.instances: + if hapd.config == config: + return hapd + + return None + + def __del__(self): + print("Removing Hostapd") + try: + os.remove(self.global_ctrl_iface) + except: + print("Failed to remove %s" % self.global_ctrl_iface) + + for hapd in self.instances: + GLib.source_remove(hapd.cli.io_watch) + + # Hostapd may have already been stopped + if self.process: + self.process.kill() + + # Hostapd creates simdb sockets for EAP-SIM/AKA tests but does not + # clean them up. + for f in glob("/tmp/eap_sim_db*"): + os.remove(f) + +class TestContext(Namespace): + ''' + Contains all information for a given set of tests being run + such as processes, radios, interfaces and test results. + ''' + def __init__(self, args): + self.name = None + self.args = args + self.hw_config = None + self.hostapd = None + self.wpas_interfaces = None + self.radios = [] + self.results = {} + self.namespaces = [] + self._last_mem_available = 0 + self._mem_chart = BarChart() + + def start_dbus_monitor(self): + if not Process.is_verbose('dbus-monitor'): + return + + self.start_process(['dbus-monitor', '--address', self.dbus_address]) + + def start_haveged(self): + self.start_process(['haveged', '-F']) + + def create_radios(self): + setup = self.hw_config['SETUP'] + nradios = int(setup['num_radios']) + args = ['hwsim'] + + if self.hw_config['SETUP'].get('hwsim_medium', 'no') in ['no', '0', 'false']: + # register hwsim as medium + args.extend(['--no-register']) + + self.start_process(args) + self.non_block_wait(self._bus.name_has_owner, 20, 'net.connman.hwsim', + exception=TimeoutError('net.connman.hwsim did not appear')) + + for i in range(nradios): + name = 'rad%u' % i + + # Get any [radX] sections. These are for configuring + # any special radios. This no longer requires a + # radio_conf list, we just assume radios start rad0 + # and increment. + rad_config = None + if self.hw_config.has_section(name): + rad_config = self.hw_config[name] + + self.radios.append(VirtualRadio(name, rad_config)) + + def discover_radios(self): + import pyroute2 + + phys = [] + + try: + iw = pyroute2.iwutil.IW() + except: + iw = pyroute2.IW() + + attrs = [phy['attrs'] for phy in iw.list_wiphy()] + + for attr in attrs: + for key, value in attr: + if key == 'NL80211_ATTR_WIPHY_NAME': + if value not in phys: + phys.append(value) + break + + print('Discovered radios: %s' % str(phys)) + self.radios = [Radio(name) for name in phys] + + def start_radios(self): + reg_domain = self.hw_config['SETUP'].get('reg_domain', None) + if reg_domain: + Process(['iw', 'reg', 'set', reg_domain]).wait() + + if self.args.hw: + self.discover_radios() + else: + self.create_radios() + + def start_hostapd(self): + if not 'HOSTAPD' in self.hw_config: + return + + settings = self.hw_config['HOSTAPD'] + + if self.args.hw: + # Just grab the first N radios. It gets rather + # complicated trying to map radX radios specified in + # hw.conf so any passed through physical adapters are + # just given to hostapd/IWD as they appear during + # discovery. + # + # TODO: It may be desireable to map PCI/USB adapters to + # specific radX radios specified in the config but + # there are really 2 separate use cases here. + # 1. You want to test a *specific* radio with IWD + # or hostapd. For this you would want radX + # to map to a specific radio + # 2. You have many adapters in use to run multiple + # tests. In this case you would not care what + # was using each radio, just that there was + # enough to run all tests. + nradios = 0 + for k, _ in settings.items(): + if k == 'radius_server': + continue + nradios += 1 + + hapd_radios = self.radios[:nradios] + + else: + hapd_radios = [rad for rad in self.radios if rad.name in settings] + + hapd_configs = [conf for rad, conf in settings.items() if rad != 'radius_server'] + + radius_config = settings.get('radius_server', None) + + self.hostapd = Hostapd(hapd_radios, hapd_configs, radius_config) + self.hostapd.attach_cli() + + def get_frequencies(self): + frequencies = [] + + for hapd in self.hostapd.instances: + frequencies.append(hapd.cli.frequency) + + return frequencies + + def start_wpas_interfaces(self): + + if 'WPA_SUPPLICANT' not in self.hw_config: + return + + settings = self.hw_config['WPA_SUPPLICANT'] + + if self.args.hw: + nradios = len(settings.items()) + + wpas_radios = self.radios[:nradios] + self.wpas_interfaces = [] + + # + # Physical radios most likely will use a different name + # than 'rad#' but the config file is referenced by these + # 'rad#' names. Iterate through both the settings and + # physical radios to create interfaces associated with + # each config file. + # + for vrad, hwrad in zip(settings.items(), wpas_radios): + self.wpas_interfaces.append(hwrad.create_interface(vrad[1], 'wpas')) + + else: + wpas_radios = [rad for rad in self.radios if rad.name in settings] + self.wpas_interfaces = [rad.create_interface(settings[rad.name], 'wpas') \ + for rad in wpas_radios] + + def start_ofono(self): + sim_keys = self.hw_config['SETUP'].get('sim_keys', None) + if not sim_keys: + print("Ofono not requred") + return + elif sim_keys != 'ofono': + os.environ['IWD_SIM_KEYS'] = sim_keys + return + + if not shutil.which('ofonod') or not shutil.which('phonesim'): + print("Ofono or Phonesim not found, skipping test") + return + + Process(['ip', 'link', 'set', 'lo', 'up']).wait() + + os.environ['OFONO_PHONESIM_CONFIG'] = '/tmp/phonesim.conf' + + phonesim_args = ['phonesim', '-p', '12345', '/usr/share/phonesim/default.xml'] + + self.start_process(phonesim_args) + + # + # TODO: + # Is there something to wait for? Without this phonesim rejects + # connections on all but the fist test. + # + time.sleep(3) + + ofono_args = ['ofonod', '-n', '--plugin=atmodem,phonesim'] + if Process.is_verbose('ofonod'): + ofono_args.append('-d') + + self.start_process(ofono_args) + + print("Ofono started") + + def create_namespaces(self): + if not self.hw_config.has_section('NameSpaces'): + return + + for key, value in self.hw_config.items('NameSpaces'): + radio_names = value.split(',') + # Gather up radio objects for this namespace + radios = [rad for rad in self.radios if rad.name in radio_names] + + # Remove radios from 'root' namespace + self.radios = list(set(self.radios) - set(radios)) + + self.namespaces.append(Namespace(self.args, key, radios)) + + def get_namespace(self, ns): + for n in self.namespaces: + if n.name == ns: + return n + + return None + + def stop_test_processes(self): + for n in self.namespaces: + n.reset() + + self.namespaces = [] + self.hostapd = None + self.wpas_interfaces = None + + self.reset() + + def meminfo_to_dict(self): + def removesuffix(string, suffix): + if string.endswith(suffix): + return string[:-len(suffix)] + return string + + ret = {} + + with open('/proc/meminfo', 'r') as f: + data = f.read().strip().split('\n') + + for l in data: + entry = l.split(':') + ret[entry[0]] = int(removesuffix(entry[1], 'kB')) + + return ret + + def __str__(self): + ret = 'Arguments:\n' + for arg in vars(self.args): + ret += '\t --%s %s\n' % (arg, str(getattr(self.args, arg))) + + ret += 'Hostapd:\n' + if self.hostapd: + for h in self.hostapd.instances: + ret += '\t%s\n' % str(h) + else: + ret += '\tNo Hostapd instances\n' + + info = self.meminfo_to_dict() + self._mem_chart.add_value(info['MemAvailable']) + + ret += 'Available Memory: %u kB\n' % info['MemAvailable'] + ret += 'Last Test Delta: %+d kB\n' % (info['MemAvailable'] - self._last_mem_available) + ret += 'Per-test Usage:\n' + ret += str(self._mem_chart) + + self._last_mem_available = info['MemAvailable'] + + ret += super().__str__() + + for n in self.namespaces: + ret += n.__str__() + + return ret + +def build_unit_list(args): + ''' + Build list of unit tests based on passed arguments. This first + checks for literal names provided in the arguments, then if + no matches were found, checks for a glob match. + ''' + tests = [] + test_root = args.testhome + '/unit' + + for unit in args.unit_tests.split(','): + path = '%s/%s' % (test_root, unit) + if os.access(unit, os.X_OK): + tests.append(unit) + elif os.access(path, os.X_OK): + tests.append(path) + else: + # Full list or glob, first build up valid list of tests + matches = glob(path) + if matches == []: + raise Exception("Could not find test %s" % unit) + + matches = [exe for exe in matches if os.access(exe, os.X_OK)] + + tests.extend(matches) + + return sorted(tests) + +def build_test_list(args): + ''' + Build list of auto test directories based on passed arguments. + First check for absolute paths, then look in <iwd>/autotests, + then glob match. + ''' + tests = [] + test_root = args.testhome + '/autotests' + + # Run all tests + if not args.autotests: + # Get list of all autotests (committed in git) + tests = os.popen('git -C %s ls-files autotests/ | cut -f2 -d"/" \ + | grep "test*" | uniq' % args.testhome).read() \ + .strip().split('\n') + tests = [test_root + '/' + t for t in tests] + else: + print("Generating partial test list") + + full_list = sorted(os.listdir(test_root)) + + for t in args.autotests.split(','): + path = '%s/%s' % (test_root, t) + if t.endswith('+'): + t = t.split('+')[0] + i = full_list.index(t) + + tests = [test_root + '/' + x for x in full_list[i:] \ + if x.startswith('test')] + elif os.path.exists(t): + if t not in tests: + tests.append(t) + elif os.path.exists(path): + if path not in tests: + tests.append(path) + else: + matches = glob(path) + if matches == []: + raise Exception("Could not find test %s" % t) + + tests.extend(list(set(matches) - set(tests))) + + return sorted(tests) + +SimpleResult = namedtuple('SimpleResult', 'run failures errors skipped time') + +def start_test(ctx, subtests, rqueue): + ''' + Run an individual test. 'subtests' are parsed prior to calling + but these effectively make up a single test. 'rqueue' is the + results queue which is required since this is using + multiprocessing. + ''' + run = 0 + errors = 0 + failures = 0 + skipped = 0 + + start = time.time() + # + # Iterate through each individual python test. + # + for s in subtests: + loader = unittest.TestLoader() + try: + module = importlib.import_module(os.path.splitext(s)[0]) + except OSError as e: + dbg(subprocess.check_output("cat /proc/buddyinfo", shell=True).decode('utf-8')) + dbg(subprocess.check_output("dmesg | tail -80", shell=True).decode('utf-8')) + print(ctx) + raise e + + subtest = loader.loadTestsFromModule(module) + + # The test suite is being (ab)used to get a bit more granularity + # with individual tests. The 'normal' way to use unittest is to + # just create a test suite and run them. The problem here is that + # test results are queued and printed at the very end so its + # difficult to know *where* a test failed (python gives a stack + # trace but printing the exception/failure immediately shows + # where in the debug logs something failed). Moreso if there are + # several test functions inside a single python file they run + # as a single test and it is difficult (again) to know where + # something failed. + + # Iterating through each python test file + for test in subtest: + limit_funcs = [] + + if ctx.args.sub_tests: + for i in ctx.args.sub_tests: + if len(i.split('.')) == 2: + limit_funcs.append(i.split('.')[1]) + + # Iterating through individual test functions inside a + # Test() class. Due to the nature of unittest we have + # to jump through some hoops to set up the test class + # only once by turning the enumeration into a list, then + # enumerating (again) to keep track of the index (just + # enumerating the test class doesn't allow len() because + # it is not a list). + tlist = list(enumerate(test)) + for index, t in enumerate(tlist): + # enumerate is returning a tuple, index 1 is our + # actual object. + t = t[1] + + func, file = str(t).split(' ') + # + # TODO: There may be a better way of doing this + # but strigifying the test class gives us a string: + # <function> (<file>.<class>) + # + file = file.strip('()').split('.')[0] + '.py' + + # Create an empty result here in case the test fails + result = TestResult() + + try: + skip = len(limit_funcs) > 0 and func not in limit_funcs + + # Set up class only on first test + if index == 0: + if not skip: + dbg("%s\n\t%s RUNNING" % (file, str(func)), end='') + t.setUpClass() + else: + if not skip: + dbg("\t%s RUNNING" % str(func), end='') + + sys.__stdout__.flush() + + name = os.path.basename(os.getcwd()) + + Process.write_separators(name, "\n====== %s:%s:%s ======\n\n" % + (name, file, func)) + + if not skip: + # Run test (setUp/tearDown run automatically) + result = t() + + # Tear down class only on last test + if index == len(tlist) - 1: + t.tearDownClass() + + if skip: + continue + except unittest.SkipTest as e: + result.skipped.append(t) + except Exception as e: + dbg('\n%s threw an uncaught exception:' % func) + traceback.print_exc(file=sys.__stdout__) + + run += result.testsRun + errors += len(result.errors) + failures += len(result.failures) + skipped += len(result.skipped) + + if len(result.skipped) > 0: + dbg(colored(" SKIPPED", "cyan")) + elif run == 0 or len(result.errors) > 0 or len(result.failures) > 0: + dbg(colored(" FAILED", "red")) + for e in result.errors: + dbg(e[1]) + for f in result.failures: + dbg(f[1]) + else: + dbg(colored(" PASSED", "green")) + + # Prevents future test modules with the same name (e.g. + # connection_test.py) from being loaded from the cache + sys.modules.pop(module.__name__) + + # + # The multiprocessing queue is picky with what objects it will serialize + # and send between processes. Because of this we put the important bits + # of the result into our own 'SimpleResult' tuple. + # + sresult = SimpleResult(run=run, failures=failures, errors=errors, + skipped=skipped, time=time.time() - start) + rqueue.put(sresult) + + # This may not be required since we are manually popping sys.modules + importlib.invalidate_caches() + +def pre_test(ctx, test, copied): + ''' + Copy test files, start processes, and any other pre test work. + ''' + os.chdir(test) + + dbg("\nStarting %s" % colored(os.path.basename(test), "white", attrs=['bold'])) + if not os.path.exists(test + '/hw.conf'): + raise Exception("No hw.conf found for %s" % test) + + ctx.hw_config = ConfigParser() + ctx.hw_config.read(test + '/hw.conf') + # + # We have two types of test files: tests and everything else. Rather + # than require each test to specify the files needing to be copied to + # /tmp (previously 'tmpfs_extra_stuff'), we just copy everything which + # isn't a test. There is really no reason not to do this as any file + # present in a test directory should be needed by the test. + # + # All files + files = os.listdir(test) + # Tests (starts or ends with 'test') + subtests = [f for f in files if f.startswith('test') or \ + os.path.splitext(f)[0].endswith('test')] + # Everything else (except .py files) + to_copy = [f for f in list(set(files) - set(subtests)) if not f.endswith('.py') \ + and f != '__pycache__'] + for f in to_copy: + if os.path.isdir(f): + shutil.copytree(f, '/tmp/' + f) + else: + shutil.copy(f, '/tmp') + copied.append(f) + + # Prune down any subtests if needed + if ctx.args.sub_tests: + ctx.args.sub_tests = ctx.args.sub_tests.split(',') + + to_run = [x.split('.')[0] for x in ctx.args.sub_tests] + pruned = [] + + for s in subtests: + no_ext = s + # Handle <file>.<test function> format + if '.' in s: + no_ext = s.split('.')[0] + + if no_ext in to_run: + pruned.append(no_ext + '.py') + + subtests = pruned + + if ctx.args.log: + ctx.start_process(['iwmon', '--nowiphy']) + elif ctx.args.monitor: + ctx.start_process(['iwmon'], outfile=ctx.args.monitor) + + ctx.start_dbus() + ctx.start_haveged() + ctx.start_dbus_monitor() + ctx.start_radios() + ctx.create_namespaces() + ctx.start_hostapd() + ctx.start_wpas_interfaces() + ctx.start_ofono() + + if ctx.hw_config.getboolean('SETUP', 'start_iwd', fallback=True): + ctx.start_iwd() + + print(ctx) + + sys.path.insert(1, test) + + return sorted(subtests) + +def post_test(ctx, to_copy): + ''' + Remove copied files, and stop test processes. + ''' + try: + for f in to_copy: + if os.path.isdir('/tmp/' + f): + shutil.rmtree('/tmp/' + f) + else: + os.remove('/tmp/' + f) + + Process(['ip', 'link', 'set', 'lo', 'down']).wait() + except Exception as e: + print("Exception thrown in post_test") + finally: + ctx.stop_test_processes() + + if ctx.args.valgrind: + for f in os.listdir('/tmp'): + if f.startswith("valgrind.log."): + dbg(f) + with open('/tmp/' + f, 'r') as v: + dbg(v.read()) + dbg("\n") + os.remove('/tmp/' + f) + + # Special case for when logging is enabled + if os.path.isfile('/tmp/iwd-tls-debug-server-cert.pem'): + os.remove('/tmp/iwd-tls-debug-server-cert.pem') + + allowed = ['phonesim.conf', 'certs', 'secrets', 'iwd'] + for f in [f for f in os.listdir('/tmp') if f not in allowed]: + dbg("File %s was not cleaned up!" % f) + try: + os.remove('/tmp/' + f) + except: + pass + +def print_results(results): + table = PrettyTable(['Test', colored('Passed', 'green'), colored('Failed', 'red'), \ + colored('Skipped', 'cyan'), colored('Time', 'yellow')]) + + total_pass = 0 + total_fail = 0 + total_skip = 0 + total_time = 0 + + for test, result in results.items(): + + if result.time == TEST_MAX_TIMEOUT: + failed = "Timed out" + passed = "Timed out" + elif result.time == 0: + failed = "Exception" + passed = "Exception" + else: + failed = result.failures + result.errors + passed = result.run - failed + + total_pass += passed + total_fail += failed + total_skip += result.skipped + + total_time += result.time + + time = '%.2f' % result.time + + table.add_row([test, colored(passed, 'green'), colored(failed, 'red'), \ + colored(result.skipped, 'cyan'), colored(time, 'yellow')]) + + total_time = '%.2f' % total_time + + table.add_row(['Total', colored(total_pass, 'green'), colored(total_fail, 'red'), \ + colored(total_skip, 'cyan'), colored(total_time, 'yellow')]) + + dbg(table) + + return total_fail == 0 + +def run_auto_tests(ctx, args): + tests = build_test_list(args) + + for test in tests: + copied = [] + try: + subtests = pre_test(ctx, test, copied) + + if len(subtests) < 1: + dbg("No tests to run") + sys.exit() + + rqueue = multiprocessing.Queue() + p = multiprocessing.Process(target=start_test, args=(ctx, subtests, rqueue)) + p.start() + # Rather than time each subtest we just time the total but + # mutiply the default time by the number of tests being run. + p.join(TEST_MAX_TIMEOUT * len(subtests)) + + if p.is_alive(): + # Timeout + p.terminate() + + ctx.results[os.path.basename(test)] = SimpleResult(run=0, + failures=0, errors=0, + skipped=0, time=TEST_MAX_TIMEOUT) + else: + ctx.results[os.path.basename(test)] = rqueue.get() + + except Exception as ex: + dbg("%s threw an uncaught exception" % test) + traceback.print_exc(file=sys.__stdout__) + ctx.results[os.path.basename(test)] = SimpleResult(run=0, failures=0, + errors=0, skipped=0, time=0) + finally: + post_test(ctx, copied) + +def run_unit_tests(ctx, args): + os.chdir(args.testhome + '/unit') + units = build_unit_list(args) + + for u in units: + p = ctx.start_process([u]).wait() + if p.returncode != 0: + dbg("Unit test %s failed" % os.path.basename(u)) + else: + dbg("Unit test %s passed" % os.path.basename(u)) + +def run_tests(args): + global config + + os.chdir(args.testhome) + + # + # This allows all autotest utils (iwd/hostapd/etc) to access the + # TestContext. Any other module or script (in the same interpreter) can + # simply import config.ctx and access all live test information, + # start/stop processes, see active radios etc. + # + config = importlib.import_module('config') + config.ctx = TestContext(args) + + # Must import these after config so ctx gets set + config.hwsim = importlib.import_module('hwsim') + config.hostapd = importlib.import_module('hostapd') + + # Start writing out kernel log + config.ctx.start_process(["dmesg", '--follow']) + + if args.unit_tests is None: + run_auto_tests(config.ctx, args) + else: + run_unit_tests(config.ctx, args) + +runner = Runner() + +atexit.register(exit_vm) +runner.prepare_environment() +run_tests(runner.args) +runner.cleanup_environment() diff --git a/tools/runner.py b/tools/runner.py @@ -0,0 +1,540 @@ +#!/usr/bin/python3 + +from argparse import ArgumentParser, Namespace, SUPPRESS +from configparser import ConfigParser +from collections import namedtuple +from shutil import copy, copytree, which, rmtree +from glob import glob + +import os +import ctypes +import fcntl +import sys + +libc = ctypes.cdll['libc.so.6'] +libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, \ + ctypes.c_ulong, ctypes.c_char_p) + +# Using ctypes to load the libc library is somewhat low level. Because of this +# we need to define our own flags/options for use with mounting. +MS_NOSUID = 2 +MS_NODEV = 4 +MS_NOEXEC = 8 +MS_STRICTATIME = 1 << 24 +STDIN_FILENO = 0 +TIOCSTTY = 0x540E + +MountInfo = namedtuple('MountInfo', 'fstype source target options flags') +DevInfo = namedtuple('DevInfo', 'target linkpath') + +mounts_common = [ + MountInfo('sysfs', 'sysfs', '/sys', '', MS_NOSUID|MS_NOEXEC|MS_NODEV), + MountInfo('proc', 'proc', '/proc', '', MS_NOSUID|MS_NOEXEC|MS_NODEV), + MountInfo('devpts', 'devpts', '/dev/pts', 'mode=0620', MS_NOSUID|MS_NOEXEC), + MountInfo('tmpfs', 'tmpfs', '/dev/shm', 'mode=1777', + MS_NOSUID|MS_NODEV|MS_STRICTATIME), + MountInfo('tmpfs', 'tmpfs', '/run', 'mode=0755', + MS_NOSUID|MS_NODEV|MS_STRICTATIME), + MountInfo('tmpfs', 'tmpfs', '/tmp', '', 0), + MountInfo('tmpfs', 'tmpfs', '/usr/share/dbus-1', 'mode=0755', + MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME), +] + +dev_table = [ + DevInfo('/proc/self/fd', '/dev/fd'), + DevInfo('/proc/self/fd/0', '/dev/stdin'), + DevInfo('/proc/self/fd/1', '/dev/stdout'), + DevInfo('/proc/self/fd/2', '/dev/stderr') +] + +def mount(source, target, fs, flags, options=''): + ''' + Python wrapper for libc mount() + ''' + ret = libc.mount(source.encode(), target.encode(), fs.encode(), flags, + options.encode()) + if ret < 0: + errno = ctypes.get_errno() + raise Exception("Could not mount %s (%d)" % (target, errno)) + +# +# Custom argparse.Namespace class to stringify arguments in a way that can be +# directly passed to the test environment as kernel arguments. This also removes +# any None, False, or [] arguments. +# +class RunnerNamespace(Namespace): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def to_cmd(self): + ret = '' + for k, v in self.__dict__.items(): + if v in [None, False, [], '']: + continue + + ret += '%s=%s ' % (k, str(v)) + + return ret.strip() + +# +# The core arguments needed both inside and outside the test environment +# +class RunnerCoreArgParse(ArgumentParser): + def __init__(self, *args, **kwargs): + ArgumentParser.__init__(self, *args, **kwargs) + + self.add_argument('--start', '-s', + help='Custom init process in virtual environment', + dest='start', + default=None, + type=os.path.abspath) + self.add_argument('--verbose', '-v', metavar='<list>', + type=str, + help='Comma separated list of applications', + dest='verbose', + default=[]) + self.add_argument('--debug', '--dbg', '-d', + action='store_true', + help='Enable test-runner debugging', + dest='dbg') + self.add_argument('--log', '-l', + type=os.path.abspath, + help='Directory for log files') + self.add_argument('--monitor', '-m', + type=os.path.abspath, + help='Enables iwmon output to file') + self.add_argument('--sub-tests', '-S', + metavar='<subtests>', + type=str, nargs=1, help='List of subtests to run', + default=None, dest='sub_tests') + self.add_argument('--result', '-e', + type=os.path.abspath, + help='Writes PASS/FAIL to results file') + self.add_argument('--hw', '-w', + type=str, + help='Use physical adapters for tests (passthrough)') + self.add_argument('--testhome', help=SUPPRESS) + self.add_argument('--monitor_parent', help=SUPPRESS) + self.add_argument('--result_parent', help=SUPPRESS) + + # Prevent --autotest/--unittest from being used together + auto_unit_group = self.add_mutually_exclusive_group() + auto_unit_group.add_argument('--autotests', '-A', + metavar='<tests>', + type=str, + help='List of tests to run', + default=None, + dest='autotests') + auto_unit_group.add_argument('--unit-tests', '-U', + metavar='<tests>', + type=str, + nargs='?', + const='*', + help='List of unit tests to run', + dest='unit_tests') + + # Prevent --valgrind/--gdb from being used together + valgrind_gdb_group = self.add_mutually_exclusive_group() + valgrind_gdb_group.add_argument('--gdb', '-g', + metavar='<exec>', + type=str, + nargs=1, + help='Run gdb on specified executable', + dest='gdb') + valgrind_gdb_group.add_argument('--valgrind', '-V', + action='store_true', + help='Run valgrind on IWD', + dest='valgrind') + + # Overwrite to use a custom namespace class and parse from env + def parse_args(self, *args): + if len(sys.argv) > 1: + return super().parse_args(*args, namespace=RunnerNamespace()) + + options = [] + for k, v in os.environ.items(): + options.append('--' + k) + options.append(v) + + return self.parse_known_args(args=options, namespace=RunnerNamespace())[0] + +# +# Arguments only needed outside the test environment +# +class RunnerArgParse(RunnerCoreArgParse): + def __init__(self, *args, **kwargs): + RunnerCoreArgParse.__init__(self, *args, **kwargs) + + self.add_argument('--runner', '-r', + metavar='<runner type>', + type=str, + help='Type of runner to use (qemu, uml, host)', + dest='runner', + default=None) + self.add_argument('--kernel', '-k', + metavar='<kernel>', + type=os.path.abspath, + help='Path to kernel/uml image', + dest='kernel', + default=None) + +# +# Class to sort out what type of runner this is, returns the RunnerAbstract +# implementation. +# +class Runner: + def __new__(self): + parser = RunnerArgParse(description='IWD Test Runner') + + args = parser.parse_args() + + # Common options + args.PATH = os.environ['PATH'] + + if 'testhome' not in args.to_cmd(): + if os.getcwd().endswith('tools'): + args.testhome = '%s/../' % os.getcwd() + else: + args.testhome = os.getcwd() + + if args.start is None: + if os.path.exists('run-tests'): + args.start = os.path.abspath('run-tests') + elif os.path.exists('tools/run-tests'): + args.start = os.path.abspath('tools/run-tests') + else: + raise Exception("Cannot locate run-tests binary") + + # If no runner is specified but we have a kernel image assume + # if the kernel is executable its UML, otherwise qemu + if not args.runner: + if not args.kernel: + raise Exception("Please specify --runner/--kernel") + + if os.access(args.kernel, os.X_OK): + args.runner = 'uml' + else: + args.runner = 'qemu' + + if args.runner == 'uml': + return UmlRunner(args) + elif args.runner == 'qemu': + return QemuRunner(args) + else: + raise Exception("Unknown runner %s" % args.runner) + +class RunnerAbstract: + cmdline = [] + env = None + name = "unnamed" + + def __init__(self, args): + self.args = args + + def start(self): + print("Starting %s" % self.name) + os.execlpe(self.cmdline[0], *self.cmdline, self.env) + + def prepare_environment(self): + path = os.environ['PATH'] + os.environ['PATH'] = '%s/src' % self.args.testhome + os.environ['PATH'] += ':%s/tools' % self.args.testhome + os.environ['PATH'] += ':%s/client' % self.args.testhome + os.environ['PATH'] += ':%s/monitor' % self.args.testhome + os.environ['PATH'] += ':%s/wired' % self.args.testhome + os.environ['PATH'] += ':' + path + + sys.path.append(self.args.testhome + '/autotests/util') + + if not os.path.exists('/tmp/iwd'): + os.mkdir('/tmp/iwd') + + # + # This prevents any print() calls in this script from printing unless + # --debug is passed. For an 'always print' option use dbg() + # + if not self.args.dbg: + sys.stdout = open(os.devnull, 'w') + + # Copy autotests/misc/{certs,secrets,phonesim} so any test can refer to them + if os.path.exists('/tmp/certs'): + rmtree('/tmp/certs') + + if os.path.exists('/tmp/secrets'): + rmtree('/tmp/secrets') + + copytree(self.args.testhome + '/autotests/misc/certs', '/tmp/certs') + copytree(self.args.testhome + '/autotests/misc/secrets', '/tmp/secrets') + copy(self.args.testhome + '/autotests/misc/phonesim/phonesim.conf', '/tmp') + + # Clear out any log files from other test runs + if self.args.log: + for f in [os.path.join(self.args.log, file) for file in os.listdir(self.args.log)]: + print("removing %s" % f) + + if os.path.isdir(f): + rmtree(f) + else: + os.remove(f) + + fcntl.ioctl(STDIN_FILENO, TIOCSTTY, 1) + + def cleanup_environment(self): + rmtree('/tmp/iwd') + rmtree('/tmp/certs') + rmtree('/tmp/secrets') + os.remove('/tmp/phonesim.conf') + + os.sync() + + # For QEMU/UML runners + def _prepare_mounts(self, extra=[]): + for entry in mounts_common + extra: + try: + os.lstat(entry.target) + except: + os.mkdir(entry.target, 755) + + mount(entry.source, entry.target, entry.fstype, entry.flags, + entry.options) + + for entry in dev_table: + os.symlink(entry.target, entry.linkpath) + + os.setsid() + + # For QEMU/UML --log, --monitor, --result + def _prepare_outfiles(self): + gid = None + append_gid_uid = False + + if os.environ.get('SUDO_GID', None): + uid = int(os.environ['SUDO_UID']) + gid = int(os.environ['SUDO_GID']) + + if self.args.log: + if os.getuid() != 0: + print("--log can only be used as root user") + quit() + + append_gid_uid = True + + if not os.path.exists(self.args.log): + os.mkdir(self.args.log) + + if gid: + os.chown(self.args.log, uid, gid) + + if self.args.monitor: + if os.getuid() != 0: + print("--monitor can only be used as root user") + quit() + + append_gid_uid = True + + self.args.monitor_parent = os.path.abspath( + os.path.join(self.args.monitor, os.pardir)) + + if self.args.result: + if os.getuid() != 0: + print("--result can only be used as root user") + quit() + + append_gid_uid = True + + self.args.result_parent = os.path.abspath( + os.path.join(self.args.result, os.pardir)) + + if append_gid_uid: + self.args.SUDO_UID = uid + self.args.SUDO_GID = gid + + def stop(self): + exit() + +class QemuRunner(RunnerAbstract): + name = "Qemu Runner" + + def __init__(self, args): + def mount_options(id): + return 'mount_tag=%s,security_model=passthrough,id=%s' % (id, id) + + usb_adapters = None + pci_adapters = None + + super().__init__(args) + + if len(sys.argv) <= 1: + return + + if not which('qemu-system-x86_64'): + raise Exception('Cannot locate qemu binary') + + if not args.kernel or not os.path.exists(args.kernel): + raise Exception('Cannot locate kernel image %s' % args.kernel) + + self._prepare_outfiles() + + if args.hw: + hw_conf = ConfigParser() + hw_conf.read(args.hw) + + if hw_conf.has_section('USBAdapters'): + # The actual key name of the adapter + # doesn't matter since all we need is the + # bus/address. This gets named by the kernel + # anyways once in the VM. + usb_adapters = [v for v in hw_conf['USBAdapters'].values()] + + if hw_conf.has_section('PCIAdapters'): + pci_adapters = [v for v in hw_conf['PCIAdapters'].values()] + + kern_log = "ignore_loglevel" if "kernel" in args.verbose else "quiet" + + qemu_cmdline = [ + 'qemu-system-x86_64', + '-machine', 'type=q35,accel=kvm:tcg', + '-nodefaults', '-no-user-config', '-monitor', 'none', + '-display', 'none', '-m', '256M', '-nographic', '-vga', + 'none', '-no-acpi', '-no-hpet', + '-no-reboot', '-fsdev', + 'local,id=fsdev-root,path=/,readonly=on,security_model=none,multidevs=remap', + '-device', + 'virtio-9p-pci,fsdev=fsdev-root,mount_tag=/dev/root', + '-chardev', 'stdio,id=chardev-serial0,signal=off', + '-device', 'pci-serial,chardev=chardev-serial0', + '-device', 'virtio-rng-pci', + '-kernel', args.kernel, + '-smp', '2', + '-append', + 'console=ttyS0,115200n8 earlyprintk=serial \ + rootfstype=9p root=/dev/root \ + rootflags=trans=virtio \ + acpi=off pci=noacpi %s ro \ + mac80211_hwsim.radios=0 init=%s %s' % + (kern_log, args.start, args.to_cmd()), + ] + + # Add two ethernet devices for testing EAD + qemu_cmdline.extend([ + '-net', 'nic,model=virtio', + '-net', 'nic,model=virtio', + '-net', 'user' + ]) + + if usb_adapters: + for bus, addr in [s.split(',') for s in usb_adapters]: + qemu_cmdline.extend(['-usb', + '-device', + 'usb-host,hostbus=%s,hostaddr=%s' % \ + (bus, addr)]) + if pci_adapters: + qemu_cmdline.extend(['-enable-kvm']) + for addr in pci_adapters: + qemu_cmdline.extend(['-device', 'vfio-pci,host=%s' % addr]) + + if args.log: + # + # Creates a virtfs device that can be mounted. This mount + # will point back to the provided log directory and is + # writable unlike the rest of the mounted file system. + # + qemu_cmdline.extend([ + '-virtfs', + 'local,path=%s,%s' % (args.log, + mount_options('logdir')) + ]) + + if args.monitor: + qemu_cmdline.extend([ + '-virtfs', + 'local,path=%s,%s' % (self.args.monitor_parent, + mount_options('mondir')) + ]) + + if args.result: + qemu_cmdline.extend([ + '-virtfs', + 'local,path=%s,%s' % (self.args.result_parent, + mount_options('resultdir')) + ]) + + + self.cmdline = qemu_cmdline + + def prepare_environment(self): + mounts = [ MountInfo('debugfs', 'debugfs', '/sys/kernel/debug', '', 0) ] + + if self.args.log: + mounts.append(MountInfo('9p', 'logdir', self.args.log, + 'trans=virtio,version=9p2000.L,msize=10240', 0)) + + if self.args.monitor: + mounts.append(MountInfo('9p', 'mondir', self.args.monitor_parent, + 'trans=virtio,version=9p2000.L,msize=10240', 0)) + + if self.args.result: + mounts.append(MountInfo('9p', 'resultdir', self.args.result_parent, + 'trans=virtio,version=9p2000.L,msize=10240', 0)) + + self._prepare_mounts(extra=mounts) + + super().prepare_environment() + + def stop(self): + RB_AUTOBOOT = 0x01234567 + # + # Killing init() results in a kernel panic. For QEMU a graceful + # exit is achieved with RB_AUTOBOOT + # + libc.reboot(RB_AUTOBOOT) + +class UmlRunner(RunnerAbstract): + name = "UML Runner" + + def __init__(self, args): + super().__init__(args) + + if len(sys.argv) <= 1: + return + + if not which(args.kernel): + raise Exception('Cannot locate UML binary %s' % args.kernel) + + self._prepare_outfiles() + + kern_log = "ignore_loglevel" if "kernel" in args.verbose else "quiet" + + cmd = [args.kernel, 'rootfstype=hostfs', 'ro', 'mem=256M', 'mac80211_hwsim.radios=0', + 'time-travel=inf-cpu', 'eth0=mcast', 'eth1=mcast', + '%s '% kern_log, 'init=%s' % args.start] + cmd.extend(args.to_cmd().split(' ')) + + self.cmdline = cmd + + def prepare_environment(self): + mounts = [] + + if self.args.log: + mounts.append(MountInfo('hostfs', 'hostfs', self.args.log, + self.args.log, 0)) + + if self.args.monitor: + mounts.append(MountInfo('hostfs', 'hostfs', self.args.monitor_parent, + self.args.monitor_parent, 0)) + + if self.args.result: + mounts.append(MountInfo('hostfs', 'hostfs', self.args.result_parent, + self.args.result_parent, 0)) + + self._prepare_mounts(extra=mounts) + + super().prepare_environment() + + def stop(self): + RB_POWER_OFF = 0x4321fedc + # + # Killing init() results in a kernel panic. For UML a graceful + # exit is achieved with RB_POWER_OFF + # + libc.reboot(RB_POWER_OFF) diff --git a/tools/test-runner b/tools/test-runner @@ -1,1887 +1,5 @@ #!/usr/bin/python3 -import argparse -import os -import shutil -import ctypes -import fcntl -import shlex -import sys -import subprocess -import atexit -import time -import unittest -import importlib -import signal -from unittest.result import TestResult -import pyroute2 -import multiprocessing -import re -import traceback +from runner import Runner -from configparser import ConfigParser -from prettytable import PrettyTable -from termcolor import colored -from glob import glob -from collections import namedtuple -from time import sleep -import dbus.mainloop.glib -from gi.repository import GLib -from weakref import WeakValueDictionary - -libc = ctypes.cdll['libc.so.6'] -libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, \ - ctypes.c_ulong, ctypes.c_char_p) - -# Using ctypes to load the libc library is somewhat low level. Because of this -# we need to define our own flags/options for use with mounting. -MS_NOSUID = 2 -MS_NODEV = 4 -MS_NOEXEC = 8 -MS_STRICTATIME = 1 << 24 -STDIN_FILENO = 0 -TIOCSTTY = 0x540E - -config = None -intf_id = 0 - -TEST_MAX_TIMEOUT = 240 - -dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) - -def dbg(*s, **kwargs): - ''' - Allows prints if stdout has been re-directed - ''' - print(*s, **kwargs, file=sys.__stdout__) - -def exit_vm(): - if config: - for p in Process.get_all(): - print("Process %s still running!" % p.args[0]) - p.kill() - - if config.ctx and config.ctx.results: - print_results(config.ctx.results) - - os.sync() - - RB_AUTOBOOT = 0x01234567 - # - # Calling 'reboot' or 'shutdown' from a shell (e.g. os.system('reboot')) - # is not the same the POSIX reboot() and will cause a kernel panic since - # we are the init process. The libc.reboot() allows the VM to exit - # gracefully. - # - libc.reboot(RB_AUTOBOOT) - -def path_exists(path): - ''' - Searches PATH as well as absolute paths. - ''' - if shutil.which(path): - return True - try: - os.stat(path) - except: - return False - return True - -def find_binary(list): - ''' - Returns a binary from 'list' if its found in PATH or on a - valid absolute path. - ''' - for path in list: - if path_exists(path): - return path - return None - -def mount(source, target, fs, flags, options=''): - ''' - Python wrapper for libc mount() - ''' - ret = libc.mount(source.encode(), target.encode(), fs.encode(), flags, - options.encode()) - if ret < 0: - errno = ctypes.get_errno() - raise Exception("Could not mount %s (%d)" % (target, errno)) - -MountInfo = namedtuple('MountInfo', 'fstype target options flags') - -mount_table = [ - MountInfo('sysfs', '/sys', '', MS_NOSUID|MS_NOEXEC|MS_NODEV), - MountInfo('proc', '/proc', '', MS_NOSUID|MS_NOEXEC|MS_NODEV), - MountInfo('devpts', '/dev/pts', 'mode=0620', MS_NOSUID|MS_NOEXEC), - MountInfo('tmpfs', '/dev/shm', 'mode=1777', MS_NOSUID|MS_NODEV|MS_STRICTATIME), - MountInfo('tmpfs', '/run', 'mode=0755', MS_NOSUID|MS_NODEV|MS_STRICTATIME), - MountInfo('tmpfs', '/tmp', '', 0), - MountInfo('tmpfs', '/usr/share/dbus-1', 'mode=0755', MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME), - MountInfo('debugfs', '/sys/kernel/debug', '', 0) -] - -DevInfo = namedtuple('DevInfo', 'target linkpath') - -dev_table = [ - DevInfo('/proc/self/fd', '/dev/fd'), - DevInfo('/proc/self/fd/0', '/dev/stdin'), - DevInfo('/proc/self/fd/1', '/dev/stdout'), - DevInfo('/proc/self/fd/2', '/dev/stderr') -] - -# Partial DBus config. The remainder (<listen>) will be filled in for each -# namespace that is created so each individual dbus-daemon has its own socket -# and address. -dbus_config = ''' -<!DOCTYPE busconfig PUBLIC \ -"-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" \ -"http://www.freedesktop.org/standards/dbus/1.0/\ -busconfig.dtd\"> -<busconfig> -<type>system</type> -<limit name=\"reply_timeout\">2147483647</limit> -<auth>ANONYMOUS</auth> -<allow_anonymous/> -<policy context=\"default\"> -<allow user=\"*\"/> -<allow own=\"*\"/> -<allow send_type=\"method_call\"/> -<allow send_type=\"signal\"/> -<allow send_type=\"method_return\"/> -<allow send_type=\"error\"/> -<allow receive_type=\"method_call\"/> -<allow receive_type=\"signal\"/> -<allow receive_type=\"method_return\"/> -<allow receive_type=\"error\"/> -<allow send_destination=\"*\" eavesdrop=\"true\"/> -<allow eavesdrop=\"true\"/> -</policy> -''' - -class Process(subprocess.Popen): - processes = WeakValueDictionary() - ctx = None - - def __new__(cls, *args, **kwargs): - obj = super().__new__(cls) - cls.processes[id(obj)] = obj - return obj - - def __init__(self, args, namespace=None, outfile=None, env=None, check=False, cleanup=None): - self.write_fds = [] - self.io_watch = None - self.cleanup = cleanup - self.verbose = False - self.out = '' - self.hup = False - self.killed = False - self.namespace = namespace - - if not self.ctx: - global config - self.ctx = config.ctx - - if self.ctx.is_verbose(args[0], log=False): - self.verbose = True - - if namespace: - args = ['ip', 'netns', 'exec', namespace] + args - - if outfile: - # outfile is only used by iwmon, in which case we don't want - # to append to an existing file. - self._append_outfile(outfile, append=False) - - if self.ctx.args.log: - logfile = '%s/%s/%s' % (self.ctx.args.log, - os.path.basename(os.getcwd()), - args[0]) - self._append_outfile(logfile) - - super().__init__(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - env=env, cwd=os.getcwd()) - - # Set as non-blocking so read() in the IO callback doesn't block forever - fl = fcntl.fcntl(self.stdout, fcntl.F_GETFL) - fcntl.fcntl(self.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) - - self.io_watch = GLib.io_add_watch(self.stdout, GLib.IO_IN | - GLib.IO_HUP | GLib.IO_ERR, self.process_io) - - print("Starting process {}".format(self.args)) - - if check: - self.wait(10) - self.killed = True - if self.returncode != 0: - raise subprocess.CalledProcessError(returncode=self.returncode, - cmd=args) - - @classmethod - def get_all(cls): - return cls.processes.values() - - @classmethod - def kill_all(cls): - for p in cls.processes.values(): - p.kill() - - @staticmethod - def _write_io(instance, data, stdout=True): - for f in instance.write_fds: - f.write(data) - - # Write out a separator so multiple process calls per - # test are easer to read. - if instance.hup: - f.write("Terminated: {}\n\n".format(instance.args)) - - f.flush() - - if instance.verbose and stdout: - sys.__stdout__.write(data) - sys.__stdout__.flush() - - @classmethod - def write_separators(cls, sep): - for proc in cls.processes.values(): - if proc.killed: - continue - - cls._write_io(proc, sep, stdout=False) - - def process_io(self, source, condition): - if condition & GLib.IO_HUP: - self.hup = True - - data = source.read() - - if not data: - return True - - data = data.decode('utf-8') - - # Save data away in case the caller needs it (e.g. list_sta) - self.out += data - - self._write_io(self, data) - - return True - - def _append_outfile(self, file, append=True): - gid = int(self.ctx.args.log_gid) - uid = int(self.ctx.args.log_uid) - dir = os.path.dirname(file) - - if not path_exists(dir): - os.mkdir(dir) - os.chown(dir, uid, gid) - - file = os.path.join(dir,file) - - # If the out file exists, append. Useful for processes like - # hostapd_cli where it is called multiple times independently. - if os.path.isfile(file) and append: - mode = 'a' - else: - mode = 'w' - - try: - f = open(os.path.join(dir, file), mode) - except Exception as e: - traceback.print_exc() - exit(0) - - os.fchown(f.fileno(), uid, gid) - - self.write_fds.append(f) - - def wait_for_socket(self, socket, wait): - Namespace.non_block_wait(os.path.exists, wait, socket) - - # Wait for both process termination and HUP signal - def __wait(self, timeout): - try: - super().wait(timeout) - if not self.hup: - return False - - return True - except: - return False - - # Override wait() so it can do so non-blocking - def wait(self, timeout=10): - Namespace.non_block_wait(self.__wait, timeout, 1) - self._cleanup() - - def _cleanup(self): - if self.cleanup: - self.cleanup() - - self.write_fds = [] - - if self.io_watch: - GLib.source_remove(self.io_watch) - self.io_watch = None - - self.cleanup = None - self.killed = True - - # Override kill() - def kill(self, force=False): - if self.killed: - return - - print("Killing process {}".format(self.args)) - - if force: - super().kill() - else: - self.terminate() - - try: - self.wait(timeout=15) - except: - dbg("Process %s did not complete in 15 seconds!" % self.name) - super().kill() - - self._cleanup() - - def __str__(self): - return str(self.args) + '\n' - -class Interface: - def __init__(self, name, config): - self.name = name - self.ctrl_interface = '/var/run/hostapd/' + name - self.config = config - - def __del__(self): - Process(['iw', 'dev', self.name, 'del']).wait() - - def set_interface_state(self, state): - Process(['ip', 'link', 'set', self.name, state]).wait() - -class Radio: - def __init__(self, name): - self.name = name - # hostapd will reset this if this radio is used by it - self.use = 'iwd' - self.interface = None - - def __del__(self): - print("Removing radio %s" % self.name) - self.interface = None - - def create_interface(self, config, use): - global intf_id - - ifname = 'wln%s' % intf_id - - intf_id += 1 - - self.interface = Interface(ifname, config) - self.use = use - - Process(['iw', 'phy', self.name, 'interface', 'add', ifname, - 'type', 'managed']).wait() - - return self.interface - - def __str__(self): - ret = self.name + ':\n' - ret += '\tUsed By: %s ' % self.use - if self.interface: - ret += '(%s)' % self.interface.name - - ret += '\n' - - return ret - -class VirtualRadio(Radio): - ''' - A subclass of 'Radio' specific to mac80211_hwsim radios. - - TODO: Using D-Bus to create and destroy radios is more desireable - than the command line. - ''' - - def __init__(self, name, cfg=None): - global config - - self.disable_cipher = None - self.disable_iftype = None - - self.hwsim = config.hwsim.Hwsim() - - if cfg: - self.disable_iftype = cfg.get('iftype_disable', None) - self.disable_cipher = cfg.get('cipher_disable', None) - - self._radio = self.hwsim.radios.create(name, p2p_device=True, - iftype_disable=self.disable_iftype, - cipher_disable=self.disable_cipher) - - super().__init__(self._radio.name) - - def __del__(self): - super().__del__() - - # If the radio was moved into a namespace this will fail - try: - self._radio.remove() - except: - pass - - self._radio = None - - def __str__(self): - ret = super().__str__() - - if self.disable_iftype: - ret += '\tDisabled interface types: %s\n' % self.disable_iftype - - if self.disable_cipher: - ret += '\tDisabled ciphers: %s\n' % self.disable_cipher - - ret += '\tPath: %s' % self._radio.path - - ret += '\n' - - return ret - -class HostapdInstance: - ''' - A single instance of hostapd. In reality all hostapd instances - are started as a single process. This class just makes things - convenient for communicating with one of the hostapd APs. - ''' - def __init__(self, config, radio): - self.radio = radio - self.config = config - self.cli = None - - self.intf = radio.create_interface(self.config, 'hostapd') - self.intf.set_interface_state('up') - - def __del__(self): - print("Removing HostapdInstance %s" % self.config) - self.intf.set_interface_state('down') - self.radio = None - self.intf = None - - def __str__(self): - ret = 'Hostapd (%s)\n' % self.intf.name - ret += '\tConfig: %s\n' % self.config - - return ret - -class Hostapd: - ''' - A set of running hostapd instances. This is really just a single - process since hostapd can be started with multiple config files. - ''' - def __init__(self, ctx, radios, configs, radius): - self.ctx = ctx - - if len(configs) != len(radios): - raise Exception("Config (%d) and radio (%d) list length not equal" % \ - (len(configs), len(radios))) - - print("Initializing hostapd instances") - - Process(['ip', 'link', 'set', 'eth0', 'up']).wait() - Process(['ip', 'link', 'set', 'eth1', 'up']).wait() - - self.global_ctrl_iface = '/var/run/hostapd/ctrl' - - self.instances = [HostapdInstance(c, r) for c, r in zip(configs, radios)] - - ifaces = [rad.interface.name for rad in radios] - ifaces = ','.join(ifaces) - - args = ['hostapd', '-g', self.global_ctrl_iface] - - if ifaces: - args.extend(['-i', ifaces]) - - # - # Config files should already be present in /tmp. This appends - # ctrl_interface and does any variable replacement. Currently - # this is just any $ifaceN occurrences. - # - for c in configs: - full_path = '/tmp/%s' % c - args.append(full_path) - - self._rewrite_config(full_path) - - if radius: - args.append(radius) - - if ctx.is_verbose('hostapd'): - args.append('-d') - - self.process = Process(args) - - self.process.wait_for_socket(self.global_ctrl_iface, 30) - - for hapd in self.instances: - self.process.wait_for_socket(hapd.intf.ctrl_interface, 30) - - def attach_cli(self): - global config - - for hapd in self.instances: - hapd.cli = config.hostapd.HostapdCLI(config=hapd.config) - - def _rewrite_config(self, config): - ''' - Replaces any $ifaceN values with the correct interface - names as well as appends the ctrl_interface path to - the config file. - ''' - with open(config, 'r+') as f: - data = f.read() - to_replace = [] - for match in re.finditer(r'\$iface[0-9]+', data): - tag = data[match.start():match.end()] - idx = tag.split('iface')[1] - - to_replace.append((tag, self.instances[int(idx)].intf.name)) - - for r in to_replace: - data = data.replace(r[0], r[1], 1) - - data += '\nctrl_interface=/var/run/hostapd\n' - - f.write(data) - - def __getitem__(self, config): - if not config: - return self.instances[0] - - for hapd in self.instances: - if hapd.config == config: - return hapd - - return None - - def __del__(self): - print("Removing Hostapd") - try: - os.remove(self.global_ctrl_iface) - except: - print("Failed to remove %s" % self.global_ctrl_iface) - - self.instances = None - - # Hostapd may have already been stopped - if self.process: - self.ctx.stop_process(self.process) - - self.ctx = None - - # Hostapd creates simdb sockets for EAP-SIM/AKA tests but does not - # clean them up. - for f in glob("/tmp/eap_sim_db*"): - os.remove(f) - -dbus_count = 0 - -class Namespace: - def __init__(self, args, name, radios): - self.dbus_address = None - self.name = name - self.radios = radios - self.args = args - - Process(['ip', 'netns', 'add', name]).wait() - for r in radios: - Process(['iw', 'phy', r.name, 'set', 'netns', 'name', name]).wait() - - self.start_dbus() - - def reset(self): - self._bus = None - - for r in self.radios: - r._radio = None - - self.radios = [] - - Process.kill_all() - - def __del__(self): - print("Removing namespace %s" % self.name) - - Process(['ip', 'netns', 'del', self.name]).wait() - - def get_bus(self): - return self._bus - - def start_process(self, args, env=None, **kwargs): - if not env: - env = os.environ.copy() - - if hasattr(self, "dbus_address"): - # In case this process needs DBus... - env['DBUS_SYSTEM_BUS_ADDRESS'] = self.dbus_address - - return Process(args, namespace=self.name, env=env, **kwargs) - - def stop_process(self, p, force=False): - p.kill(force) - - def is_process_running(self, process): - for p in Process.get_all(): - if p.namespace == self.name and p.args[0] == process: - return True - return False - - def _cleanup_dbus(self): - try: - os.remove(self.dbus_address.split('=')[1]) - except: - pass - - os.remove(self.dbus_cfg) - - def start_dbus(self): - global dbus_count - - self.dbus_address = 'unix:path=/tmp/dbus%d' % dbus_count - self.dbus_cfg = '/tmp/dbus%d.conf' % dbus_count - dbus_count += 1 - - with open(self.dbus_cfg, 'w+') as f: - f.write(dbus_config) - f.write('<listen>%s</listen>\n' % self.dbus_address) - f.write('</busconfig>\n') - - p = self.start_process(['dbus-daemon', '--config-file=%s' % self.dbus_cfg], - cleanup=self._cleanup_dbus) - - p.wait_for_socket(self.dbus_address.split('=')[1], 5) - - self._bus = dbus.bus.BusConnection(address_or_type=self.dbus_address) - - def start_iwd(self, config_dir = '/tmp', storage_dir = '/tmp/iwd'): - args = [] - iwd_radios = ','.join([r.name for r in self.radios if r.use == 'iwd']) - - if self.args.valgrind: - args.extend(['valgrind', '--leak-check=full', '--track-origins=yes', - '--show-leak-kinds=all', - '--log-file=/tmp/valgrind.log.%p']) - - args.extend(['iwd', '-E']) - - if iwd_radios != '': - args.extend(['-p', iwd_radios]) - - if self.is_verbose(args[0]): - args.append('-d') - - env = os.environ.copy() - - env['CONFIGURATION_DIRECTORY'] = config_dir - env['STATE_DIRECTORY'] = storage_dir - - if self.is_verbose('iwd-dhcp'): - env['IWD_DHCP_DEBUG'] = '1' - - if self.is_verbose('iwd-tls'): - env['IWD_TLS_DEBUG'] = '1' - - if self.is_verbose('iwd-acd'): - env['IWD_ACD_DEBUG'] = '1' - - return self.start_process(args, env=env) - - def is_verbose(self, process, log=True): - process = os.path.basename(process) - - if self.args is None: - return False - - # every process is verbose when logging is enabled - if log and self.args.log: - return True - - if process in self.args.verbose: - return True - - # Special case here to enable verbose output with valgrind running - if process == 'valgrind' and 'iwd' in self.args.verbose: - return True - - # Handle any glob matches - for item in self.args.verbose: - if process in glob(item): - return True - - return False - - @staticmethod - def non_block_wait(func, timeout, *args, exception=True): - ''' - Convenience function for waiting in a non blocking - manor using GLibs context iteration i.e. does not block - the main loop while waiting. - - 'func' will be called at least once and repeatedly until - either it returns success, throws an exception, or the - 'timeout' expires. - - 'timeout' is the ultimate timeout in seconds - - '*args' will be passed to 'func' - - If 'exception' is an Exception type it will be raised. - If 'exception' is True a generic TimeoutError will be raised. - Any other value will not result in an exception. - ''' - # Simple class for signaling the wait timeout - class Bool: - def __init__(self, value): - self.value = value - - def wait_timeout_cb(done): - done.value = True - return False - - mainloop = GLib.MainLoop() - done = Bool(False) - - timeout = GLib.timeout_add_seconds(timeout, wait_timeout_cb, done) - context = mainloop.get_context() - - while True: - context.iteration(may_block=False) - - try: - ret = func(*args) - if ret: - if not done.value: - GLib.source_remove(timeout) - return ret - except Exception as e: - if not done.value: - GLib.source_remove(timeout) - raise e - - sleep(0.1) - - if done.value == True: - if isinstance(exception, Exception): - raise exception - elif type(exception) == bool and exception: - raise TimeoutError("Timeout on non_block_wait") - else: - return - - def __str__(self): - ret = 'Namespace: %s\n' % self.name - ret += 'Processes:\n' - for p in Process.get_all(): - ret += '\t%s' % str(p) - - ret += 'Radios:\n' - if len(self.radios) > 0: - for r in self.radios: - ret += '\t%s\n' % str(r) - else: - ret += '\tNo Radios\n' - - ret += 'DBus Address: %s\n' % self.dbus_address - ret += '===================================================\n\n' - - return ret - -class TestContext(Namespace): - ''' - Contains all information for a given set of tests being run - such as processes, radios, interfaces and test results. - ''' - def __init__(self, args): - self.name = None - self.args = args - self.hw_config = None - self.hostapd = None - self.wpas_interfaces = None - self.cur_radio_id = 0 - self.cur_iface_id = 0 - self.radios = [] - self.loopback_started = False - self.results = {} - self.mainloop = GLib.MainLoop() - self.namespaces = [] - - def start_dbus_monitor(self): - if not self.is_verbose('dbus-monitor'): - return - - self.start_process(['dbus-monitor', '--address', self.dbus_address]) - - def start_haveged(self): - self.start_process(['haveged', '-F']) - - def create_radios(self): - setup = self.hw_config['SETUP'] - nradios = int(setup['num_radios']) - args = ['hwsim'] - - if self.hw_config['SETUP'].get('hwsim_medium', 'no') in ['no', '0', 'false']: - # register hwsim as medium - args.extend(['--no-register']) - - self.start_process(args) - self.non_block_wait(self._bus.name_has_owner, 20, 'net.connman.hwsim', - exception=TimeoutError('net.connman.hwsim did not appear')) - - for i in range(nradios): - name = 'rad%u' % i - - # Get any [radX] sections. These are for configuring - # any special radios. This no longer requires a - # radio_conf list, we just assume radios start rad0 - # and increment. - rad_config = None - if self.hw_config.has_section(name): - rad_config = self.hw_config[name] - - self.radios.append(VirtualRadio(name, rad_config)) - self.cur_radio_id += 1 - - def discover_radios(self): - phys = [] - - try: - iw = pyroute2.iwutil.IW() - except: - iw = pyroute2.IW() - - attrs = [phy['attrs'] for phy in iw.list_wiphy()] - - for attr in attrs: - for key, value in attr: - if key == 'NL80211_ATTR_WIPHY_NAME': - if value not in phys: - phys.append(value) - break - - print('Discovered radios: %s' % str(phys)) - self.radios = [Radio(name) for name in phys] - - def start_radios(self): - reg_domain = self.hw_config['SETUP'].get('reg_domain', None) - if reg_domain: - Process(['iw', 'reg', 'set', reg_domain]).wait() - - if self.args.hw: - self.discover_radios() - else: - self.create_radios() - - def start_hostapd(self): - if not 'HOSTAPD' in self.hw_config: - return - - settings = self.hw_config['HOSTAPD'] - - if self.args.hw: - # Just grab the first N radios. It gets rather - # complicated trying to map radX radios specified in - # hw.conf so any passed through physical adapters are - # just given to hostapd/IWD as they appear during - # discovery. - # - # TODO: It may be desireable to map PCI/USB adapters to - # specific radX radios specified in the config but - # there are really 2 separate use cases here. - # 1. You want to test a *specific* radio with IWD - # or hostapd. For this you would want radX - # to map to a specific radio - # 2. You have many adapters in use to run multiple - # tests. In this case you would not care what - # was using each radio, just that there was - # enough to run all tests. - nradios = 0 - for k, _ in settings.items(): - if k == 'radius_server': - continue - nradios += 1 - - hapd_radios = self.radios[:nradios] - - else: - hapd_radios = [rad for rad in self.radios if rad.name in settings] - - hapd_configs = [conf for rad, conf in settings.items() if rad != 'radius_server'] - - radius_config = settings.get('radius_server', None) - - self.hostapd = Hostapd(self, hapd_radios, hapd_configs, radius_config) - self.hostapd.attach_cli() - - def get_frequencies(self): - frequencies = [] - - for hapd in self.hostapd.instances: - frequencies.append(hapd.cli.frequency) - - return frequencies - - def start_wpas_interfaces(self): - - if 'WPA_SUPPLICANT' not in self.hw_config: - return - - settings = self.hw_config['WPA_SUPPLICANT'] - - if self.args.hw: - nradios = len(settings.items()) - - wpas_radios = self.radios[:nradios] - self.wpas_interfaces = [] - - # - # Physical radios most likely will use a different name - # than 'rad#' but the config file is referenced by these - # 'rad#' names. Iterate through both the settings and - # physical radios to create interfaces associated with - # each config file. - # - for vrad, hwrad in zip(settings.items(), wpas_radios): - self.wpas_interfaces.append(hwrad.create_interface(vrad[1], 'wpas')) - - else: - wpas_radios = [rad for rad in self.radios if rad.name in settings] - self.wpas_interfaces = [rad.create_interface(settings[rad.name], 'wpas') \ - for rad in wpas_radios] - - def start_ofono(self): - sim_keys = self.hw_config['SETUP'].get('sim_keys', None) - if not sim_keys: - print("Ofono not requred") - return - elif sim_keys != 'ofono': - os.environ['IWD_SIM_KEYS'] = sim_keys - return - - if not find_binary(['ofonod']) or not find_binary(['phonesim']): - print("Ofono or Phonesim not found, skipping test") - return - - Process(['ip', 'link', 'set', 'lo', 'up']).wait() - - os.environ['OFONO_PHONESIM_CONFIG'] = '/tmp/phonesim.conf' - - phonesim_args = ['phonesim', '-p', '12345', '/usr/share/phonesim/default.xml'] - - self.start_process(phonesim_args) - - # - # TODO: - # Is there something to wait for? Without this phonesim rejects - # connections on all but the fist test. - # - time.sleep(3) - - ofono_args = ['ofonod', '-n', '--plugin=atmodem,phonesim'] - if self.is_verbose('ofonod'): - ofono_args.append('-d') - - self.start_process(ofono_args) - - print("Ofono started") - - def create_namespaces(self): - if not self.hw_config.has_section('NameSpaces'): - return - - for key, value in self.hw_config.items('NameSpaces'): - radio_names = value.split(',') - # Gather up radio objects for this namespace - radios = [rad for rad in self.radios if rad.name in radio_names] - - # Remove radios from 'root' namespace - self.radios = list(set(self.radios) - set(radios)) - - self.namespaces.append(Namespace(self.args, key, radios)) - - def get_namespace(self, ns): - for n in self.namespaces: - if n.name == ns: - return n - - return None - - def stop_test_processes(self): - for n in self.namespaces: - n.reset() - - self.namespaces = [] - self.hostapd = None - self.wpas_interfaces = None - - self.reset() - - def __str__(self): - ret = 'Arguments:\n' - for arg in vars(self.args): - ret += '\t --%s %s\n' % (arg, str(getattr(self.args, arg))) - - ret += 'Hostapd:\n' - if self.hostapd: - for h in self.hostapd.instances: - ret += '\t%s\n' % str(h) - else: - ret += '\tNo Hostapd instances\n' - - ret += super().__str__() - - for n in self.namespaces: - ret += n.__str__() - - return ret - -def prepare_sandbox(): - print('Preparing sandbox') - - for entry in mount_table: - try: - os.lstat(entry.target) - except: - os.mkdir(entry.target, 755) - - mount(entry.fstype, entry.target, entry.fstype, entry.flags, - entry.options) - - for entry in dev_table: - os.symlink(entry.target, entry.linkpath) - - os.mkdir('/tmp/iwd') - - os.setsid() - - fcntl.ioctl(STDIN_FILENO, TIOCSTTY, 1) - -def build_unit_list(args): - ''' - Build list of unit tests based on passed arguments. This first - checks for literal names provided in the arguments, then if - no matches were found, checks for a glob match. - ''' - tests = [] - test_root = args.testhome + '/unit' - - for unit in args.unit_tests.split(','): - path = '%s/%s' % (test_root, unit) - if os.access(unit, os.X_OK): - tests.append(unit) - elif os.access(path, os.X_OK): - tests.append(path) - else: - # Full list or glob, first build up valid list of tests - matches = glob(path) - if matches == []: - raise Exception("Could not find test %s" % unit) - - matches = [exe for exe in matches if os.access(exe, os.X_OK)] - - tests.extend(matches) - - return sorted(tests) - -def build_test_list(args): - ''' - Build list of auto test directories based on passed arguments. - First check for absolute paths, then look in <iwd>/autotests, - then glob match. - ''' - tests = [] - test_root = args.testhome + '/autotests' - - # Run all tests - if not args.auto_tests: - # --shell with no tests implies 'shell' test - if args.shell: - return [test_root + '/shell'] - - # Get list of all autotests (committed in git) - tests = os.popen('git -C %s ls-files autotests/ | cut -f2 -d"/" \ - | grep "test*" | uniq' % args.testhome).read() \ - .strip().split('\n') - tests = [test_root + '/' + t for t in tests] - else: - print("Generating partial test list") - - full_list = sorted(os.listdir(test_root)) - - for t in args.auto_tests.split(','): - path = '%s/%s' % (test_root, t) - if t.endswith('+'): - t = t.split('+')[0] - i = full_list.index(t) - - tests = [test_root + '/' + x for x in full_list[i:] \ - if x.startswith('test')] - elif os.path.exists(t): - if t not in tests: - tests.append(t) - elif os.path.exists(path): - if path not in tests: - tests.append(path) - else: - matches = glob(path) - if matches == []: - raise Exception("Could not find test %s" % t) - - tests.extend(list(set(matches) - set(tests))) - - return sorted(tests) - -SimpleResult = namedtuple('SimpleResult', 'run failures errors skipped time') - -def start_test(ctx, subtests, rqueue): - ''' - Run an individual test. 'subtests' are parsed prior to calling - but these effectively make up a single test. 'rqueue' is the - results queue which is required since this is using - multiprocessing. - ''' - run = 0 - errors = 0 - failures = 0 - skipped = 0 - - start = time.time() - # - # Iterate through each individual python test. - # - for s in subtests: - loader = unittest.TestLoader() - module = importlib.import_module(os.path.splitext(s)[0]) - subtest = loader.loadTestsFromModule(module) - - # The test suite is being (ab)used to get a bit more granularity - # with individual tests. The 'normal' way to use unittest is to - # just create a test suite and run them. The problem here is that - # test results are queued and printed at the very end so its - # difficult to know *where* a test failed (python gives a stack - # trace but printing the exception/failure immediately shows - # where in the debug logs something failed). Moreso if there are - # several test functions inside a single python file they run - # as a single test and it is difficult (again) to know where - # something failed. - - # Iterating through each python test file - for test in subtest: - limit_funcs = [] - - if ctx.args.sub_tests: - for i in ctx.args.sub_tests: - if len(i.split('.')) == 2: - limit_funcs.append(i.split('.')[1]) - - # Iterating through individual test functions inside a - # Test() class. Due to the nature of unittest we have - # to jump through some hoops to set up the test class - # only once by turning the enumeration into a list, then - # enumerating (again) to keep track of the index (just - # enumerating the test class doesn't allow len() because - # it is not a list). - tlist = list(enumerate(test)) - for index, t in enumerate(tlist): - # enumerate is returning a tuple, index 1 is our - # actual object. - t = t[1] - - func, file = str(t).split(' ') - # - # TODO: There may be a better way of doing this - # but strigifying the test class gives us a string: - # <function> (<file>.<class>) - # - file = file.strip('()').split('.')[0] + '.py' - - # Create an empty result here in case the test fails - result = TestResult() - - try: - skip = len(limit_funcs) > 0 and func not in limit_funcs - - # Set up class only on first test - if index == 0: - if not skip: - dbg("%s\n\t%s RUNNING" % (file, str(func)), end='') - t.setUpClass() - else: - if not skip: - dbg("\t%s RUNNING" % str(func), end='') - - sys.__stdout__.flush() - - Process.write_separators("\n====== %s:%s ======\n\n" % (file, func)) - - if not skip: - # Run test (setUp/tearDown run automatically) - result = t() - - # Tear down class only on last test - if index == len(tlist) - 1: - t.tearDownClass() - - if skip: - continue - except unittest.SkipTest as e: - result.skipped.append(t) - except Exception as e: - dbg('\n%s threw an uncaught exception:' % func) - traceback.print_exc(file=sys.__stdout__) - - run += result.testsRun - errors += len(result.errors) - failures += len(result.failures) - skipped += len(result.skipped) - - if len(result.skipped) > 0: - dbg(colored(" SKIPPED", "cyan")) - elif run == 0 or len(result.errors) > 0 or len(result.failures) > 0: - dbg(colored(" FAILED", "red")) - for e in result.errors: - dbg(e[1]) - for f in result.failures: - dbg(f[1]) - else: - dbg(colored(" PASSED", "green")) - - # Prevents future test modules with the same name (e.g. - # connection_test.py) from being loaded from the cache - sys.modules.pop(module.__name__) - - # - # The multiprocessing queue is picky with what objects it will serialize - # and send between processes. Because of this we put the important bits - # of the result into our own 'SimpleResult' tuple. - # - sresult = SimpleResult(run=run, failures=failures, errors=errors, - skipped=skipped, time=time.time() - start) - rqueue.put(sresult) - - # This may not be required since we are manually popping sys.modules - importlib.invalidate_caches() - -def pre_test(ctx, test, copied): - ''' - Copy test files, start processes, and any other pre test work. - ''' - os.chdir(test) - - dbg("\nStarting %s" % colored(os.path.basename(test), "white", attrs=['bold'])) - if not os.path.exists(test + '/hw.conf'): - raise Exception("No hw.conf found for %s" % test) - - ctx.hw_config = ConfigParser() - ctx.hw_config.read(test + '/hw.conf') - # - # We have two types of test files: tests and everything else. Rather - # than require each test to specify the files needing to be copied to - # /tmp (previously 'tmpfs_extra_stuff'), we just copy everything which - # isn't a test. There is really no reason not to do this as any file - # present in a test directory should be needed by the test. - # - # All files - files = os.listdir(test) - # Tests (starts or ends with 'test') - subtests = [f for f in files if f.startswith('test') or \ - os.path.splitext(f)[0].endswith('test')] - # Everything else (except .py files) - to_copy = [f for f in list(set(files) - set(subtests)) if not f.endswith('.py') \ - and f != '__pycache__'] - for f in to_copy: - if os.path.isdir(f): - shutil.copytree(f, '/tmp/' + f) - else: - shutil.copy(f, '/tmp') - copied.append(f) - - # Prune down any subtests if needed - if ctx.args.sub_tests: - ctx.args.sub_tests = ctx.args.sub_tests.split(',') - - to_run = [x.split('.')[0] for x in ctx.args.sub_tests] - pruned = [] - - for s in subtests: - no_ext = s - # Handle <file>.<test function> format - if '.' in s: - no_ext = s.split('.')[0] - - if no_ext in to_run: - pruned.append(no_ext + '.py') - - subtests = pruned - - ctx.start_dbus() - ctx.start_haveged() - ctx.start_dbus_monitor() - ctx.start_radios() - ctx.create_namespaces() - ctx.start_hostapd() - ctx.start_wpas_interfaces() - ctx.start_ofono() - - if ctx.args.log: - ctx.start_process(['iwmon', '--nowiphy']) - elif ctx.args.monitor: - ctx.start_process(['iwmon', '--nowiphy'], outfile=ctx.args.monitor) - - if ctx.hw_config.has_option('SETUP', 'start_iwd'): - start = ctx.hw_config.getboolean('SETUP', 'start_iwd') - else: - start = True - - if start: - ctx.start_iwd() - else: - print("Not starting IWD from test-runner") - - print(ctx) - - sys.path.insert(1, test) - - return sorted(subtests) - -def post_test(ctx, to_copy): - ''' - Remove copied files, and stop test processes. - ''' - try: - for f in to_copy: - if os.path.isdir('/tmp/' + f): - shutil.rmtree('/tmp/' + f) - else: - os.remove('/tmp/' + f) - - Process(['ip', 'link', 'set', 'lo', 'down']).wait() - except Exception as e: - print("Exception thrown in post_test") - finally: - ctx.stop_test_processes() - - if ctx.args.valgrind: - for f in os.listdir('/tmp'): - if f.startswith("valgrind.log."): - dbg(f) - with open('/tmp/' + f, 'r') as v: - dbg(v.read()) - dbg("\n") - os.remove('/tmp/' + f) - - # Special case for when logging is enabled - if os.path.isfile('/tmp/iwd-tls-debug-server-cert.pem'): - os.remove('/tmp/iwd-tls-debug-server-cert.pem') - - allowed = ['phonesim.conf', 'certs', 'secrets', 'iwd'] - for f in [f for f in os.listdir('/tmp') if f not in allowed]: - dbg("File %s was not cleaned up!" % f) - try: - os.remove('/tmp/' + f) - except: - pass - -def print_results(results): - table = PrettyTable(['Test', colored('Passed', 'green'), colored('Failed', 'red'), \ - colored('Skipped', 'cyan'), colored('Time', 'yellow')]) - - total_pass = 0 - total_fail = 0 - total_skip = 0 - total_time = 0 - - for test, result in results.items(): - - if result.time == TEST_MAX_TIMEOUT: - failed = "Timed out" - passed = "Timed out" - elif result.time == 0: - failed = "Exception" - passed = "Exception" - else: - failed = result.failures + result.errors - passed = result.run - failed - - total_pass += passed - total_fail += failed - total_skip += result.skipped - - total_time += result.time - - time = '%.2f' % result.time - - table.add_row([test, colored(passed, 'green'), colored(failed, 'red'), \ - colored(result.skipped, 'cyan'), colored(time, 'yellow')]) - - total_time = '%.2f' % total_time - - table.add_row(['Total', colored(total_pass, 'green'), colored(total_fail, 'red'), \ - colored(total_skip, 'cyan'), colored(total_time, 'yellow')]) - - dbg(table) - -def run_auto_tests(ctx, args): - tests = build_test_list(args) - - # Copy autotests/misc/{certs,secrets,phonesim} so any test can refer to them - shutil.copytree(args.testhome + '/autotests/misc/certs', '/tmp/certs') - shutil.copytree(args.testhome + '/autotests/misc/secrets', '/tmp/secrets') - shutil.copy(args.testhome + '/autotests/misc/phonesim/phonesim.conf', '/tmp') - - for test in tests: - copied = [] - try: - subtests = pre_test(ctx, test, copied) - - if args.shell: - # - # Shell really isn't meant to be used with multiple tests. If - # a set of tests was passed in just start out in the first. - # - os.chdir(tests[0]) - os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = ctx.dbus_address - os.system('/bin/bash') - exit() - - if len(subtests) < 1: - dbg("No tests to run") - exit() - - rqueue = multiprocessing.Queue() - p = multiprocessing.Process(target=start_test, args=(ctx, subtests, rqueue)) - p.start() - # Rather than time each subtest we just time the total but - # mutiply the default time by the number of tests being run. - p.join(TEST_MAX_TIMEOUT * len(subtests)) - - if p.is_alive(): - # Timeout - p.terminate() - - ctx.results[os.path.basename(test)] = SimpleResult(run=0, - failures=0, errors=0, - skipped=0, time=TEST_MAX_TIMEOUT) - else: - ctx.results[os.path.basename(test)] = rqueue.get() - - except Exception as ex: - dbg("%s threw an uncaught exception" % test) - traceback.print_exc(file=sys.__stdout__) - ctx.results[os.path.basename(test)] = SimpleResult(run=0, failures=0, - errors=0, skipped=0, time=0) - finally: - post_test(ctx, copied) - - shutil.rmtree('/tmp/iwd') - shutil.rmtree('/tmp/certs') - shutil.rmtree('/tmp/secrets') - os.remove('/tmp/phonesim.conf') - -def run_unit_tests(ctx, args): - os.chdir(args.testhome + '/unit') - units = build_unit_list(args) - - for u in units: - p = ctx.start_process([u]).wait() - if p.returncode != 0: - dbg("Unit test %s failed" % os.path.basename(u)) - else: - dbg("Unit test %s passed" % os.path.basename(u)) - -def run_tests(): - global config - - with open('/proc/cmdline', 'r') as f: - cmdline = f.read() - - start = cmdline.find('--testhome') - - options = shlex.split(cmdline[start:]) - - parser = argparse.ArgumentParser() - parser.add_argument('--testhome') - parser.add_argument('--auto_tests') - parser.add_argument('--unit_tests') - parser.add_argument('--verbose', default=[]) - parser.add_argument('--debug') - parser.add_argument('--path') - parser.add_argument('--valgrind') - parser.add_argument('--gdb') - parser.add_argument('--shell') - parser.add_argument('--log') - parser.add_argument('--log-gid') - parser.add_argument('--log-uid') - parser.add_argument('--hw') - parser.add_argument('--monitor') - parser.add_argument('--sub_tests') - - args = parser.parse_args(options) - - # - # This prevents any print() calls in this script from printing unless - # --debug is passed. For an 'always print' option use dbg() - # - if not args.debug: - sys.stdout = open(os.devnull, 'w') - - if args.verbose != []: - args.verbose = args.verbose.split(',') - - os.environ['PATH'] = '%s/src' % args.testhome - os.environ['PATH'] += ':%s/tools' % args.testhome - os.environ['PATH'] += ':%s/client' % args.testhome - os.environ['PATH'] += ':%s/monitor' % args.testhome - os.environ['PATH'] += ':%s/wired' % args.testhome - os.environ['PATH'] += ':' + args.path - - sys.path.append(args.testhome + '/autotests/util') - - # - # This allows all autotest utils (iwd/hostapd/etc) to access the - # TestContext. Any other module or script (in the same interpreter) can - # simply import config.ctx and access all live test information, - # start/stop processes, see active radios etc. - # - config = importlib.import_module('config') - config.ctx = TestContext(args) - - # Must import these after config so ctx gets set - config.hwsim = importlib.import_module('hwsim') - config.hostapd = importlib.import_module('hostapd') - - if args.log: - mount('logdir', args.log, '9p', 0, 'trans=virtio,version=9p2000.L,msize=10240') - # Clear out any log files from other test runs - for f in glob('%s/*' % args.log): - print("removing %s" % f) - - if os.path.isdir(f): - shutil.rmtree(f) - else: - os.remove(f) - - # Start writing out kernel log - config.ctx.start_process(["dmesg", '--follow']) - elif args.monitor: - parent = os.path.abspath(os.path.join(args.monitor, os.pardir)) - mount('mondir', parent, '9p', 0, 'trans=virtio,version=9p2000.L,msize=10240') - - if config.ctx.args.unit_tests is None: - run_auto_tests(config.ctx, args) - else: - run_unit_tests(config.ctx, args) - -class Main: - def __init__(self): - self.parser = argparse.ArgumentParser( - description='IWD Test Runner') - - self.parser.add_argument('--qemu', '-q', - metavar='<QEMU binary>', type=str, - help='QEMU binary to use', - dest='qemu', - default=None) - self.parser.add_argument('--kernel', '-k', metavar='<kernel>', - type=str, - help='Path to kernel image', - dest='kernel', - default=None) - self.parser.add_argument('--verbose', '-v', metavar='<list>', - type=str, - help='Comma separated list of applications', - dest='verbose', - default=[]) - self.parser.add_argument('--debug', '-d', - action='store_true', - help='Enable test-runner debugging', - dest='debug') - self.parser.add_argument('--shell', '-s', action='store_true', - help='Boot into shell', dest='shell') - self.parser.add_argument('--log', '-l', type=str, - help='Directory for log files') - self.parser.add_argument('--hw', '-w', type=str, nargs=1, - help='Use physical adapters for tests (passthrough)') - self.parser.add_argument('--monitor', '-m', type=str, - help='Enables iwmon output to file') - self.parser.add_argument('--sub-tests', '-S', metavar='<subtests>', - type=str, nargs=1, help='List of subtests to run', - default=None, dest='sub_tests') - - # Prevent --autotest/--unittest from being used together - auto_unit_group = self.parser.add_mutually_exclusive_group() - auto_unit_group.add_argument('--auto-tests', '-A', - metavar='<tests>', type=str, nargs=1, - help='List of tests to run', - default=None, - dest='auto_tests') - auto_unit_group.add_argument('--unit-tests', '-U', - metavar='<tests>', type=str, nargs='?', - const='*', - help='List of unit tests to run', - dest='unit_tests') - - # Prevent --valgrind/--gdb from being used together - valgrind_gdb_group = self.parser.add_mutually_exclusive_group() - valgrind_gdb_group.add_argument('--gdb', '-g', metavar='<exec>', - type=str, nargs=1, - help='Run gdb on specified executable', - dest='gdb') - valgrind_gdb_group.add_argument('--valgrind', '-V', action='store_true', - help='Run valgrind on IWD', dest='valgrind') - - self.args = self.parser.parse_args() - - if self.args.auto_tests: - self.args.auto_tests = self.args.auto_tests[0].split(',') - - if self.args.sub_tests: - self.args.sub_tests = self.args.sub_tests[0].split(',') - - if self.args.log and self.args.unit_tests: - dbg("Cannot use --log with --unit-tests") - quit() - - if self.args.sub_tests: - if not self.args.auto_tests: - dbg("--sub-tests must be used with --auto-tests") - quit() - - if len(self.args.auto_tests) > 1: - dbg("--sub-tests must be used with a single auto test") - quit() - - def start(self): - usb_adapters = None - pci_adapters = None - - qemu_table = [ - 'qemu-system-x86_64', - '/usr/bin/qemu-system-x86_64' - ] - - kernel_table = [ - 'bzImage', - 'arch/x86/boot/bzImage', - 'vmlinux', - 'arch/x86/boot/vmlinux' - ] - - if self.args.qemu is None: - qemu_binary = find_binary(qemu_table) - if not qemu_binary: - print("Could not find qemu binary") - quit() - else: - if path_exists(self.args.qemu): - qemu_binary = self.args.qemu - else: - print("QEMU binary %s does not exist" % \ - self.args.qemu) - quit() - - if self.args.kernel is None: - kernel_binary = find_binary(kernel_table) - if not kernel_binary: - print("Could not find kernel image") - quit() - else: - if path_exists(self.args.kernel): - kernel_binary = self.args.kernel - else: - print("Kernel image %s does not exist" % \ - self.args.kernel) - quit() - - if self.args.hw: - hw_conf = ConfigParser() - hw_conf.read(self.args.hw) - - if hw_conf.has_section('USBAdapters'): - # The actual key name of the adapter - # doesn't matter since all we need is the - # bus/address. This gets named by the kernel - # anyways once in the VM. - usb_adapters = [v for v in hw_conf['USBAdapters'].values()] - - if hw_conf.has_section('PCIAdapters'): - pci_adapters = [v for v in hw_conf['PCIAdapters'].values()] - - # - # Additional arguments not provided to test-runner which are - # needed once booted into the kernel. - # - options = 'init=%s' % os.path.realpath(sys.argv[0]) - - # Support running from top level as well as tools - if os.getcwd().endswith('tools'): - options += ' --testhome %s/../' % os.getcwd() - else: - options += ' --testhome %s' % os.getcwd() - - options += ' --path "%s"' % os.environ['PATH'] - - if self.args.auto_tests: - options += ' --auto_tests %s' % ','.join(self.args.auto_tests) - - if self.args.sub_tests: - options += ' --sub_tests %s' % ','.join(self.args.sub_tests) - - if self.args.log: - if os.environ.get('SUDO_GID', None) is None: - print("--log can only be used as root user") - quit() - - self.args.log = os.path.abspath(self.args.log) - uid = int(os.environ['SUDO_UID']) - gid = int(os.environ['SUDO_GID']) - - if not path_exists(self.args.log): - os.mkdir(self.args.log) - os.chown(self.args.log, uid, gid) - - options += ' --log-gid %u' % gid - options += ' --log-uid %u' % uid - - if self.args.monitor: - if os.environ.get('SUDO_GID', None) is None: - print("--monitor can only be used as root user") - quit() - - self.args.monitor = os.path.abspath(self.args.monitor) - mon_parent_dir = os.path.abspath(os.path.join(self.args.monitor, os.pardir)) - - options += ' --log-gid %u' % int(os.environ['SUDO_GID']) - options += ' --log-uid %u' % int(os.environ['SUDO_UID']) - - denylist = [ - 'auto_tests', - 'sub_tests', - 'qemu', - 'kernel' - ] - - nproc = multiprocessing.cpu_count() - - # - # Specially handle CPU systems with minimal cores, otherwise - # use half the host cores. - # - if nproc < 2: - smp = 1 - else: - smp = int(nproc / 2) - - # - # Increase RAM if valgrind is being used - # - if self.args.valgrind: - ram = 512 - else: - ram = 384 - - print("Using %d cores, %d RAM for VM" % (smp, ram)) - - # - # This passes through most of the command line options to - # the kernel command line. Some are not relevant (e.g. qemu) - # so similar options are added in the denylist above. This excludes - # any unset options which are assumed to be None or False. This - # is done so default arguments can be filled once in the VM. If - # we pass and basic types (None, False etc.) they are turned into - # a string representation ('None', 'False', etc.) which is not - # desirable. - # - for arg in vars(self.args): - if arg in denylist or getattr(self.args, arg) in [None, False, []]: - continue - options += ' --%s %s' % (arg, str(getattr(self.args, arg))) - - kern_log = "ignore_loglevel" if "kernel" in self.args.verbose else "quiet" - - qemu_cmdline = [ - qemu_binary, - '-machine', 'type=q35,accel=kvm:tcg', - '-nodefaults', '-no-user-config', '-monitor', 'none', - '-display', 'none', '-m', '%dM' % ram, '-nographic', '-vga', - 'none', '-no-acpi', '-no-hpet', - '-no-reboot', '-fsdev', - 'local,id=fsdev-root,path=/,readonly=on,security_model=none,multidevs=remap', - '-device', - 'virtio-9p-pci,fsdev=fsdev-root,mount_tag=/dev/root', - '-chardev', 'stdio,id=chardev-serial0,signal=off', - '-device', 'pci-serial,chardev=chardev-serial0', - '-device', 'virtio-rng-pci', - '-kernel', - kernel_binary, - '-append', - 'console=ttyS0,115200n8 earlyprintk=serial \ - rootfstype=9p root=/dev/root \ - rootflags=trans=virtio,msize=1048576,version=9p2000.u \ - acpi=off pci=noacpi %s ro \ - mac80211_hwsim.radios=0 %s' % (kern_log, options), - '-smp', str(smp) - ] - - # Add two ethernet devices for testing EAD - qemu_cmdline.extend([ - '-net', 'nic,model=virtio', - '-net', 'nic,model=virtio', - '-net', 'user' - ]) - - if usb_adapters: - for bus, addr in [s.split(',') for s in usb_adapters]: - qemu_cmdline.extend(['-usb', - '-device', - 'usb-host,hostbus=%s,hostaddr=%s' % \ - (bus, addr)]) - if pci_adapters: - qemu_cmdline.extend(['-enable-kvm']) - for addr in pci_adapters: - qemu_cmdline.extend(['-device', 'vfio-pci,host=%s' % addr]) - - if self.args.log: - # - # Creates a virtfs device that can be mounted. This mount - # will point back to the provided log directory and is - # writable unlike the rest of the mounted file system. - # - qemu_cmdline.extend([ - '-virtfs', - 'local,path=%s,mount_tag=logdir,security_model=passthrough,id=logdir' \ - % self.args.log - ]) - - if self.args.monitor: - qemu_cmdline.extend([ - '-virtfs', - 'local,path=%s,mount_tag=mondir,security_model=passthrough,id=mondir' \ - % mon_parent_dir - ]) - - os.execlp(qemu_cmdline[0], *qemu_cmdline) - -if __name__ == '__main__': - if os.getpid() == 1 and os.getppid() == 0: - atexit.register(exit_vm) - prepare_sandbox() - run_tests() - - exit() - - main = Main() - main.start() +Runner().start() diff --git a/tools/test_runner_kernel_config b/tools/test_runner_kernel_config @@ -1,8 +1,12 @@ #! /bin/sh +scripts/config --enable CONFIG_CFG80211 +scripts/config --enable CONFIG_MAC80211 scripts/config --enable CONFIG_MAC80211_HWSIM scripts/config --enable CONFIG_NLMON scripts/config --enable CONFIG_VLAN_8021Q +scripts/config --enable CONFIG_RFKILL +scripts/config --enable CONFIG_IPV6 scripts/config --enable CONFIG_EXPERT scripts/config --enable CONFIG_CFG80211_CERTIFICATION_ONUS @@ -16,14 +20,21 @@ scripts/config --enable CONFIG_CRYPTO_RSA scripts/config --enable CONFIG_CRYPTO_AES_X86_64 scripts/config --enable CONFIG_CRYPTO_AES_NI_INTEL scripts/config --enable CONFIG_CRYPTO_MD4 +scripts/config --enable CONFIG_CRYPTO_MD5 +scripts/config --enable CONFIG_CRYPTO_SHA1 +scripts/config --enable CONFIG_CRYPTO_SHA256 +scripts/config --enable CONFIG_CRYPTO_SHA512 scripts/config --enable CONFIG_CRYPTO_SHA1_SSSE3 scripts/config --enable CONFIG_CRYPTO_SHA256_SSSE3 scripts/config --enable CONFIG_CRYPTO_SHA512_SSSE3 scripts/config --enable CONFIG_CRYPTO_ECB +scripts/config --enable CONFIG_CRYPTO_CBC scripts/config --enable CONFIG_CRYPTO_CMAC scripts/config --enable CONFIG_CRYPTO_DES scripts/config --enable CONFIG_CRYPTO_DES3_EDE_X86_64 scripts/config --enable CONFIG_CRYPTO_ARC4 +scripts/config --enable CONFIG_CRYPTO_HMAC +scripts/config --enable CONFIG_KEYS scripts/config --enable CONFIG_KEY_DH_OPERATIONS scripts/config --enable CONFIG_ASYMMETRIC_KEY_TYPE scripts/config --enable CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE @@ -35,3 +46,9 @@ scripts/config --enable CONFIG_HW_RANDOM_VIRTIO scripts/config --enable CONFIG_HW_RANDOM_INTEL #scripts/config --enable CONFIG_HW_RANDOM_AMD scripts/config --enable CONFIG_SECURITYFS + +# Options needed for UML +scripts/config --enable CONFIG_BINFMT_ELF +scripts/config --enable CONFIG_HOSTFS +scripts/config --enable CONFIG_UML_TIME_TRAVEL_SUPPORT +scripts/config --enable CONFIG_BINFMT_SCRIPT diff --git a/tools/utils.py b/tools/utils.py @@ -0,0 +1,519 @@ +import os +import subprocess +import fcntl +import sys +import traceback +import shutil +import dbus + +from gi.repository import GLib +from weakref import WeakValueDictionary +from glob import glob + +from runner import RunnerCoreArgParse + +class Process(subprocess.Popen): + processes = WeakValueDictionary() + testargs = RunnerCoreArgParse().parse_args() + + def __new__(cls, *args, **kwargs): + obj = super().__new__(cls) + cls.processes[id(obj)] = obj + return obj + + def __init__(self, args, namespace=None, outfile=None, env=None, check=False, cleanup=None): + self.write_fds = [] + self.io_watch = None + self.cleanup = cleanup + self.verbose = False + self.out = '' + self.hup = False + self.killed = False + self.namespace = namespace + + logfile = args[0] + + if Process.is_verbose(args[0], log=False): + self.verbose = True + + if namespace: + args = ['ip', 'netns', 'exec', namespace] + args + logfile += '-%s' % namespace + + if outfile: + # outfile is only used by iwmon, in which case we don't want + # to append to an existing file. + self._append_outfile(outfile, append=False) + + if self.testargs.log: + testdir = os.getcwd() + + # Special case any processes started prior to a test + # (i.e. from testhome). Put these in the root log directory + if testdir == self.testargs.testhome: + testdir = '.' + else: + testdir = os.path.basename(testdir) + + logfile = '%s/%s/%s' % (self.testargs.log, testdir, logfile) + self._append_outfile(logfile) + + super().__init__(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=env, cwd=os.getcwd()) + + # Set as non-blocking so read() in the IO callback doesn't block forever + fl = fcntl.fcntl(self.stdout, fcntl.F_GETFL) + fcntl.fcntl(self.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) + + self.io_watch = GLib.io_add_watch(self.stdout, GLib.IO_IN | + GLib.IO_HUP | GLib.IO_ERR, self.process_io) + + print("Starting process {}".format(self.args)) + + if check: + self.wait(10) + self.killed = True + if self.returncode != 0: + raise subprocess.CalledProcessError(returncode=self.returncode, + cmd=args) + + @staticmethod + def is_verbose(process, log=True): + process = os.path.basename(process) + + if Process.testargs is None: + return False + + # every process is verbose when logging is enabled + if log and Process.testargs.log: + return True + + if process in Process.testargs.verbose: + return True + + # Special case here to enable verbose output with valgrind running + if process == 'valgrind' and 'iwd' in Process.testargs.verbose: + return True + + # Handle any glob matches + for item in Process.testargs.verbose: + if process in glob(item): + return True + + return False + + @classmethod + def get_all(cls): + return cls.processes.values() + + @classmethod + def kill_all(cls): + for p in cls.processes.values(): + if p.args[0] == 'dmesg': + continue + + p.kill() + + @staticmethod + def _write_io(instance, data, stdout=True): + for f in instance.write_fds: + f.write(data) + + # Write out a separator so multiple process calls per + # test are easer to read. + if instance.hup: + f.write("Terminated: {}\n\n".format(instance.args)) + + f.flush() + + if instance.verbose and stdout: + sys.__stdout__.write(data) + sys.__stdout__.flush() + + @classmethod + def write_separators(cls, test, sep): + # + # There are either log running processes (cls.processes) or + # processes that have terminated already but a log file exists + # on disk. We still want the separators to show for both cases + # so after writing separators for running processes, also + # write them in any additional log files. + # + nowrite = [] + + for proc in cls.processes.values(): + if proc.killed: + continue + + cls._write_io(proc, sep, stdout=False) + nowrite.append(proc.args[0]) + + if cls.testargs.log: + logfiles = os.listdir('%s/%s' % (cls.testargs.log, test)) + + extra = list(set(logfiles) - set(nowrite)) + + for log in extra: + logfile = '%s/%s/%s' % (cls.testargs.log, test, log) + with open(logfile, 'a') as f: + f.write(sep) + f.close() + + def process_io(self, source, condition): + if condition & GLib.IO_HUP: + self.hup = True + + data = source.read() + + if not data: + return True + + try: + data = data.decode('utf-8') + except: + return True + + # Save data away in case the caller needs it (e.g. list_sta) + self.out += data + + self._write_io(self, data) + + return True + + def _append_outfile(self, file, append=True): + gid = int(os.environ.get('SUDO_GID', os.getgid())) + uid = int(os.environ.get('SUDO_UID', os.getuid())) + dir = os.path.dirname(file) + + if not os.path.exists(dir): + os.mkdir(dir) + os.chown(dir, uid, gid) + + file = os.path.join(dir,file) + + # If the out file exists, append. Useful for processes like + # hostapd_cli where it is called multiple times independently. + if os.path.isfile(file) and append: + mode = 'a' + else: + mode = 'w' + + try: + f = open(file, mode) + except Exception as e: + traceback.print_exc() + sys.exit(0) + + os.fchown(f.fileno(), uid, gid) + + self.write_fds.append(f) + + def wait_for_socket(self, socket, wait): + Namespace.non_block_wait(os.path.exists, wait, socket) + + # Wait for both process termination and HUP signal + def __wait(self, timeout): + try: + super().wait(timeout) + if not self.hup: + return False + + return True + except: + return False + + # Override wait() so it can do so non-blocking + def wait(self, timeout=10): + Namespace.non_block_wait(self.__wait, timeout, 1) + self._cleanup() + + def _cleanup(self): + if self.cleanup: + self.cleanup() + + self.write_fds = [] + + if self.io_watch: + GLib.source_remove(self.io_watch) + self.io_watch = None + + self.cleanup = None + self.killed = True + + # Override kill() + def kill(self, force=False): + if self.killed: + return + + print("Killing process {}".format(self.args)) + + if force: + super().kill() + else: + self.terminate() + + try: + self.wait(timeout=15) + except: + print("Process %s did not complete in 15 seconds!" % self.name) + super().kill() + + self._cleanup() + + def __str__(self): + return str(self.args) + '\n' + +dbus_count = 0 +# Partial DBus config. The remainder (<listen>) will be filled in for each +# namespace that is created so each individual dbus-daemon has its own socket +# and address. +dbus_config = ''' +<!DOCTYPE busconfig PUBLIC \ +"-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" \ +"http://www.freedesktop.org/standards/dbus/1.0/\ +busconfig.dtd\"> +<busconfig> +<type>system</type> +<limit name=\"reply_timeout\">2147483647</limit> +<auth>ANONYMOUS</auth> +<allow_anonymous/> +<policy context=\"default\"> +<allow user=\"*\"/> +<allow own=\"*\"/> +<allow send_type=\"method_call\"/> +<allow send_type=\"signal\"/> +<allow send_type=\"method_return\"/> +<allow send_type=\"error\"/> +<allow receive_type=\"method_call\"/> +<allow receive_type=\"signal\"/> +<allow receive_type=\"method_return\"/> +<allow receive_type=\"error\"/> +<allow send_destination=\"*\" eavesdrop=\"true\"/> +<allow eavesdrop=\"true\"/> +</policy> +''' + +class Namespace: + def __init__(self, args, name, radios): + self.dbus_address = None + self.name = name + self.radios = radios + self.args = args + + Process(['ip', 'netns', 'add', name]).wait() + for r in radios: + Process(['iw', 'phy', r.name, 'set', 'netns', 'name', name]).wait() + + self.start_dbus() + + def reset(self): + self._bus = None + + for r in self.radios: + r._radio = None + + self.radios = [] + + Process.kill_all() + + def __del__(self): + if self.name: + print("Removing namespace %s" % self.name) + + Process(['ip', 'netns', 'del', self.name]).wait() + + def get_bus(self): + return self._bus + + def start_process(self, args, env=None, **kwargs): + if not env: + env = os.environ.copy() + + if hasattr(self, "dbus_address"): + # In case this process needs DBus... + env['DBUS_SYSTEM_BUS_ADDRESS'] = self.dbus_address + + return Process(args, namespace=self.name, env=env, **kwargs) + + def stop_process(self, p, force=False): + p.kill(force) + + def is_process_running(self, process): + for p in Process.get_all(): + if p.namespace == self.name and p.args[0] == process: + return True + return False + + def _cleanup_dbus(self): + try: + os.remove(self.dbus_address.split('=')[1]) + except: + pass + + os.remove(self.dbus_cfg) + + def start_dbus(self): + global dbus_count + + self.dbus_address = 'unix:path=/tmp/dbus%d' % dbus_count + self.dbus_cfg = '/tmp/dbus%d.conf' % dbus_count + dbus_count += 1 + + with open(self.dbus_cfg, 'w+') as f: + f.write(dbus_config) + f.write('<listen>%s</listen>\n' % self.dbus_address) + f.write('</busconfig>\n') + + p = self.start_process(['dbus-daemon', '--config-file=%s' % self.dbus_cfg], + cleanup=self._cleanup_dbus) + + p.wait_for_socket(self.dbus_address.split('=')[1], 5) + + self._bus = dbus.bus.BusConnection(address_or_type=self.dbus_address) + + def start_iwd(self, config_dir = '/tmp', storage_dir = '/tmp/iwd'): + args = [] + iwd_radios = ','.join([r.name for r in self.radios if r.use == 'iwd']) + + if self.args.valgrind: + args.extend(['valgrind', '--leak-check=full', '--track-origins=yes', + '--show-leak-kinds=all', + '--log-file=/tmp/valgrind.log.%p']) + + args.extend(['iwd', '-E']) + + if iwd_radios != '': + args.extend(['-p', iwd_radios]) + + if Process.is_verbose(args[0]): + args.append('-d') + + env = os.environ.copy() + + env['CONFIGURATION_DIRECTORY'] = config_dir + env['STATE_DIRECTORY'] = storage_dir + + if Process.is_verbose('iwd-dhcp'): + env['IWD_DHCP_DEBUG'] = '1' + + if Process.is_verbose('iwd-tls'): + env['IWD_TLS_DEBUG'] = '1' + + if Process.is_verbose('iwd-acd'): + env['IWD_ACD_DEBUG'] = '1' + + return self.start_process(args, env=env) + + @staticmethod + def non_block_wait(func, timeout, *args, exception=True): + ''' + Convenience function for waiting in a non blocking + manor using GLibs context iteration i.e. does not block + the main loop while waiting. + + 'func' will be called at least once and repeatedly until + either it returns success, throws an exception, or the + 'timeout' expires. + + 'timeout' is the ultimate timeout in seconds + + '*args' will be passed to 'func' + + If 'exception' is an Exception type it will be raised. + If 'exception' is True a generic TimeoutError will be raised. + Any other value will not result in an exception. + ''' + # Simple class for signaling the wait timeout + class Bool: + def __init__(self, value): + self.value = value + + def wait_timeout_cb(done): + done.value = True + return False + + mainloop = GLib.MainLoop() + done = Bool(False) + + timeout = GLib.timeout_add_seconds(timeout, wait_timeout_cb, done) + context = mainloop.get_context() + + while True: + try: + ret = func(*args) + if ret: + if not done.value: + GLib.source_remove(timeout) + return ret + except Exception as e: + if not done.value: + GLib.source_remove(timeout) + raise e + + if done.value == True: + if isinstance(exception, Exception): + raise exception + elif type(exception) == bool and exception: + raise TimeoutError("Timeout on non_block_wait") + else: + return + + context.iteration(may_block=True) + + def __str__(self): + ret = 'Namespace: %s\n' % self.name + ret += 'Processes:\n' + for p in Process.get_all(): + ret += '\t%s' % str(p) + + ret += 'Radios:\n' + if len(self.radios) > 0: + for r in self.radios: + ret += '\t%s\n' % str(r) + else: + ret += '\tNo Radios\n' + + ret += 'DBus Address: %s\n' % self.dbus_address + ret += '===================================================\n\n' + + return ret + +class BarChart(): + def __init__(self, height=10, max_width=80): + self._height = height + self._max_width = max_width + self._values = [] + self._max_value = 0 + self._min_value = 0 + + def add_value(self, value): + if len(self._values) == 0: + self._max_value = int(1.01 * value) + self._min_value = int(0.99 * value) + elif value > self._max_value: + self._max_value = int(1.01 * value) + elif value < self._min_value: + self._min_value = int(0.99 * value) + + self._values.append(value) + + def _value_to_stars(self, value): + # Need to scale value (range of min_value -> max_value) to + # a range of 0 -> height + # + # Scaled = ((value - min_value) / ( max_value - min_value)) * (Height - 0) + 0 + + return int(((value - self._min_value) / + (self._max_value - self._min_value)) * self._height) + + def __str__(self): + # Need to map value from range 0 - self._height + ret = '' + + for i, value in enumerate(self._values): + stars = self._value_to_stars(value) + ret += '[%3u] ' % i + '%-10s' % ('*' * stars) + '\t\t\t%d\n' % value + + ret += '\n' + + return ret diff --git a/unit/test-band.c b/unit/test-band.c @@ -331,6 +331,33 @@ static const struct band_chandef cd_4 = { .center1_frequency = 2427, }; +static const struct band_chandef cd_5 = { + .frequency = 6235, + .channel_width = BAND_CHANDEF_WIDTH_20, +}; + +static const struct band_chandef cd_6 = { + .frequency = 6235, + .channel_width = BAND_CHANDEF_WIDTH_40, +}; + +static const struct band_chandef cd_7 = { + .frequency = 6235, + .channel_width = BAND_CHANDEF_WIDTH_80, +}; + +static const struct band_chandef cd_8 = { + .frequency = 6235, + .channel_width = BAND_CHANDEF_WIDTH_160, +}; + +static const struct band_chandef cd_9 = { + .frequency = 6235, + .channel_width = BAND_CHANDEF_WIDTH_80P80, + .center1_frequency = 6145, + .center2_frequency = 6225, +}; + struct oci_data { const struct band_chandef *cd; uint8_t oci[3]; @@ -341,6 +368,11 @@ static const struct oci_data oci_data_1 = { &cd_1, { 129, 108, 0 } }; static const struct oci_data oci_data_2 = { &cd_2, { 130, 36, 155 } }; static const struct oci_data oci_data_3 = { &cd_3, { 81, 6, 0 } }; static const struct oci_data oci_data_4 = { &cd_4, { 84, 6, 0 } }; +static const struct oci_data oci_data_5 = { &cd_5, { 131, 57, 0 } }; +static const struct oci_data oci_data_6 = { &cd_6, { 132, 57, 0 } }; +static const struct oci_data oci_data_7 = { &cd_7, { 133, 57, 0 } }; +static const struct oci_data oci_data_8 = { &cd_8, { 134, 57, 0 } }; +static const struct oci_data oci_data_9 = { &cd_9, { 135, 57, 55 } }; static const struct oci_data oci_err_1 = { &cd_1, { 129, 36, 0 }, -EPERM }; static const struct oci_data oci_err_2 = { &cd_1, { 121, 108, 0 }, -EPERM }; @@ -372,6 +404,26 @@ static void test_oci_from_chandef(const void *data) assert(!memcmp(oci, test->oci, sizeof(oci))); } +static void test_6ghz_channels(const void *data) +{ + unsigned int i; + + /* Test all channels for 6GHz */ + for (i = 1; i <= 233; i += 4) + assert(band_channel_to_freq(i, BAND_FREQ_6_GHZ) != 0); +} + +static void test_6ghz_freqs(const void *data) +{ + uint32_t i; + enum band_freq band; + + for (i = 5955; i < 7115; i += 5) { + assert(band_freq_to_channel(i, &band) != 0); + assert(band == BAND_FREQ_6_GHZ); + } +} + int main(int argc, char *argv[]) { l_test_init(&argc, &argv); @@ -395,6 +447,11 @@ int main(int argc, char *argv[]) l_test_add("/band/oci/verify 2", test_oci_verify, &oci_data_2); l_test_add("/band/oci/verify 3", test_oci_verify, &oci_data_3); l_test_add("/band/oci/verify 4", test_oci_verify, &oci_data_4); + l_test_add("/band/oci/verify 5", test_oci_verify, &oci_data_5); + l_test_add("/band/oci/verify 6", test_oci_verify, &oci_data_6); + l_test_add("/band/oci/verify 7", test_oci_verify, &oci_data_7); + l_test_add("/band/oci/verify 8", test_oci_verify, &oci_data_8); + l_test_add("/band/oci/verify 9", test_oci_verify, &oci_data_9); l_test_add("/band/oci/noverify 1", test_oci_verify, &oci_err_1); l_test_add("/band/oci/noverify 2", test_oci_verify, &oci_err_2); @@ -410,5 +467,8 @@ int main(int argc, char *argv[]) l_test_add("/band/oci/chandef 3", test_oci_from_chandef, &oci_data_3); l_test_add("/band/oci/chandef 4", test_oci_from_chandef, &oci_data_4); + l_test_add("/band/6ghz/channels", test_6ghz_channels, NULL); + l_test_add("/band/6ghz/freq", test_6ghz_freqs, NULL); + return l_test_run(); } diff --git a/wired/ethdev.c b/wired/ethdev.c @@ -238,10 +238,15 @@ static void rx_packet(struct ethdev *dev, const uint8_t *addr, l_debug("Created new EAPoL session"); - l_queue_push_tail(dev->eapol_sessions, eapol); - eapol->cred = network_lookup_security("default"); - eap_load_settings(eapol->eap, eapol->cred, "EAP-"); + if (!eapol->cred || !eap_load_settings(eapol->eap, + eapol->cred, "EAP-")) { + l_error("Failed to load EAP settings"); + eapol_free(eapol); + return; + } + + l_queue_push_tail(dev->eapol_sessions, eapol); eap_set_key_material_func(eapol->eap, eap_key_material); eap_set_event_func(eapol->eap, eap_event); @@ -386,7 +391,7 @@ static char *read_devtype_from_uevent(const char *ifname) return devtype; } -static int modify_membership(struct ethdev *dev, int optname) +static int modify_membership(uint32_t index, int optname) { struct packet_mreq mreq; int fd; @@ -396,7 +401,7 @@ static int modify_membership(struct ethdev *dev, int optname) return -1; memset(&mreq, 0, sizeof(mreq)); - mreq.mr_ifindex = dev->index; + mreq.mr_ifindex = index; mreq.mr_type = PACKET_MR_MULTICAST; mreq.mr_alen = ETH_ALEN; memcpy(mreq.mr_address, pae_group_addr, ETH_ALEN); @@ -410,7 +415,8 @@ static void ethdev_free(void *data) l_debug("Freeing device %s", dev->ifname); - modify_membership(dev, PACKET_DROP_MEMBERSHIP); + if (modify_membership(dev->index, PACKET_DROP_MEMBERSHIP) < 0) + l_error("Failed to drop membership"); l_queue_destroy(dev->eapol_sessions, eapol_free); @@ -516,6 +522,11 @@ static void newlink_notify(const struct ifinfomsg *ifi, int bytes) } } + if (modify_membership(index, PACKET_ADD_MEMBERSHIP) < 0) { + l_error("Failed to add membership"); + return; + } + dev = l_new(struct ethdev, 1); dev->index = index; dev->active = active; @@ -527,8 +538,6 @@ static void newlink_notify(const struct ifinfomsg *ifi, int bytes) l_debug("Creating device %u", dev->index); - modify_membership(dev, PACKET_ADD_MEMBERSHIP); - l_dbus_object_add_interface(dbus_app_get(), dev->path, ADAPTER_INTERFACE, dev); diff --git a/wired/network.c b/wired/network.c @@ -133,7 +133,10 @@ struct l_settings *network_lookup_security(const char *network) l_debug("Loading %s", path); conf = l_settings_new(); - l_settings_load_from_file(conf, path); + if (!l_settings_load_from_file(conf, path)) { + l_settings_free(conf); + conf = NULL; + } l_free(path);