eiwd

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

commit 65388d4c9ddeb398fa9a65c4ba77af1d6be54c4d
parent 4bc8fff2a3ad303f65e7eec144e2f15ed028ab23
Author: illiliti <illiliti@protonmail.com>
Date:   Sun, 17 Jul 2022 15:07:59 +0300

Merge tag '1.29'

Release 1.29

Diffstat:
MChangeLog | 5+++++
MHACKING | 2+-
Macinclude.m4 | 5+++++
Mautotests/testAP/connection_test.py | 79++++++++++++++++---------------------------------------------------------------
Mautotests/testAP/dhcp_config_test.py | 49+++----------------------------------------------
Mautotests/testAP/dhcp_test.py | 69++++++++++++++++++++++++---------------------------------------------
Aautotests/testAP/validation.py | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mautotests/testAdHoc/adhoc_test.py | 19+++++++++++++++----
Mautotests/testAgent/agent_test.py | 26+++++---------------------
Mautotests/testDPP/connection_test.py | 34++++++++++++++++++++++++++++++++++
Mautotests/testEAP-WPS/four_digit_pin_test.py | 16+++++++++++-----
Mautotests/testEAP-WPS/push_button_test.py | 17++++++++++++-----
Mautotests/testEncryptedProfiles/connection_test.py | 9+++++++++
Mautotests/testHiddenNetworks/exceptions_test.py | 4++--
Mautotests/testHiddenNetworks/open_network_test.py | 4++--
Mautotests/testHiddenNetworks/validation.py | 2+-
Mautotests/testHiddenNetworks/wpa_network_test.py | 4++--
Mautotests/testKnownNetworks/known_network_test.py | 23+++++++++++++++++++++--
Aautotests/testNetconfig/ap-main.conf | 7+++++++
Aautotests/testNetconfig/ap-ns1.conf | 7+++++++
Aautotests/testNetconfig/auto.psk | 5+++++
Mautotests/testNetconfig/connection_test.py | 266++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mautotests/testNetconfig/dhcpd-v6.conf | 4++--
Mautotests/testNetconfig/dhcpd.conf | 24+++++++++++++++++-------
Mautotests/testNetconfig/hw.conf | 8+++++---
Mautotests/testNetconfig/main.conf | 2+-
Aautotests/testNetconfig/resolvconf | 2++
Dautotests/testNetconfig/ssidTKIP.conf | 7-------
Dautotests/testNetconfig/ssidTKIP.psk | 6------
Aautotests/testNetconfig/static.psk | 16++++++++++++++++
Mautotests/testNetconfig/static_test.py | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Dautotests/testNetconfig/storage/ssidTKIP.psk | 3---
Mautotests/testP2P/connection_test.py | 5+++++
Mautotests/testWPA2-ext-key-id/connection_test.py | 2--
Mautotests/util/hostapd.py | 22+++++++++++++---------
Mautotests/util/iwd.py | 105+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mautotests/util/testutil.py | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mclient/ad-hoc.c | 13+++++--------
Mclient/adapter.c | 12+++++++-----
Mclient/agent.c | 4++--
Mclient/ap.c | 39++++++++++++++++++++-------------------
Mclient/command.c | 16++++++++--------
Mclient/dbus-proxy.c | 21++++++++++++++-------
Mclient/dbus-proxy.h | 3++-
Mclient/device.c | 18+++++++++---------
Mclient/diagnostic.c | 32+++++++++++++-------------------
Mclient/display.c | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mclient/display.h | 20++++++++++----------
Mclient/dpp.c | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mclient/known-networks.c | 12++++++------
Mclient/station.c | 48++++++++++++++++++++++--------------------------
Mclient/wsc.c | 4++--
Mconfigure.ac | 4++--
Mdoc/device-provisioning-api.txt | 15+++++++++++++++
Mmonitor/nlmon.c | 2+-
Msrc/ap.c | 2++
Msrc/dpp.c | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/eap.c | 5++++-
Msrc/eapol.c | 14++++++++------
Msrc/eapol.h | 5+++--
Msrc/fils.c | 3+++
Msrc/netconfig.c | 6++++--
Msrc/p2p.c | 2+-
Msrc/station.c | 12+++---------
Msrc/storage.c | 12++++++++----
Mtools/run-tests | 106++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Mtools/runner.py | 36+++++++++++++++++++-----------------
Mtools/test_runner_kernel_config | 2+-
Mtools/utils.py | 58+++++++++++++++++++++++++++++++++++++++++++++++++---------
Munit/test-eapol.c | 12++++++------
70 files changed, 1498 insertions(+), 570 deletions(-)

diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,8 @@ +ver 1.29: + Fix issue with handling EAP-Success message. + Fix issue with handling secure setting and EAPoL. + Add support for DeviceProvisioning API properties. + ver 1.28: Fix issue with handling invalid EAPoL frames. Fix issue with handling unexpectedly unencrypted EAP frames. diff --git a/HACKING b/HACKING @@ -5,7 +5,7 @@ If you fixed a bug or you want to add support for something, patches are welcome! The preferred method of submitting the patches to the project is by email to the iwd mailing list: - iwd@lists.01.org + iwd@lists.linux.dev In order to ease the inclusion of your patch, it's important to follow some rules, otherwise it will likely be rejected by maintainers. diff --git a/acinclude.m4 b/acinclude.m4 @@ -64,4 +64,9 @@ AC_DEFUN([COMPILER_FLAGS], [ CFLAGS+=" -Wcast-align" fi fi + + if (test "$CC" = "clang"); then + CFLAGS+=" -Wno-unknown-warning-option" + CFLAGS+=" -Wno-unknown-pragmas" + fi ]) diff --git a/autotests/testAP/connection_test.py b/autotests/testAP/connection_test.py @@ -1,90 +1,43 @@ #! /usr/bin/python3 import unittest -import sys, os -import iwd from iwd import IWD -from iwd import PSKAgent -from iwd import NetworkType -from hostapd import HostapdCLI -import testutil +from config import ctx +from validation import validate, client_connect class Test(unittest.TestCase): - - def client_connect(self, wd, dev): - hostapd = HostapdCLI(config='psk-ccmp.conf') - - ordered_network = dev.get_ordered_network('TestAP1') - - self.assertEqual(ordered_network.type, NetworkType.psk) - - psk_agent = PSKAgent('Password1') - wd.register_psk_agent(psk_agent) - - ordered_network.network_object.connect() - - condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(dev, condition) - - wd.unregister_psk_agent(psk_agent) - - testutil.test_iface_operstate(dev.name) - testutil.test_ifaces_connected(hostapd.ifname, dev.name) - - dev.disconnect() - - condition = 'not obj.connected' - wd.wait_for_object_condition(ordered_network.network_object, condition) - def test_connection_success(self): wd = IWD(True) dev1, dev2 = wd.list_devices(2) - self.client_connect(wd, dev1) + client_connect(wd, dev1, 'TestAP1') dev1.start_ap('TestAP2', 'Password2') - try: - networks = {} - 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) - self.assertEqual(networks['TestAP2'].type, NetworkType.psk) - - psk_agent = PSKAgent('Password2') - wd.register_psk_agent(psk_agent) + validate(wd, dev2, dev1, 'TestAP2', 'Password2') - try: - dev2.disconnect() + # Finally test dev1 can go to client mode and connect again + client_connect(wd, dev1, 'TestAP1') - condition = 'not obj.connected' - wd.wait_for_object_condition(dev2, condition) - except: - pass + def test_client_start_ap(self): + wd = IWD(True) - networks['TestAP2'].network_object.connect() + dev1, dev2 = wd.list_devices(2) - condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(dev2, condition) + ctx.start_process(['iwctl', 'device', dev1.name, 'set-property', 'Mode', 'ap'], check=True) + ctx.start_process(['iwctl', 'ap', dev1.name, 'start', 'TestAP2', 'Password2'], check=True) - testutil.test_iface_operstate(dev2.name) - testutil.test_ifaces_connected(dev1.name, dev2.name, group=False) + iwctl = ctx.start_process(['iwctl', 'ap', 'list'], check=True) - wd.unregister_psk_agent(psk_agent) + self.assertIn(dev1.name, iwctl.out) - dev2.disconnect() + iwctl = ctx.start_process(['iwctl', 'ap', dev1.name, 'show'], check=True) - condition = 'not obj.connected' - wd.wait_for_object_condition(networks['TestAP2'].network_object, - condition) - finally: - dev1.stop_ap() + self.assertIn('TestAP2', iwctl.out) - # Finally test dev1 can go to client mode and connect again - self.client_connect(wd, dev1) + validate(wd, dev2, dev1, 'TestAP2', 'Password2') @classmethod def setUpClass(cls): diff --git a/autotests/testAP/dhcp_config_test.py b/autotests/testAP/dhcp_config_test.py @@ -1,14 +1,10 @@ #! /usr/bin/python3 import unittest -import sys, os -import iwd from iwd import IWD -from iwd import PSKAgent -from iwd import NetworkType from config import ctx -import testutil +from validation import validate class Test(unittest.TestCase): def test_connection_success(self): @@ -28,47 +24,8 @@ class Test(unittest.TestCase): dev1.start_ap('APConfig') - try: - networks = {} - networks['APConfig'] = dev2.get_ordered_network('APConfig', full_scan=True) - - self.assertEqual(networks['APConfig'].type, NetworkType.psk) - - psk_agent = PSKAgent('password123') - wd.register_psk_agent(psk_agent) - - try: - dev2.disconnect() - - condition = 'not obj.connected' - wd.wait_for_object_condition(dev2, condition) - except: - pass - - networks['APConfig'].network_object.connect() - - condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(dev2, condition) - - testutil.test_iface_operstate(dev2.name) - # - # TODO: cannot yet check the AP interface IP since its in a - # different namespace. - # - testutil.test_ip_address_match(dev2.name, "192.168.1.3") - - testutil.test_ip_connected(('192.168.1.3', ctx), ('192.168.1.1', ns0)) - - wd.unregister_psk_agent(psk_agent) - - dev2.disconnect() - - condition = 'not obj.connected' - wd.wait_for_object_condition(networks['APConfig'].network_object, - condition) - - finally: - dev1.stop_ap() + validate(wd, dev2, dev1, 'APConfig', 'password123', + sta_ip_info=('192.168.1.3', ctx), ap_ip_info=('192.168.1.1', ns0)) @classmethod def setUpClass(cls): diff --git a/autotests/testAP/dhcp_test.py b/autotests/testAP/dhcp_test.py @@ -10,6 +10,8 @@ from iwd import NetworkType from config import ctx import testutil +from validation import validate + class Test(unittest.TestCase): def test_connection_success(self): wd = IWD(True, '/tmp/dhcp') @@ -25,59 +27,36 @@ class Test(unittest.TestCase): with self.assertRaises(iwd.AlreadyExistsEx): dev4.start_ap('TestAP4', 'Password4') - try: - networks = {} - networks['TestAP2'] = dev2.get_ordered_network('TestAP2', full_scan=True) - - self.assertEqual(networks['TestAP2'].type, NetworkType.psk) - - psk_agent = PSKAgent('Password2') - wd.register_psk_agent(psk_agent) - - try: - dev2.disconnect() - - condition = 'not obj.connected' - wd.wait_for_object_condition(dev2, condition) - except: - pass + validate(wd, dev2, dev1, 'TestAP2', 'Password2', ip_checks=False) - networks['TestAP2'].network_object.connect() + network = dev2.get_ordered_network('TestAP2', full_scan=True) - condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(dev2, condition) - - testutil.test_iface_operstate(dev2.name) - testutil.test_ifaces_connected(dev1.name, dev2.name, group=False) - - try: - testutil.test_ip_address_match(dev1.name, "192.168.80.1") - testutil.test_ip_address_match(dev2.name, "192.168.80.2") - ip = "192.168.80.1" - except: - testutil.test_ip_address_match(dev1.name, "192.168.80.17") - testutil.test_ip_address_match(dev2.name, "192.168.80.18") - ip = "192.168.80.17" - - wd.unregister_psk_agent(psk_agent) + try: + testutil.test_ip_address_match(dev1.name, "192.168.80.1") + testutil.test_ip_address_match(dev2.name, "192.168.80.2") + ip = "192.168.80.1" + except: + testutil.test_ip_address_match(dev1.name, "192.168.80.17") + testutil.test_ip_address_match(dev2.name, "192.168.80.18") + ip = "192.168.80.17" - dev2.disconnect() + dev2.disconnect() - condition = 'not obj.connected' - wd.wait_for_object_condition(networks['TestAP2'].network_object, - condition) + condition = 'not obj.connected' + wd.wait_for_object_condition(network.network_object, condition) - # This should release the IP */ - dev1.stop_ap() + # This should release the IP */ + dev1.stop_ap() - # This should now succeed and the IP should match the old IP dev1 - # got initially. - dev4.start_ap('TestAP4', 'Password4') + # This should now succeed and the IP should match the old IP dev1 + # got initially. + dev4.start_ap('TestAP4', 'Password4') - testutil.test_ip_address_match(dev4.name, ip) + testutil.test_ip_address_match(dev4.name, ip) - finally: - dev1.stop_ap() + dev1.stop_ap() + dev3.stop_ap() + dev4.stop_ap() @classmethod def setUpClass(cls): diff --git a/autotests/testAP/validation.py b/autotests/testAP/validation.py @@ -0,0 +1,71 @@ +from iwd import PSKAgent +from iwd import NetworkType +from hostapd import HostapdCLI +import testutil + +def validate(wd, sta_dev, ap_dev, ssid, passphrase, + sta_ip_info=None, ap_ip_info=None, ip_checks=True): + try: + network = sta_dev.get_ordered_network(ssid, full_scan=True) + + if network.type != NetworkType.psk: + raise Exception("Network type mismatch") + + psk_agent = PSKAgent(passphrase) + wd.register_psk_agent(psk_agent) + + network.network_object.connect() + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(sta_dev, condition) + + testutil.test_iface_operstate(sta_dev.name) + + # This implies separate namespaces so the iface names won't exist + if not sta_ip_info or not ap_ip_info: + testutil.test_ifaces_connected(ap_dev.name, sta_dev.name, group=False) + + if not ip_checks: + return + + if sta_ip_info: + testutil.test_ip_address_match(sta_dev.name, sta_ip_info[0]) + + if sta_ip_info and ap_ip_info: + testutil.test_ip_connected(sta_ip_info, ap_ip_info) + + wd.unregister_psk_agent(psk_agent) + + sta_dev.disconnect() + + condition = 'not obj.connected' + wd.wait_for_object_condition(network.network_object, condition) + finally: + if ip_checks: + ap_dev.stop_ap() + +def client_connect(wd, dev, ssid): + hostapd = HostapdCLI(config='psk-ccmp.conf') + + ordered_network = dev.get_ordered_network(ssid) + + if ordered_network.type != NetworkType.psk: + raise Exception("Network type mismatch") + + psk_agent = PSKAgent('Password1') + wd.register_psk_agent(psk_agent) + + ordered_network.network_object.connect() + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(dev, condition) + + wd.unregister_psk_agent(psk_agent) + + testutil.test_iface_operstate(dev.name) + testutil.test_ifaces_connected(hostapd.ifname, dev.name) + + dev.disconnect() + + condition = 'not obj.connected' + wd.wait_for_object_condition(ordered_network.network_object, condition) diff --git a/autotests/testAdHoc/adhoc_test.py b/autotests/testAdHoc/adhoc_test.py @@ -2,16 +2,16 @@ import unittest import sys -import time sys.path.append('../util') -import iwd from iwd import IWD +from iwd import AdHocDevice +from config import ctx import testutil class Test(unittest.TestCase): - def validate_connection(self, wd): + def validate_connection(self, wd, client=False): dev1, dev2 = wd.list_devices(2) self.assertIsNotNone(dev1) @@ -22,7 +22,14 @@ class Test(unittest.TestCase): condition = 'obj.started == True' wd.wait_for_object_condition(adhoc1, condition) - adhoc2 = dev2.start_adhoc("AdHocNetwork", "secret123") + if not client: + adhoc2 = dev2.start_adhoc("AdHocNetwork", "secret123") + else: + ctx.start_process(['iwctl', 'device', dev2.name, 'set-property', + 'Mode', 'ad-hoc'], check=True) + ctx.start_process(['iwctl', 'ad-hoc', dev2.name, 'start', + 'AdHocNetwork', 'secret123'], check=True) + adhoc2 = AdHocDevice(dev2.device_path) condition = 'obj.started == True' wd.wait_for_object_condition(adhoc1, condition) @@ -42,6 +49,10 @@ class Test(unittest.TestCase): self.validate_connection(wd) + def test_client_adhoc(self): + wd = IWD(True) + self.validate_connection(wd, client=True) + @classmethod def setUpClass(cls): pass diff --git a/autotests/testAgent/agent_test.py b/autotests/testAgent/agent_test.py @@ -2,6 +2,7 @@ import unittest import sys +import dbus sys.path.append('../util') import iwd @@ -55,36 +56,19 @@ class Test(unittest.TestCase): IWD.clear_storage() - def test_connection_with_other_agent(self): + def test_connection_use_first_from_multiple_registered(self): wd = IWD() - iwctl = ctx.start_process(['iwctl', '-P', 'secret_ssid2']) - # Let iwctl to start and register its agent. - wd.wait(2) - - self.check_connection(wd, 'ssid2') - - iwctl.kill() - - IWD.clear_storage() - - def test_connection_use_own_agent_from_multiple_registered(self): - - wd = IWD() - - iwctl = ctx.start_process(['iwctl', '-P', 'secret_ssid2']) - # Let iwctl to start and register its agent. - wd.wait(2) - psk_agent = PSKAgent("secret_ssid1") wd.register_psk_agent(psk_agent) + psk_agent = PSKAgent("secret_ssid2") + wd.register_psk_agent(psk_agent) + self.check_connection(wd, 'ssid1') wd.unregister_psk_agent(psk_agent) - iwctl.kill() - IWD.clear_storage() @classmethod diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -5,9 +5,11 @@ import sys sys.path.append('../util') from iwd import IWD +from iwd import DeviceProvisioning from wpas import Wpas from hostapd import HostapdCLI from hwsim import Hwsim +from config import ctx class Test(unittest.TestCase): def test_iwd_as_enrollee(self): @@ -98,6 +100,38 @@ class Test(unittest.TestCase): self.wpas.wait_for_event('DPP-CONF-RECEIVED', timeout=30) + def test_client_as_configurator(self): + self.hapd.reload() + self.hapd.wait_for_event('AP-ENABLED') + + IWD.copy_to_storage('ssidCCMP.psk') + self.device.autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) + + ctx.start_process(['iwctl', 'dpp', self.device.name, 'start-configurator'], check=True) + + dpp = DeviceProvisioning(self.device.device_path) + + self.wpas.dpp_enrollee_start(dpp.uri) + + self.wpas.wait_for_event('DPP-CONF-RECEIVED', timeout=30) + + def test_client_as_enrollee(self): + self.device.autoconnect = True + self.hapd.reload() + + ctx.start_process(['iwctl', 'dpp', self.device.name, 'start-enrollee'], check=True) + + dpp = DeviceProvisioning(self.device.device_path) + + self.wpas.dpp_configurator_create(dpp.uri) + self.wpas.dpp_configurator_start('ssidCCMP', 'secret123') + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) + def setUp(self): self.wpas = Wpas('wpas.conf') self.wd = IWD(True) diff --git a/autotests/testEAP-WPS/four_digit_pin_test.py b/autotests/testEAP-WPS/four_digit_pin_test.py @@ -4,22 +4,23 @@ import unittest import sys sys.path.append('../util') -import iwd from iwd import IWD -from iwd import DeviceState - from hostapd import HostapdCLI +from config import ctx class Test(unittest.TestCase): - def four_digit_pin_success(self, wd): + def four_digit_pin_success(self, wd, client=False): devices = wd.list_devices(1) device = devices[0] pin = '1234' self.hostapd.wps_pin(pin) - device.wps_start_pin(pin) + if not client: + device.wps_start_pin(pin) + else: + ctx.start_process(['iwctl', 'wsc', device.name, 'start-user-pin', pin], check=True) condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) @@ -36,6 +37,11 @@ class Test(unittest.TestCase): self.four_digit_pin_success(wd) + def test_client_four_digit_pin(self): + wd = IWD(True) + + self.four_digit_pin_success(wd, client=True) + @classmethod def setUpClass(cls): cls.hostapd = HostapdCLI(config='ssidWPS.conf') diff --git a/autotests/testEAP-WPS/push_button_test.py b/autotests/testEAP-WPS/push_button_test.py @@ -4,20 +4,22 @@ import unittest import sys sys.path.append('../util') -import iwd from iwd import IWD -from iwd import DeviceState - from hostapd import HostapdCLI +from config import ctx + class Test(unittest.TestCase): - def push_button_success(self, wd): + def push_button_success(self, wd, client=False): self.hostapd.wps_push_button() devices = wd.list_devices(1) device = devices[0] - device.wps_push_button() + if not client: + device.wps_push_button() + else: + ctx.start_process(['iwctl', 'wsc', device.name, 'push-button'], check=True) condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) @@ -34,6 +36,11 @@ class Test(unittest.TestCase): self.push_button_success(wd) + def test_client_push_button(self): + wd = IWD(True) + + self.push_button_success(wd, client=True) + @classmethod def setUpClass(cls): cls.hostapd = HostapdCLI(config='ssidWPS.conf') diff --git a/autotests/testEncryptedProfiles/connection_test.py b/autotests/testEncryptedProfiles/connection_test.py @@ -6,6 +6,7 @@ import sys sys.path.append('../util') import iwd import os +from time import sleep from iwd import IWD from iwd import NetworkType from iwd import PSKAgent @@ -48,6 +49,8 @@ class Test(unittest.TestCase): mtime = os.path.getmtime('/tmp/iwd/' + 'ssidCCMP.psk') self.assertFalse(self.profile_is_encrypted('ssidCCMP.psk')) + sleep(1) + wd = IWD(True) # Make sure profile was accepted @@ -115,6 +118,12 @@ EncryptedSecurity=aabbccddeeff00112233445566778899 self.assertEqual(wd.list_known_networks(), []) + # This test starts and stops IWD so quickly the DBus utilities don't + # even have a chance to set up the Device interface object which causes + # exceptions on the next test as the InterfaceAdded signals arrive. This + # allows the device interface to get set up before ending the test. + wd.list_devices(1) + def test_runtime_profile(self): wd = IWD(True) diff --git a/autotests/testHiddenNetworks/exceptions_test.py b/autotests/testHiddenNetworks/exceptions_test.py @@ -6,7 +6,7 @@ import sys sys.path.append('../util') import iwd import validation -from validation import TestConnectAutoConnect +from validation import TestHiddenNetworks from iwd import IWD class TestWpaNetwork(unittest.TestCase): @@ -23,7 +23,7 @@ class TestWpaNetwork(unittest.TestCase): ''' def test_wpa(self): - tca = TestConnectAutoConnect() + tca = TestHiddenNetworks() tca.validate('UnExistingNetwork', False, iwd.NotFoundEx) tca.validate('ssidOverlap', False, iwd.ServiceSetOverlapEx) diff --git a/autotests/testHiddenNetworks/open_network_test.py b/autotests/testHiddenNetworks/open_network_test.py @@ -6,7 +6,7 @@ import sys sys.path.append('../util') import iwd import validation -from validation import TestConnectAutoConnect +from validation import TestHiddenNetworks from iwd import IWD class TestOpenNetwork(unittest.TestCase): @@ -20,7 +20,7 @@ class TestOpenNetwork(unittest.TestCase): True True Connection succeeds ''' def test_open(self): - tca = TestConnectAutoConnect() + tca = TestHiddenNetworks() tca.validate('ssidHiddenOpen', False) tca.validate('ssidHiddenOpen', True) diff --git a/autotests/testHiddenNetworks/validation.py b/autotests/testHiddenNetworks/validation.py @@ -9,7 +9,7 @@ from iwd import IWD from iwd import PSKAgent from iwd import NetworkType -class TestConnectAutoConnect(unittest.TestCase): +class TestHiddenNetworks(unittest.TestCase): def check_connect_hidden_network(self, wd, device, ssid, throws): if not throws is None: diff --git a/autotests/testHiddenNetworks/wpa_network_test.py b/autotests/testHiddenNetworks/wpa_network_test.py @@ -6,7 +6,7 @@ import sys sys.path.append('../util') import iwd import validation -from validation import TestConnectAutoConnect +from validation import TestHiddenNetworks from iwd import IWD class TestWpaNetwork(unittest.TestCase): @@ -21,7 +21,7 @@ class TestWpaNetwork(unittest.TestCase): ''' def test_wpa(self): - tca = TestConnectAutoConnect() + tca = TestHiddenNetworks() tca.validate('ssidHiddenWPA', False, None, True) tca.validate('ssidHiddenWPA', True, None, True) diff --git a/autotests/testKnownNetworks/known_network_test.py b/autotests/testKnownNetworks/known_network_test.py @@ -2,10 +2,11 @@ import unittest import sys +import subprocess sys.path.append('../util') -import iwd from iwd import IWD +from config import ctx class Test(unittest.TestCase): @@ -70,8 +71,26 @@ class Test(unittest.TestCase): self.list_removal_and_addition(wd) + def test_client_known_networks(self): + networks = ['Hotspot Network', 'ssidOpen', 'ssidTKIP', 'ssidEAP-TLS'] + wd = IWD(True) + + iwctl = ctx.start_process(['iwctl', 'known-networks', 'list'], check=True) + + for n in networks: + self.assertIn(n, iwctl.out) + + for n in networks: + ctx.start_process(['iwctl', 'known-networks', n, 'show'], check=True) + + networks.remove('ssidOpen') + ctx.start_process(['iwctl', 'known-networks', 'ssidOpen', 'forget'], check=True) + + with self.assertRaises(subprocess.CalledProcessError): + ctx.start_process(['iwctl', 'known-networks', 'ssidOpen', 'show'], check=True) + @classmethod - def setUpClass(cls): + def setUp(self): IWD.copy_to_storage('known_networks/ssidOpen.open') IWD.copy_to_storage('known_networks/ssidTKIP.psk') IWD.copy_to_storage('known_networks/ssidEAP-TLS.8021x') diff --git a/autotests/testNetconfig/ap-main.conf b/autotests/testNetconfig/ap-main.conf @@ -0,0 +1,7 @@ +hw_mode=g +channel=1 +ssid=ap-main + +wpa=1 +wpa_pairwise=TKIP +wpa_passphrase=secret123 diff --git a/autotests/testNetconfig/ap-ns1.conf b/autotests/testNetconfig/ap-ns1.conf @@ -0,0 +1,7 @@ +hw_mode=g +channel=1 +ssid=ap-ns1 + +wpa=1 +wpa_pairwise=TKIP +wpa_passphrase=secret123 diff --git a/autotests/testNetconfig/auto.psk b/autotests/testNetconfig/auto.psk @@ -0,0 +1,5 @@ +[IPv4] +SendHostname=true + +[Settings] +AutoConnect=false diff --git a/autotests/testNetconfig/connection_test.py b/autotests/testNetconfig/connection_test.py @@ -11,21 +11,33 @@ from iwd import NetworkType from hostapd import HostapdCLI import testutil from config import ctx -import os, time -import subprocess +import os +import socket +import datetime, time 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) + # DHCPv6 addresses always have a prefix length of 128 bits, the actual + # subnet's prefix length is in the route. + testutil.test_ip_address_match(device.name, '3ffe:501:ffff:100::1', 128, 112) except: return False return True + def get_ll_addrs6(ns, ifname): + show_ip = ns.start_process(['ip', 'addr', 'show', ifname]) + show_ip.wait() + for l in show_ip.out.split('\n'): + if 'inet6 fe80::' in l: + return socket.inet_pton(socket.AF_INET6, l.split(None, 1)[1].split('/', 1)[0]) + return None + + os.system("hostname test-sta") + IWD.copy_to_storage('auto.psk', name='ap-ns1.psk') wd = IWD(True) psk_agent = PSKAgent("secret123") @@ -34,7 +46,7 @@ class Test(unittest.TestCase): devices = wd.list_devices(1) device = devices[0] - ordered_network = device.get_ordered_network('ssidTKIP') + ordered_network = device.get_ordered_network('ap-ns1') self.assertEqual(ordered_network.type, NetworkType.psk) @@ -45,13 +57,121 @@ class Test(unittest.TestCase): condition = 'obj.state == DeviceState.connected' wd.wait_for_object_condition(device, condition) + connect_time = time.time() testutil.test_iface_operstate() - testutil.test_ifaces_connected() + testutil.test_ip_address_match(device.name, '192.168.1.10', 17, 24) ctx.non_block_wait(check_addr, 10, device, exception=Exception("IPv6 address was not set")) + # Cannot use test_ifaces_connected() across namespaces (implementation details) + testutil.test_ip_connected(('192.168.1.10', ctx), ('192.168.1.1', self.ns1)) + + ifname = str(device.name) + router_ll_addr = get_ll_addrs6(self.ns1, self.hapd.ifname) + # Since we're in an isolated VM with freshly created interfaces we know any routes + # will have been created by IWD and we don't have to allow for pre-existing routes + # in the table. + # Flags: 1=RTF_UP, 2=RTF_GATEWAY + expected_routes4 = { + testutil.RouteInfo(gw=socket.inet_pton(socket.AF_INET, '192.168.1.1'), + flags=3, ifname=ifname), + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET, '192.168.0.0'), plen=17, + flags=1, ifname=ifname) + } + expected_routes6 = { + # Default router + testutil.RouteInfo(gw=router_ll_addr, flags=3, ifname=ifname), + # On-link prefix + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:100::'), plen=72, + flags=1, ifname=ifname), + # Router for an off-link prefix, medium preference + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:300::'), plen=64, + gw=router_ll_addr, flags=3, ifname=ifname), + # Router for an off-link prefix, high preference + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:400::'), plen=65, + gw=router_ll_addr, flags=3, ifname=ifname), + # Router for an off-link prefix, low preference + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:500::'), plen=66, + gw=router_ll_addr, flags=3, ifname=ifname) + } + self.maxDiff = None + self.assertEqual(expected_routes4, set(testutil.get_routes4(ifname))) + self.assertEqual(expected_routes6, set(testutil.get_routes6(ifname))) + + rclog = open('/tmp/resolvconf.log', 'r') + entries = rclog.readlines() + rclog.close() + expected_rclog = ['-a %s.dns\n' % ifname, 'nameserver 192.168.1.2\n', 'nameserver 3ffe:501:ffff:100::2\n'] + # Every real resolvconf -a run overwrites the previous settings. Check the last three lines + # of our log since we care about the end result here. + self.assertEqual(expected_rclog, entries[-3:]) + + leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) + lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] + self.assertEqual(lease['state'], 'active') + self.assertEqual(lease['client-hostname'], 'test-sta') + self.assertTrue(lease['starts'] < connect_time) + self.assertTrue(lease['ends'] > connect_time) + # The T1 is 15 seconds per dhcpd.conf. This is the approximate interval between lease + # renewals we should see from the client (+/- 1 second + some jitter). Wait a little + # less than twice that time (25s) so that we can expect the lease was renewed strictly + # once (not 0 or 2 times) by that time, check that the lease timestamps have changed by + # at least 10s so as to leave a lot of margin. + renew_time = lease['starts'] + 15 + now = time.time() + ctx.non_block_wait(lambda: False, renew_time + 10 - now, exception=False) + + leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) + new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] + self.assertEqual(new_lease['state'], 'active') + self.assertEqual(new_lease['client-hostname'], 'test-sta') + self.assertTrue(new_lease['starts'] > lease['starts'] + 10) + self.assertTrue(new_lease['starts'] < lease['starts'] + 25) + self.assertTrue(new_lease['ends'] > lease['ends'] + 10) + self.assertTrue(new_lease['ends'] < lease['ends'] + 25) + + # Now wait another T1 seconds but don't let our DHCP client get its REQUEST out this + # time so as to test renew timeouts and resends. The retry interval is 60 seconds + # since (T2 - T1) / 2 is shorter than 60s. It is now about 10s since the last + # renewal or 5s before the next DHCPREQUEST frame that is going to be lost. We'll + # wait T1 seconds, so until about 10s after the failed attempt, we'll check that + # there was no renewal by that time, just in case, and we'll reenable frame delivery. + # We'll then wait another 60s and we should see the lease has been successfully + # renewed some 10 seconds earlier on the 1st DHCPREQUEST retransmission. + # + # We can't use hswim to block the frames from reaching the AP because we'd lose + # beacons and get disconnected. We also can't drop our subnet route or IP address + # because IWD's sendto() call would synchronously error out and the DHCP client + # would just give up. Add a false route to break routing to 192.168.1.1 and delete + # it afterwards. + os.system('ip route add 192.168.1.1/32 dev ' + ifname + ' via 192.168.1.100 preference 0') + + lease = new_lease + renew_time = lease['starts'] + 15 + now = time.time() + ctx.non_block_wait(lambda: False, renew_time + 10 - now, exception=False) + + leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) + new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] + self.assertEqual(new_lease['starts'], lease['starts']) + + os.system('ip route del 192.168.1.1/32 dev ' + ifname + ' via 192.168.1.100 preference 0') + + retry_time = lease['starts'] + 75 + now = time.time() + ctx.non_block_wait(lambda: False, retry_time + 10 - now, exception=False) + + leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) + new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] + self.assertEqual(new_lease['state'], 'active') + self.assertEqual(lease['client-hostname'], 'test-sta') + self.assertTrue(new_lease['starts'] > lease['starts'] + 70) + self.assertTrue(new_lease['starts'] < lease['starts'] + 85) + self.assertTrue(new_lease['ends'] > lease['ends'] + 70) + self.assertTrue(new_lease['ends'] < lease['ends'] + 85) + device.disconnect() condition = 'not obj.connected' @@ -74,40 +194,130 @@ class Test(unittest.TestCase): except: pass - hapd = HostapdCLI() + cls.ns1 = ctx.get_namespace('ns1') + cls.hapd = HostapdCLI('ap-ns1.conf') # 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', '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', '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', - hapd.ifname], cleanup=remove_lease6) - ctx.start_process(['sysctl', 'net.ipv6.conf.' + hapd.ifname + '.forwarding=1']).wait() - # Tell clients to use DHCPv6 + cls.ns1.start_process(['ip', 'addr','add', '192.168.1.1/17', + 'dev', cls.hapd.ifname]).wait() + cls.ns1.start_process(['touch', '/tmp/dhcpd.leases']).wait() + cls.dhcpd_pid = cls.ns1.start_process(['dhcpd', '-f', '-d', '-cf', '/tmp/dhcpd.conf', + '-lf', '/tmp/dhcpd.leases', + cls.hapd.ifname], cleanup=remove_lease4) + + cls.ns1.start_process(['ip', 'addr', 'add', '3ffe:501:ffff:100::1/72', + 'dev', cls.hapd.ifname]).wait() + cls.ns1.start_process(['touch', '/tmp/dhcpd6.leases']).wait() + cls.dhcpd6_pid = cls.ns1.start_process(['dhcpd', '-6', '-f', '-d', + '-cf', '/tmp/dhcpd-v6.conf', + '-lf', '/tmp/dhcpd6.leases', + cls.hapd.ifname], cleanup=remove_lease6) + cls.ns1.start_process(['sysctl', + 'net.ipv6.conf.' + cls.hapd.ifname + '.forwarding=1']).wait() + # Send out Router Advertisements telling clients to use DHCPv6. + # Note trying to send the RAs from the router's global IPv6 address by adding a + # "AdvRASrcAddress { 3ffe:501:ffff:100::1; };" line will fail because the client + # and the router interfaces are in the same namespace and Linux won't allow routes + # with a non-link-local gateway address that is present on another interface in the + # same namespace. config = open('/tmp/radvd.conf', 'w') - config.write('interface ' + hapd.ifname + ' { AdvSendAdvert on; AdvManagedFlag on; };') + config.write('interface ' + cls.hapd.ifname + ''' { + AdvSendAdvert on; + AdvManagedFlag on; + prefix 3ffe:501:ffff:100::/72 { AdvAutonomous off; }; + route 3ffe:501:ffff:300::/64 {}; + route 3ffe:501:ffff:400::/65 { AdvRoutePreference low; }; + route 3ffe:501:ffff:500::/66 { AdvRoutePreference high; }; + };''') config.close() - cls.radvd_pid = ctx.start_process(['radvd', '-n', '-d5', '-p', '/tmp/radvd.pid', '-C', '/tmp/radvd.conf']) + cls.radvd_pid = cls.ns1.start_process(['radvd', '-n', '-d5', + '-p', '/tmp/radvd.pid', '-C', '/tmp/radvd.conf']) + + cls.orig_path = os.environ['PATH'] + os.environ['PATH'] = '/tmp/test-bin:' + os.environ['PATH'] + IWD.copy_to_storage('resolvconf', '/tmp/test-bin') @classmethod def tearDownClass(cls): IWD.clear_storage() - ctx.stop_process(cls.dhcpd_pid) + cls.ns1.stop_process(cls.dhcpd_pid) cls.dhcpd_pid = None - ctx.stop_process(cls.dhcpd6_pid) + cls.ns1.stop_process(cls.dhcpd6_pid) cls.dhcpd6_pid = None - ctx.stop_process(cls.radvd_pid) + cls.ns1.stop_process(cls.radvd_pid) cls.radvd_pid = None - os.remove('/tmp/radvd.conf') + os.system('rm -rf /tmp/radvd.conf /tmp/resolvconf.log /tmp/test-bin') + os.environ['PATH'] = cls.orig_path + + @staticmethod + def parse_lease_file(path, family): + file = open(path, 'r') + lines = file.readlines() + file.close() + + stack = [[]] + statement = [] + token = '' + for line in lines: + whitespace = False + quote = False + for ch in line: + if not quote and ch in ' \t\r\n;{}=#': + if len(token): + statement.append(token) + token = '' + if not quote and ch in ';{}': + if len(statement): + stack[-1].append(statement) + statement = [] + if ch == '"': + quote = not quote + elif quote or ch not in ' \t\r\n;{}#': + token += ch + if ch == '#': + break + elif ch == '{': + stack.append([]) + elif ch == '}': + statements = stack.pop() + stack[-1][-1].append(statements) + if len(token): + statement.append(token) + token = '' + if len(statement): + stack[-1].append(statement) + statements = stack.pop(0) + if len(stack): + raise Exception('Unclosed block(s)') + + contents = {'leases':{}} + for s in statements: + if s[0] == 'lease': + ip = socket.inet_pton(family, s[1]) + lease = {} + for param in s[2]: + if param[0] in ('starts', 'ends', 'tstp', 'tsfp', 'atsfp', 'cltt'): + weekday = param[1] + year, month, day = param[2].split('/') + hour, minute, second = param[3].split(':') + dt = datetime.datetime( + int(year), int(month), int(day), + int(hour), int(minute), int(second), + tzinfo=datetime.timezone.utc) + lease[param[0]] = dt.timestamp() + elif param[0:2] == ['binding', 'state']: + lease['state'] = param[2] + elif param[0:2] == ['hardware', 'ethernet']: + lease['hwaddr'] = bytes([int(v, 16) for v in param[2].split(':')]) + elif param[0] in ('preferred-life', 'max-life'): + lease[param[0]] = int(param[1]) + elif param[0] in ('client-hostname'): + lease[param[0]] = param[1] + contents['leases'][ip] = lease # New entries overwrite older ones + elif s[0] == 'server-duid': + contents[s[0]] = s[1] + return contents if __name__ == '__main__': unittest.main(exit=True) diff --git a/autotests/testNetconfig/dhcpd-v6.conf b/autotests/testNetconfig/dhcpd-v6.conf @@ -1,6 +1,6 @@ -subnet6 3ffe:501:ffff:100::/64 +subnet6 3ffe:501:ffff:100::/72 { - option dhcp6.name-servers 3ffe:501:ffff:100::1; + option dhcp6.name-servers 3ffe:501:ffff:100::2; range6 3ffe:501:ffff:100::10 3ffe:501:ffff:100::20; range6 3ffe:501:ffff:100::100 3ffe:501:ffff:100::200; } diff --git a/autotests/testNetconfig/dhcpd.conf b/autotests/testNetconfig/dhcpd.conf @@ -1,15 +1,25 @@ -default-lease-time 600; # 10 minutes -max-lease-time 7200; # 2 hours +default-lease-time 120; # 2 minutes +min-lease-time 120; # 2 minutes +max-lease-time 120; # 2 minutes +option dhcp-renewal-time 15; # 15 secs for T1 +# We set a relatively low lease lifetime of 2 minutes but our renewal interval +# (T1) is still unproportionally low to speed the test up -- 12% instead of the +# default 50% lifetime value. We need a lifetime in the order of minutes +# because minimum lease renewal retry interval is 60s per spec. However by +# default dhcpd will not renew leases that are newer than 25% their lifetime. +# Set that threshold to 1% so that we can verify that the lease is renewed +# without waiting too long. +dhcp-cache-threshold 1; -option broadcast-address 192.168.1.255; +option broadcast-address 192.168.127.255; option routers 192.168.1.254; -option subnet-mask 255.255.255.0; +option subnet-mask 255.255.128.0; -subnet 192.168.1.0 netmask 255.255.255.0 +subnet 192.168.0.0 netmask 255.255.128.0 { option routers 192.168.1.1; - option subnet-mask 255.255.255.0; - option domain-name-servers 192.168.1.1; + option subnet-mask 255.255.128.0; + option domain-name-servers 192.168.1.2; range 192.168.1.10 192.168.1.20; range 192.168.1.100 192.168.1.200; } diff --git a/autotests/testNetconfig/hw.conf b/autotests/testNetconfig/hw.conf @@ -1,9 +1,11 @@ [SETUP] -num_radios=3 +num_radios=4 start_iwd=0 [HOSTAPD] -rad0=ssidTKIP.conf +rad2=ap-main.conf +rad3=ap-ns1.conf [NameSpaces] -ns0=rad2 +ns0=rad0 +ns1=rad3 diff --git a/autotests/testNetconfig/main.conf b/autotests/testNetconfig/main.conf @@ -3,4 +3,4 @@ EnableNetworkConfiguration=true [Network] EnableIPv6=true -NameResolvingService=none +NameResolvingService=resolvconf diff --git a/autotests/testNetconfig/resolvconf b/autotests/testNetconfig/resolvconf @@ -0,0 +1,2 @@ +#! /bin/sh +(echo "$*" ; [ "$1" = -a ] && cat) >> /tmp/resolvconf.log 2> /dev/null diff --git a/autotests/testNetconfig/ssidTKIP.conf b/autotests/testNetconfig/ssidTKIP.conf @@ -1,7 +0,0 @@ -hw_mode=g -channel=1 -ssid=ssidTKIP - -wpa=1 -wpa_pairwise=TKIP -wpa_passphrase=secret123 diff --git a/autotests/testNetconfig/ssidTKIP.psk b/autotests/testNetconfig/ssidTKIP.psk @@ -1,6 +0,0 @@ -[IPv4] -Address=192.168.1.10 -Gateway=192.168.1.1 - -[Settings] -AutoConnect=false diff --git a/autotests/testNetconfig/static.psk b/autotests/testNetconfig/static.psk @@ -0,0 +1,16 @@ +[IPv4] +# Use a different netmask than DHCP on purpose, but use the same address +# as DHCP would assign us to produce a conflict and test ACD +Address=192.168.1.10 +Netmask=255.255.255.128 +Gateway=192.168.1.3 +DNS=192.168.1.4 + +[IPv6] +# Use a different subnet than DHCP on purpose +Address=3ffe:501:ffff:200::10/80 +Gateway=3ffe:501:ffff:200::3 +DNS=3ffe:501:ffff:200::4 + +[Settings] +AutoConnect=false diff --git a/autotests/testNetconfig/static_test.py b/autotests/testNetconfig/static_test.py @@ -12,10 +12,12 @@ from hostapd import HostapdCLI import testutil from config import ctx import os +import socket class Test(unittest.TestCase): def test_connection_success(self): + # Use a non-default storage_dir for one of the instances, the default for the other one wd = IWD(True, iwd_storage_dir='/tmp/storage') ns0 = ctx.get_namespace('ns0') @@ -30,7 +32,7 @@ class Test(unittest.TestCase): dev1 = wd.list_devices(1)[0] dev2 = wd_ns0.list_devices(1)[0] - ordered_network = dev1.get_ordered_network('ssidTKIP') + ordered_network = dev1.get_ordered_network('ap-main') self.assertEqual(ordered_network.type, NetworkType.psk) @@ -45,20 +47,58 @@ class Test(unittest.TestCase): testutil.test_iface_operstate() testutil.test_ifaces_connected() - testutil.test_ip_address_match(dev1.name, '192.168.1.10') - - ordered_network = dev2.get_ordered_network('ssidTKIP') + testutil.test_ip_address_match(dev1.name, '192.168.1.10', 25) + testutil.test_ip_address_match(dev1.name, '3ffe:501:ffff:200::10', 80) + + ifname = str(dev1.name) + # Since we're in an isolated VM with freshly created interfaces we know any routes + # will have been created by IWD and don't have to allow for pre-existing routes + # in the table. + # Flags: 1=RTF_UP, 2=RTF_GATEWAY + expected_routes4 = { + testutil.RouteInfo(gw=socket.inet_pton(socket.AF_INET, '192.168.1.3'), + flags=3, ifname=ifname), + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET, '192.168.1.0'), plen=25, + flags=1, ifname=ifname) + } + expected_routes6 = { + testutil.RouteInfo(gw=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:200::3'), + flags=3, ifname=ifname), + testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:200::'), plen=80, + flags=1, ifname=ifname), + } + + self.maxDiff = None + self.assertEqual(expected_routes4, set(testutil.get_routes4(ifname))) + self.assertEqual(expected_routes6, set(testutil.get_routes6(ifname))) + + rclog = open('/tmp/resolvconf.log', 'r') + entries = rclog.readlines() + rclog.close() + expected_rclog = ['-a %s.dns\n' % ifname, 'nameserver 192.168.1.4\n', 'nameserver 3ffe:501:ffff:200::4\n'] + # Every resolvconf -a run overwrites the previous settings. Check the last three lines + # of the log since we care about the end result here. + self.assertEqual(expected_rclog, entries[-3:]) + + ordered_network = dev2.get_ordered_network('ap-main') condition = 'not obj.connected' wd_ns0.wait_for_object_condition(ordered_network.network_object, condition) + # Connect to the same network from a dynamically configured client. The + # DHCP server doesn't know (even though dev1 announced itself) that + # 192.168.1.10 is already in use and if it assigns dev2 the lowest + # available address, that's going to be 192.168.1.10. dev1's ACD + # implementation should then stop using this address. ordered_network.network_object.connect() condition = 'obj.state == DeviceState.connected' wd_ns0.wait_for_object_condition(dev2, condition) wd.wait(1) - testutil.test_ip_address_match(dev1.name, None) + # Check dev1 is now disconnected or without its IPv4 address + if dev1.state == iwd.DeviceState.connected: + testutil.test_ip_address_match(dev1.name, None) dev1.disconnect() dev2.disconnect() @@ -77,22 +117,27 @@ class Test(unittest.TestCase): except: pass - hapd = HostapdCLI() + hapd = HostapdCLI('ap-main.conf') # TODO: This could be moved into test-runner itself if other tests ever - # require this functionality (p2p, FILS, etc.). Since its simple + # require this functionality (p2p, FILS, etc.). Since it's simple # enough it can stay here for now. - ctx.start_process(['ip', 'addr','add', '192.168.1.1/255.255.255.0', + ctx.start_process(['ip', 'addr','add', '192.168.1.1/255.255.128.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_lease) - IWD.copy_to_storage('ssidTKIP.psk', '/tmp/storage') + IWD.copy_to_storage('static.psk', '/tmp/storage', 'ap-main.psk') + + cls.orig_path = os.environ['PATH'] + os.environ['PATH'] = '/tmp/test-bin:' + os.environ['PATH'] + IWD.copy_to_storage('resolvconf', '/tmp/test-bin') @classmethod def tearDownClass(cls): - IWD.clear_storage() cls.dhcpd_pid.kill() + os.system('rm -rf /tmp/resolvconf.log /tmp/test-bin /tmp/storage') + os.environ['PATH'] = cls.orig_path if __name__ == '__main__': unittest.main(exit=True) diff --git a/autotests/testNetconfig/storage/ssidTKIP.psk b/autotests/testNetconfig/storage/ssidTKIP.psk @@ -1,3 +0,0 @@ -[IPv4] -Address=192.168.1.10 -Gateway=192.168.1.1 diff --git a/autotests/testP2P/connection_test.py b/autotests/testP2P/connection_test.py @@ -87,7 +87,12 @@ class Test(unittest.TestCase): # For some reason wpa_supplicant's newly created P2P-client interface doesn't inherit # the settings from the main interface which were loaded from the config file # (P2P-device and P2P-GO interfaces do), we need to set config_methods again. + # + # Additionally since hostap commit 922fa099721903b106a7bc1ccd1ffe8c4a7bce69, + # just setting config_methods to the same value we used last time is detected as + # a NOOP so we need to set it to a different value first for it to take effect. peer_ifname = 'p2p-' + wpas.interface.name + '-0' + wpas.set('config_methods', '', ifname=peer_ifname) wpas.set('config_methods', wpas.config['config_methods'], ifname=peer_ifname) wpas.set('device_name', wpas.config['device_name'], ifname=peer_ifname) wpas.set('device_type', wpas.config['device_type'], ifname=peer_ifname) diff --git a/autotests/testWPA2-ext-key-id/connection_test.py b/autotests/testWPA2-ext-key-id/connection_test.py @@ -50,8 +50,6 @@ 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 @@ -33,7 +33,7 @@ class HostapdCLI(object): _instances = WeakValueDictionary() def __new__(cls, config=None, *args, **kwargs): - hapd = ctx.hostapd[config] + hapd = ctx.get_hapd_instance(config) if not config: config = hapd.config @@ -58,10 +58,10 @@ class HostapdCLI(object): if not ctx.hostapd: raise Exception("No hostapd instances are configured") - if not config and len(ctx.hostapd.instances) > 1: + if not config and sum([len(hapd.instances) for hapd in ctx.hostapd]) > 1: raise Exception('config must be provided if more than one hostapd instance exists') - hapd = ctx.hostapd[config] + hapd = ctx.get_hapd_instance(config) self.interface = hapd.intf self.config = hapd.config @@ -102,23 +102,26 @@ class HostapdCLI(object): return True - def _poll_event(self, event): + def _poll_event(self, event, disallow): # 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): + for d in disallow: + if d in e: + raise Exception('Event %s found while waiting for %s' % (d, event)) if event in e: self.events = self.events[:idx] return e return False - def wait_for_event(self, event, timeout=10): + def wait_for_event(self, event, timeout=10, disallow=[]): if event == 'AP-ENABLED': if self.enabled: return 'AP-ENABLED' - return ctx.non_block_wait(self._poll_event, timeout, event, + return ctx.non_block_wait(self._poll_event, timeout, event, disallow, exception=TimeoutError("waiting for event")) def _data_available(self): @@ -166,8 +169,8 @@ class HostapdCLI(object): self.events = [] cmd = 'EAPOL_REAUTH ' + client_address self.ctrl_sock.sendall(cmd.encode('utf-8')) - self.wait_for_event('CTRL-EVENT-EAP-STARTED') - self.wait_for_event('CTRL-EVENT-EAP-SUCCESS') + self.wait_for_event('CTRL-EVENT-EAP-STARTED', disallow=['AP-STA-DISCONNECTED']) + self.wait_for_event('CTRL-EVENT-EAP-SUCCESS', disallow=['AP-STA-DISCONNECTED']) def reload(self): # Seemingly all three commands needed for the instance to notice @@ -234,7 +237,8 @@ class HostapdCLI(object): if address: cmd = 'REKEY_PTK %s' % address self.ctrl_sock.sendall(cmd.encode('utf-8')) - self.wait_for_event('EAPOL-4WAY-HS-COMPLETED') + self.events = [] + self.wait_for_event('EAPOL-4WAY-HS-COMPLETED', disallow=['AP-STA-DISCONNECTED']) return cmd = 'REKEY_GTK' diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -287,6 +287,18 @@ class DeviceProvisioning(IWDDBusAbstract): def stop(self): self._iface.Stop() + @property + def uri(self): + return self._properties['URI'] + + @property + def started(self): + return self._properties['Started'] + + @property + def role(self): + return self._properties['Role'] + class Device(IWDDBusAbstract): ''' Class represents a network device object: net.connman.iwd.Device @@ -858,10 +870,11 @@ class PSKAgent(dbus.service.Object): users = [users] self.users = users self._path = '/test/agent/%s' % agent_count + self._bus = dbus.bus.BusConnection(address_or_type=namespace.dbus_address) agent_count += 1 - dbus.service.Object.__init__(self, namespace.get_bus(), self._path) + dbus.service.Object.__init__(self, self._bus, self._path) @property def path(self): @@ -1079,14 +1092,13 @@ class IWD(AsyncOpAbstract): start_iwd_daemon=True) ''' _object_manager_if = None - _agent_manager_if = None _iwd_proc = None _devices = None _default_instance = None - psk_agent = None + psk_agents = [] def __init__(self, start_iwd_daemon = False, iwd_config_dir = '/tmp', - iwd_storage_dir = '/tmp/iwd', namespace=ctx): + iwd_storage_dir = IWD_STORAGE_DIR, namespace=ctx): self.namespace = namespace self._bus = namespace.get_bus() @@ -1097,9 +1109,6 @@ class IWD(AsyncOpAbstract): self._iwd_proc = self.namespace.start_iwd(iwd_config_dir, iwd_storage_dir) - ctx.non_block_wait(self._bus.name_has_owner, 20, IWD_SERVICE, - exception=TimeoutError('IWD has failed to start')) - self._devices = DeviceList(self) # Weak to make sure the test's reference to @self is the only counted @@ -1110,11 +1119,12 @@ class IWD(AsyncOpAbstract): IWD._default_instance = weakref.ref(self) def __del__(self): - if self.psk_agent: - self.unregister_psk_agent(self.psk_agent) + for agent in self.psk_agents: + self.unregister_psk_agent(agent) + + self.psk_agents = [] self._object_manager_if = None - self._agent_manager_if = None self._known_networks = None self._devices = None @@ -1133,15 +1143,6 @@ class IWD(AsyncOpAbstract): DBUS_OBJECT_MANAGER) return self._object_manager_if - @property - def _agent_manager(self): - if self._agent_manager_if is None: - self._agent_manager_if =\ - dbus.Interface(self._bus.get_object(IWD_SERVICE, - IWD_AGENT_MANAGER_PATH), - IWD_AGENT_MANAGER_INTERFACE) - return self._agent_manager_if - @staticmethod def _wait_for_object_condition(obj, condition_str, max_wait = 50): def _eval_wrap(obj, condition_str): @@ -1197,40 +1198,49 @@ class IWD(AsyncOpAbstract): os.system('rm -rf ' + storage_dir + '/ap/*') @staticmethod - def create_in_storage(file_name, file_content): - fo = open(IWD_STORAGE_DIR + '/' + file_name, 'w') + def create_in_storage(file_name, file_content, storage_dir=IWD_STORAGE_DIR): + fo = open(storage_dir + '/' + file_name, 'w') fo.write(file_content) fo.close() @staticmethod + def _ensure_storage_dir_exists(storage_dir): + if not os.path.exists(storage_dir): + os.mkdir(storage_dir) + + @staticmethod def copy_to_storage(source, storage_dir=IWD_STORAGE_DIR, name=None): import shutil assert not os.path.isabs(source) + target = storage_dir if name: - storage_dir += '/%s' % name + target += '/%s' % name - shutil.copy(source, storage_dir) + IWD._ensure_storage_dir_exists(storage_dir) + shutil.copy(source, target) @staticmethod - def copy_to_hotspot(source): - if not os.path.exists(IWD_STORAGE_DIR + "/hotspot"): - os.mkdir(IWD_STORAGE_DIR + "/hotspot") + def copy_to_hotspot(source, storage_dir=IWD_STORAGE_DIR): + IWD._ensure_storage_dir_exists(storage_dir) - IWD.copy_to_storage(source, IWD_STORAGE_DIR + "/hotspot") + if not os.path.exists(storage_dir + "/hotspot"): + os.mkdir(storage_dir + "/hotspot") + + IWD.copy_to_storage(source, storage_dir + "/hotspot") @staticmethod - def copy_to_ap(source): - if not os.path.exists(IWD_STORAGE_DIR + "/ap"): - os.mkdir(IWD_STORAGE_DIR + "/ap") + def copy_to_ap(source, storage_dir=IWD_STORAGE_DIR): + if not os.path.exists(storage_dir + "/ap"): + os.mkdir(storage_dir + "/ap") - IWD.copy_to_storage(source, IWD_STORAGE_DIR + '/ap/') + IWD.copy_to_storage(source, storage_dir + '/ap/') @staticmethod - def remove_from_storage(file_name): - os.system('rm -rf ' + IWD_STORAGE_DIR + '/\'' + file_name + '\'') + def remove_from_storage(file_name, storage_dir=IWD_STORAGE_DIR): + os.system('rm -rf ' + storage_dir + '/\'' + file_name + '\'') def list_devices(self, wait_to_appear = 0, max_wait = 50, p2p = False): if not wait_to_appear: @@ -1258,22 +1268,27 @@ class IWD(AsyncOpAbstract): return known_network_list def register_psk_agent(self, psk_agent): - self._agent_manager.RegisterAgent( - psk_agent.path, - dbus_interface=IWD_AGENT_MANAGER_INTERFACE, - reply_handler=self._success, - error_handler=self._failure) + iface = dbus.Interface(psk_agent._bus.get_object(IWD_SERVICE, + IWD_AGENT_MANAGER_PATH), + IWD_AGENT_MANAGER_INTERFACE) + iface.RegisterAgent(psk_agent.path, + dbus_interface=IWD_AGENT_MANAGER_INTERFACE, + reply_handler=self._success, + error_handler=self._failure) + self._wait_for_async_op() - self.psk_agent = psk_agent + self.psk_agents.append(psk_agent) def unregister_psk_agent(self, psk_agent): - self._agent_manager.UnregisterAgent( - psk_agent.path, - dbus_interface=IWD_AGENT_MANAGER_INTERFACE, - reply_handler=self._success, - error_handler=self._failure) + iface = dbus.Interface(psk_agent._bus.get_object(IWD_SERVICE, + IWD_AGENT_MANAGER_PATH), + IWD_AGENT_MANAGER_INTERFACE) + iface.UnregisterAgent(psk_agent.path, + dbus_interface=IWD_AGENT_MANAGER_INTERFACE, + reply_handler=self._success, + error_handler=self._failure) self._wait_for_async_op() - self.psk_agent = None + self.psk_agents.remove(psk_agent) @staticmethod def get_instance(): diff --git a/autotests/util/testutil.py b/autotests/util/testutil.py @@ -4,6 +4,8 @@ import socket import fcntl import struct import select +import codecs +import collections import iwd from config import ctx @@ -131,6 +133,7 @@ def test_ifaces_connected(if0=None, if1=None, group=True, expect_fail=False): SIOCGIFFLAGS = 0x8913 SIOCGIFADDR = 0x8915 +SIOCGIFNETMASK = 0x891b IFF_UP = 1 << 0 IFF_RUNNING = 1 << 6 @@ -156,19 +159,68 @@ def test_iface_operstate(intf=None): 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) - addr = fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', intf.encode('utf-8'))) - addr = socket.inet_ntoa(addr[20:24]) - except OSError as e: - if e.errno != 99 or ip != None: - raise Exception('SIOCGIFADDR failed with %d' % e.errno) - - return +def get_addrs6(ifname): + f = open('/proc/net/if_inet6', 'r') + lines = f.readlines() + f.close() + for line in lines: + addr_str, _, plen, _, _, addr_ifname = line.split() + if ifname is not None and addr_ifname != ifname: + continue + + yield (codecs.decode(addr_str, 'hex'), int(plen, 16), addr_ifname) + +def test_ip_address_match(intf, expected_addr_str, expected_plen=None, match_plen=None): + def mask_addr(addr, plen): + if plen is None or len(addr) * 8 <= plen: + return addr + bytelen = int(plen / 8) + return addr[0:bytelen] + bytes([addr[bytelen] & (0xff00 >> (plen & 7))]) + b'\0' * (len(addr) - bytelen - 1) + if expected_addr_str is not None: + try: + expected_addr = socket.inet_pton(socket.AF_INET, expected_addr_str) + family = socket.AF_INET + except OSError as e: + try: + expected_addr = socket.inet_pton(socket.AF_INET6, expected_addr_str) + family = socket.AF_INET6 + except OSError as e2: + raise e2 from None + expected_addr = mask_addr(expected_addr, match_plen) + else: + expected_addr = None + family = socket.AF_INET - if ip != addr: - raise Exception('IP for %s did not match %s (was %s)' % (intf, ip, addr)) + if family == socket.AF_INET: + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + out = fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', intf.encode('utf-8'))) + actual_addr = mask_addr(out[20:24], match_plen) + out = fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, struct.pack('256s', intf.encode('utf-8'))) + actual_plen = sum([sum([(byte >> bit) & 1 for bit in range(0, 8)]) for byte in out[20:24]]) # count bits + except OSError as e: + if e.errno == 99 and expected_addr is None: + return + + raise Exception('SIOCGIFADDR/SIOCGIFNETMASK failed with %d' % e.errno) + else: + # The "get" ioctls don't work for IPv6, netdevice(7) recommends reading /proc/net instead, + # which on the other hand works *only* for IPv6 + actual_addr = None + actual_plen = None + for addr, plen, _ in get_addrs6(intf): + actual_addr = mask_addr(addr, match_plen) + actual_plen = plen + if actual_addr == expected_addr: + break + + if expected_addr != actual_addr: + raise Exception('IP for %s did not match %s (was %s)' % + (intf, expected_addr_str, socket.inet_ntop(family, actual_addr))) + + if expected_plen is not None and expected_plen != actual_plen: + raise Exception('Prefix Length for %s did not match %i (was %i)' % + (intf, expected_plen, actual_plen)) def test_ip_connected(tup0, tup1): ip0, ns0 = tup0 @@ -179,3 +231,59 @@ def test_ip_connected(tup0, tup1): ns1.start_process(['ping', '-c', '5', '-i', '0.2', ip0], check=True) except: raise Exception('Could not ping between %s and %s' % (ip0, ip1)) + +RouteInfo = collections.namedtuple('RouteInfo', 'dst plen gw flags ifname', + defaults=(None, None, None, 0, '')) + +def get_routes4(ifname=None): + f = open('/proc/net/route', 'r') + lines = f.readlines() + f.close() + for line in lines[1:]: # Skip header line + route_ifname, dst_str, gw_str, flags, ref_cnt, use_cnt, metric, mask_str, \ + mtu = line.strip().split(maxsplit=8) + if ifname is not None and route_ifname != ifname: + continue + + dst = codecs.decode(dst_str, 'hex')[::-1] + mask = int(mask_str, 16) + plen = sum([(mask >> bit) & 1 for bit in range(0, 32)]) # count bits + gw = codecs.decode(gw_str, 'hex')[::-1] + + if dst == b'\0\0\0\0': + dst = None + plen = None + if gw == b'\0\0\0\0': + gw = None + yield RouteInfo(dst, plen, gw, int(flags, 16), route_ifname) + +def get_routes6(ifname=None): + f = open('/proc/net/ipv6_route', 'r') + lines = f.readlines() + f.close() + for line in lines: + dst_str, dst_plen_str, src_str, src_plen_str, gw_str, metric, ref_cnt, \ + use_cnt, flags, route_ifname = line.strip().split(maxsplit=9) + if ifname is not None and route_ifname != ifname: + continue + + dst = codecs.decode(dst_str, 'hex') + plen = int(dst_plen_str, 16) + gw = codecs.decode(gw_str, 'hex') + + if dst[0] == 0xff or dst[:2] == b'\xfe\x80': # Skip link-local and multicast + continue + + # Skip RTN_LOCAL-type routes, we don't need to validate them since they're added by + # the kernel and we can't simply add them to the expected list (the list that we + # validate against) because they're added a short time after an address (due to DAD?) + # and would create race conditions + if int(flags, 16) & (1 << 31): + continue + + if dst == b'\0' * 16: + dst = None + plen = None + if gw == b'\0' * 16: + gw = None + yield RouteInfo(dst, plen, gw, int(flags, 16) & 0xf, route_ifname) diff --git a/client/ad-hoc.c b/client/ad-hoc.c @@ -117,7 +117,7 @@ static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) struct l_queue *match = proxy_interface_find_all(IWD_AD_HOC_INTERFACE, NULL, NULL); - display_table_header("Devices in Ad-Hoc Mode", MARGIN "%-*s%-*s", + display_table_header("Devices in Ad-Hoc Mode", MARGIN "%-*s %-*s", 20, "Name", 8, "Started"); if (!match) { @@ -215,14 +215,11 @@ static enum cmd_status cmd_stop(const char *device_name, char **argv, int argc) static const struct command ad_hoc_commands[] = { { NULL, "list", NULL, cmd_list, "List devices in Ad-hoc mode", true }, { "<wlan>", "start", "<\"network name\"> <passphrase>", cmd_start, - "Start or join an existing\n" - "\t\t\t\t\t\t Ad-Hoc network called\n" - "\t\t\t\t\t\t \"network name\" with a\n" - "\t\t\t\t\t\t passphrase" }, + "Start or join an existing Ad-Hoc network called " + "\"network name\" with a passphrase" }, { "<wlan>", "start_open", "<\"network name\">", cmd_start_open, - "Start or join an existing\n" - "\t\t\t\t\t\t open Ad-Hoc network called\n" - "\t\t\t\t\t\t \"network name\"" }, + "Start or join an existing open Ad-Hoc network called" + " \"network name\"" }, { "<wlan>", "stop", NULL, cmd_stop, "Leave an Ad-Hoc network" }, { } }; diff --git a/client/adapter.c b/client/adapter.c @@ -185,9 +185,10 @@ static void display_adapter_inline(const char *margin, const void *data) { const struct adapter *adapter = data; - display("%s%-*s%-*s%-.*s%-.*s\n", margin, - 19, adapter->name ? : "-", 10, get_powered_tostr(adapter), - 20, adapter->vendor ? : "-", 20, adapter->model ? : "-"); + display_table_row(margin, 4, 8, adapter->name ? : "-", + 8, get_powered_tostr(adapter), + 20, adapter->vendor ? : "-", + 20, adapter->model ? : "-"); } static void *adapter_create(void) @@ -268,8 +269,9 @@ static const struct proxy_interface *get_adapter_proxy_by_name( static enum cmd_status cmd_list(const char *adapter_name, char **argv, int argc) { - display_table_header("Adapters", MARGIN "%-*s%-*s%-*s%-*s", 19, "Name", - 10, "Powered", 20, "Vendor", 20, "Model"); + display_table_header("Adapters", MARGIN "%-*s %-*s %-*s %-*s", + 8, "Name", 8, "Powered", + 20, "Vendor", 20, "Model"); proxy_interface_display_list(adapter_interface_type.interface); diff --git a/client/agent.c b/client/agent.c @@ -301,8 +301,8 @@ static struct l_dbus_message *request_user_password_method_call( display("Type the network password for %s.\n", proxy_interface_get_identity_str(proxy)); - username_prompt = l_strdup_printf(COLOR_BLUE PROMPT_USERNAME " " - COLOR_OFF "%s\n", username); + username_prompt = l_strdup_printf(COLOR_BLUE(PROMPT_USERNAME " ") + "%s\n", username); display("%s", username_prompt); l_free(username_prompt); diff --git a/client/ap.c b/client/ap.c @@ -161,9 +161,7 @@ static void display_ap_inline(const char *margin, const void *data) if (!identity) return; - display("%s%-*s%-*s\n", margin, - 20, identity, - 8, get_started_tostr(ap)); + display_table_row(margin, 2, 20, identity, 8, get_started_tostr(ap)); } static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) @@ -173,9 +171,8 @@ static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) proxy_interface_find_all(IWD_ACCESS_POINT_INTERFACE, NULL, NULL); - display_table_header("Devices in Access Point Mode", MARGIN "%-*s%-*s", - 20, "Name", - 8, "Started"); + display_table_header("Devices in Access Point Mode", + MARGIN "%-*s %-*s", 20, "Name", 8, "Started"); if (!match) { display("No devices in access point mode available.\n"); @@ -265,10 +262,10 @@ static void ap_get_diagnostics_callback(struct l_dbus_message *message, } while (l_dbus_message_iter_next_entry(&array, &iter)) { - sprintf(client_num, "Client %u", idx++); - display_table_header(client_num, " %-*s%-*s", + sprintf(client_num, "STA %u", idx++); + display_table_header("", MARGIN "%-*s %-*s %-*s", 8, client_num, 20, "Property", 20, "Value"); - diagnostic_display(&iter, " ", 20, 20); + diagnostic_display(&iter, MARGIN, 20, 20); display_table_footer(); } } @@ -286,10 +283,11 @@ static enum cmd_status cmd_show(const char *device_name, char **argv, int argc) } proxy_properties_display(ap_i, "Access Point Interface", MARGIN, 20, 20); - display_table_footer(); - if (!ap_diagnostic) + if (!ap_diagnostic) { + display_table_footer(); return CMD_STATUS_DONE; + } proxy_interface_method_call(ap_diagnostic, "GetDiagnostics", "", ap_get_diagnostics_callback); @@ -355,14 +353,18 @@ static void ap_display_network(struct l_dbus_message_iter *iter, if (!l_dbus_message_iter_get_variant(&variant, "s", &s)) goto parse_error; - display("%s%-*s%-*s\n", margin, name_width, key, + display_table_row(margin, 2, name_width, key, value_width, s); } else if (!strcmp(key, "SignalStrength")) { + char signal[7]; + 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); + snprintf(signal, sizeof(signal), "%i", n); + + display_table_row(margin, 2, name_width, key, + value_width, signal); } } @@ -386,7 +388,7 @@ static void ap_get_networks_callback(struct l_dbus_message *message, return; } - display_table_header("Networks", " %-*s%-*s", + 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); @@ -416,12 +418,11 @@ static enum cmd_status cmd_get_networks(const char *device_name, char **argv, static const struct command ap_commands[] = { { NULL, "list", NULL, cmd_list, "List devices in AP mode", true }, { "<wlan>", "start", "<\"network name\"> <passphrase>", cmd_start, - "Start an access point\n\t\t\t\t\t\t called \"network " - "name\" with\n\t\t\t\t\t\t a passphrase" }, + "Start an access point called \"network " + "name\" with a passphrase" }, { "<wlan>", "start-profile", "<\"network name\">", cmd_start_profile, "Start an access point based on a disk profile" }, - { "<wlan>", "stop", NULL, cmd_stop, "Stop a started access\n" - "\t\t\t\t\t\t point" }, + { "<wlan>", "stop", NULL, cmd_stop, "Stop a started access 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, diff --git a/client/command.c b/client/command.c @@ -509,16 +509,16 @@ static void list_commands(const char *command_family, static void list_cmd_options(void) { - display(MARGIN "--%-*s%s\n", 48, COMMAND_OPTION_USERNAME, + display(MARGIN "--%-*s %s\n", 48, COMMAND_OPTION_USERNAME, "Provide username"); - display(MARGIN "--%-*s%s\n", 48, COMMAND_OPTION_PASSWORD, + display(MARGIN "--%-*s %s\n", 48, COMMAND_OPTION_PASSWORD, "Provide password"); - display(MARGIN "--%-*s%s\n", 48, COMMAND_OPTION_PASSPHRASE, + display(MARGIN "--%-*s %s\n", 48, COMMAND_OPTION_PASSPHRASE, "Provide passphrase"); - display(MARGIN "--%-*s%s\n", 48, COMMAND_OPTION_DONTASK, + display(MARGIN "--%-*s %s\n", 48, COMMAND_OPTION_DONTASK, "Don't ask for missing\n" - "\t\t\t\t\t\t credentials"); - display(MARGIN "--%-*s%s\n", 48, "help", "Display help"); + "\t\t\t\t\t\t credentials"); + display(MARGIN "--%-*s %s\n", 48, "help", "Display help"); } static void list_cmd_families(void) @@ -542,12 +542,12 @@ static void command_display_help(void) display(MARGIN "iwctl [--options] [commands]\n"); display_table_footer(); - display_table_header("Available options", MARGIN "%-*s%-*s", + display_table_header("Available options", MARGIN "%-*s %-*s", 50, "Options", 28, "Description"); list_cmd_options(); display_table_footer(); - display_table_header("Available commands", MARGIN "%-*s%-*s", + display_table_header("Available commands", MARGIN "%-*s %-*s", 50, "Commands", 28, "Description"); list_cmd_families(); display_table_footer(); diff --git a/client/dbus-proxy.c b/client/dbus-proxy.c @@ -49,7 +49,8 @@ static struct l_queue *proxy_interface_types; void proxy_properties_display(const struct proxy_interface *proxy, const char *caption, const char *margin, - int name_column_width, int value_column_width) + unsigned int name_column_width, + unsigned int value_column_width) { const void *data; const struct proxy_interface_property *properties; @@ -58,7 +59,7 @@ void proxy_properties_display(const struct proxy_interface *proxy, if (!proxy->type->properties) return; - display_table_header(caption, "%s%-*s %-*s%-*s", margin, + display_table_header(caption, "%s%-*s %-*s %-*s", margin, 8, "Settable", name_column_width, "Property", value_column_width, "Value"); @@ -67,14 +68,17 @@ void proxy_properties_display(const struct proxy_interface *proxy, properties = proxy->type->properties; for (i = 0; properties[i].name; i++) { + const char *str; + if (!properties[i].tostr) continue; - display("%s%*s %-*s%-.*s\n", margin, - 8, properties[i].is_read_write ? - COLOR_BOLDGRAY " *" COLOR_OFF : "", - name_column_width, properties[i].name, - value_column_width, properties[i].tostr(data) ? : ""); + str = properties[i].tostr(data); + + display_table_row(MARGIN, 3, 8, properties[i].is_read_write ? + COLOR_BOLDGRAY(" *") : "", + name_column_width, properties[i].name, + value_column_width, str ? : ""); } } @@ -107,6 +111,9 @@ static void proxy_interface_property_update(struct proxy_interface *proxy, const struct proxy_interface_property *property_table = proxy->type->properties; + if (!property_table) + return; + for (i = 0; property_table[i].name; i++) { if (strcmp(property_table[i].name, name)) continue; diff --git a/client/dbus-proxy.h b/client/dbus-proxy.h @@ -89,7 +89,8 @@ bool proxy_interface_method_call(const struct proxy_interface *proxy, void proxy_properties_display(const struct proxy_interface *proxy, const char *caption, const char *margin, - int name_column_width, int value_column_width); + unsigned int name_column_width, + unsigned int value_column_width); char *proxy_property_str_completion(const struct proxy_interface_type *type, proxy_property_match_func_t function, diff --git a/client/device.c b/client/device.c @@ -54,9 +54,10 @@ static void display_device(const struct proxy_interface *proxy) l_free(caption); if (device->adapter) { - display("%s%*s %-*s%-*s\n", MARGIN, 8, "", 20, "Adapter", 47, - proxy_interface_get_identity_str( + display_table_row(MARGIN, 3, 8, "", 20, "Adapter", 47, + proxy_interface_get_identity_str( device->adapter) ? : ""); + } display_table_footer(); @@ -216,12 +217,11 @@ static void display_device_inline(const char *margin, const void *data) else adapter_str = "-"; - display("%s%-*s%-*s%-*s%-*s%-*s\n", margin, - 20, device->name ? : "", - 20, device->address ? : "", - 10, get_powered_tostr(device), - 10, adapter_str, - 10, device->mode); + display_table_row(margin, 5, 20, device->name ? : "", + 20, device->address ? : "", + 10, get_powered_tostr(device), + 10, adapter_str, + 10, device->mode); } static const char *device_identity(void *data) @@ -368,7 +368,7 @@ static void check_errors_method_callback(struct l_dbus_message *message, static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) { - display_table_header("Devices", MARGIN "%-*s%-*s%-*s%-*s%-*s", + display_table_header("Devices", MARGIN "%-*s %-*s %-*s %-*s %-*s", 20, "Name", 20, "Address", 10, "Powered", 10, "Adapter", 10, "Mode"); diff --git a/client/diagnostic.c b/client/diagnostic.c @@ -69,12 +69,13 @@ static bool display_bitrate_100kbps(struct l_dbus_message_iter *variant, int name_column_width, int value_column_width) { uint32_t rate; + char str[50]; if (!l_dbus_message_iter_get_variant(variant, "u", &rate)) return false; - display("%s%-*s%-*u Kbit/s\n", margin, name_column_width, key, - value_column_width, rate * 100); + sprintf(str, "%u Kbit/s", rate * 100); + display_table_row(margin, 3, 8, "", name_column_width, key, value_column_width, str); return true; } @@ -110,6 +111,7 @@ void diagnostic_display(struct l_dbus_message_iter *dict, uint32_t u_value; int16_t n_value; uint8_t y_value; + int bytes; map = find_mapping(key, diagnostic_mapping); if (!map) @@ -132,9 +134,7 @@ void diagnostic_display(struct l_dbus_message_iter *dict, &s_value)) goto parse_error; - sprintf(display_text, "%s%-*s%-*s", margin, - name_column_width, key, - value_column_width, s_value); + bytes = sprintf(display_text, "%s", s_value); break; case 'u': @@ -142,9 +142,7 @@ void diagnostic_display(struct l_dbus_message_iter *dict, &u_value)) goto parse_error; - sprintf(display_text, "%s%-*s%-*u", margin, - name_column_width, key, - value_column_width, u_value); + bytes = sprintf(display_text, "%u", u_value); break; case 'n': @@ -152,9 +150,7 @@ void diagnostic_display(struct l_dbus_message_iter *dict, &n_value)) goto parse_error; - sprintf(display_text, "%s%-*s%-*i", margin, - name_column_width, key, - value_column_width, n_value); + bytes = sprintf(display_text, "%i", n_value); break; case 'y': @@ -162,21 +158,19 @@ void diagnostic_display(struct l_dbus_message_iter *dict, &y_value)) goto parse_error; - sprintf(display_text, "%s%-*s%-*u", margin, - name_column_width, key, - value_column_width, y_value); + bytes = sprintf(display_text, "%u", y_value); break; default: - display("type %c not handled", map->type); + display("type %c not handled\n", map->type); continue; } if (map->units) - display("%s %s\n", display_text, - (const char *)map->units); - else - display("%s\n", display_text); + sprintf(display_text + bytes, " %s", map->units); + + display_table_row(margin, 3, 8, "", name_column_width, + key, value_column_width, display_text); } return; diff --git a/client/display.c b/client/display.c @@ -40,7 +40,7 @@ #include "client/display.h" #define IWD_PROMPT \ - "\001" COLOR_GREEN "\002" "[iwd]" "\001" COLOR_OFF "\002" "# " + "\001" COLOR_GREEN("\002" "[iwd]" "\001") "\002" "# " #define LINE_LEN 81 static struct l_signal *window_change_signal; @@ -234,9 +234,9 @@ static void display_refresh_check_feasibility(void) if (ws.ws_col < LINE_LEN - 1) { if (display_refresh.enabled) { display_refresh.recording = false; - display(COLOR_YELLOW "Auto-refresh is disabled. " + display(COLOR_YELLOW("Auto-refresh is disabled. " "Enlarge window width to at least %u to enable." - "\n" COLOR_OFF, LINE_LEN - 1); + "\n"), LINE_LEN - 1); display_refresh.recording = true; } @@ -317,7 +317,7 @@ void display(const char *fmt, ...) void display_error(const char *error) { - char *text = l_strdup_printf(COLOR_RED "%s" COLOR_OFF "\n", error); + char *text = l_strdup_printf(COLOR_RED("%s\n"), error); display_text(text); @@ -344,14 +344,14 @@ void display_table_header(const char *caption, const char *fmt, ...) int caption_pos = (int) ((sizeof(dashed_line) - 1) / 2 + strlen(caption) / 2); - text = l_strdup_printf("%*s" COLOR_BOLDGRAY "%*c" COLOR_OFF "\n", + text = l_strdup_printf("%*s" COLOR_BOLDGRAY("%*c") "\n", caption_pos, caption, LINE_LEN - 2 - caption_pos, display_refresh.cmd ? get_flasher() : ' '); display_text(text); l_free(text); - text = l_strdup_printf("%s%s%s\n", COLOR_GRAY, dashed_line, COLOR_OFF); + text = l_strdup_printf(COLOR_GRAY("%s\n"), dashed_line); display_text(text); l_free(text); @@ -359,12 +359,12 @@ void display_table_header(const char *caption, const char *fmt, ...) text = l_strdup_vprintf(fmt, args); va_end(args); - body = l_strdup_printf("%s%s%s\n", COLOR_BOLDGRAY, text, COLOR_OFF); + body = l_strdup_printf(COLOR_BOLDGRAY("%s\n"), text); display_text(body); l_free(body); l_free(text); - text = l_strdup_printf("%s%s%s\n", COLOR_GRAY, dashed_line, COLOR_OFF); + text = l_strdup_printf(COLOR_GRAY("%s\n"), dashed_line); display_text(text); l_free(text); } @@ -376,8 +376,183 @@ void display_table_footer(void) display_refresh_check_applicability(); } -void display_command_line(const char *command_family, - const struct command *cmd) +static unsigned int color_end(char *s) +{ + char *start = s; + + while (*s != 'm' && *s != '\0') + s++; + + return s - start + 1; +} + +/* + * Finds last space in 's' before 'max' characters, terminates at that index, + * and returns a new string to be printed on the next line. + * + * 'max' should be set to the column width, but is also an out parameter since + * this width can be updated if colored escapes are detected. + * + * Any colored escapes found are set to 'color_out' so they can be re-enabled + * on the next line. + */ +static char* next_line(char *s, unsigned int *max, char **color_out) +{ + unsigned int i; + int last_space = -1; + int last_color = -1; + + /* Find the last space before 'max', as well as any color */ + for (i = 0; i <= *max && s[i] != '\0'; i++) { + if (s[i] == ' ') + last_space = i; + else if (s[i] == 0x1b) { + /* color escape won't count for column width */ + *max += color_end(s + i); + last_color = i; + } + } + + /* Reached the end of the string within the column bounds */ + if (i <= *max) + return NULL; + + /* Not anywhere nice to split the line */ + if (last_space == -1) + last_space = *max - 1; + + /* + * Only set the color if it occurred prior to the last space. If after, + * it will get picked up on the next line. + */ + if (last_color != -1 && last_space >= last_color) + *color_out = l_strndup(s + last_color, + color_end(s + last_color)); + else + *color_out = NULL; + + s[last_space] = '\0'; + + return l_strdup(s + last_space + 1); +} + +struct table_entry { + unsigned int width; + char *next; + char *color; +}; + +/* + * Appends the next line from 'e' to 'line_buf'. 'done' is only set false when + * there are more lines needed for the current entry. + */ +static int entry_append(struct table_entry *e, char *line_buf) +{ + char *value = e->next; + unsigned int ret = 0; + unsigned int width = e->width; + + /* Empty line */ + if (!value) + return sprintf(line_buf, "%-*s ", e->width, ""); + + /* Color from previous line */ + if (e->color) { + ret = sprintf(line_buf, "%s", e->color); + l_free(e->color); + e->color = NULL; + } + + /* Advance entry to next line, and terminate current */ + e->next = next_line(value, &width, &e->color); + + /* Append current line */ + ret += sprintf(line_buf + ret, "%-*s ", width, value); + + l_free(value); + + /* Un-color output for next column */ + if (e->color) + ret += sprintf(line_buf + ret, "%s", COLOR_OFF); + + return ret; +} + +static bool entries_done(unsigned int num, struct table_entry *e) +{ + unsigned int i; + + for (i = 0; i < num; i++) + if (e[i].next) + return false; + + return true; +} + +/* + * Expects an initial margin, number of columns in table, then row data: + * + * <row width>, <row data>, ... + * + * The data string can be of any length, and will be split into new lines of + * length <row width>. + */ +void display_table_row(const char *margin, unsigned int ncolumns, ...) +{ + char buf[512]; + char *str = buf; + unsigned int i; + struct table_entry entries[ncolumns]; + va_list va; + + memset(&entries[0], 0, sizeof(entries)); + + va_start(va, ncolumns); + + str += sprintf(str, "%s", margin); + + for (i = 0; i < ncolumns; i++) { + struct table_entry *e = &entries[i]; + + e->width = va_arg(va, unsigned int); + e->next = l_strdup(va_arg(va, char*)); + + str += entry_append(e, str); + } + + va_end(va); + + display("%s\n", buf); + str = buf; + + /* + * The first column should now be indented, which effects the entry + * width. Subtract this indentation only from the first column. + */ + entries[0].width -= strlen(margin) * 2; + + while (!entries_done(ncolumns, &entries[0])) { + for (i = 0; i < ncolumns; i++) { + struct table_entry *e = &entries[i]; + + if (i == 0) + str += sprintf(str, "%s%s%s", margin, + margin, margin); + + str += entry_append(e, str); + } + + display("%s\n", buf); + str = buf; + } + + for (i = 0; i < ncolumns; i++) { + if (entries[i].color) + l_free(entries[i].color); + } +} + +void display_command_line(const char *command_family, const struct command *cmd) { char *cmd_line = l_strdup_printf("%s%s%s%s%s%s%s", command_family ? : "", @@ -388,7 +563,7 @@ void display_command_line(const char *command_family, cmd->arg ? " " : "", cmd->arg ? : ""); - display(MARGIN "%-*s%s\n", 50, cmd_line, cmd->desc ? : ""); + display_table_row(MARGIN, 2, 50, cmd_line, 30, cmd->desc); l_free(cmd_line); } @@ -599,7 +774,7 @@ void display_agent_prompt(const char *label, bool mask_input) if (mask_input) reset_masked_input(); - prompt = l_strdup_printf(COLOR_BLUE "%s " COLOR_OFF, label); + prompt = l_strdup_printf(COLOR_BLUE("%s "), label); if (command_is_interactive_mode()) { if (agent_saved_input) { @@ -645,8 +820,8 @@ void display_agent_prompt_release(const char *label) if (display_refresh.cmd) { char *text = rl_copy_text(0, rl_end); - char *prompt = l_strdup_printf(COLOR_BLUE "%s " COLOR_OFF - "%s\n", label, text); + char *prompt = l_strdup_printf(COLOR_BLUE("%s ") + "%s\n", label, text); l_free(text); l_queue_push_tail(display_refresh.redo_entries, prompt); diff --git a/client/display.h b/client/display.h @@ -22,21 +22,21 @@ struct command; struct command_family; - -#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" -#define COLOR_YELLOW "\x1b[33m" -#define COLOR_OFF "\x1B[0m" -#define CLEAR_SCREEN "\033[2J" -#define MARGIN " " +#define COLOR_OFF "\x1B[0m" +#define COLOR_BOLDGRAY(s) "\x1B[1;90m" s COLOR_OFF +#define COLOR_GRAY(s) "\x1b[90m" s COLOR_OFF +#define COLOR_GREEN(s) "\x1b[32m" s COLOR_OFF +#define COLOR_RED(s) "\x1B[0;91m" s COLOR_OFF +#define COLOR_BLUE(s) "\x1B[94m" s COLOR_OFF +#define COLOR_YELLOW(s) "\x1b[33m" s COLOR_OFF +#define CLEAR_SCREEN "\x1b[2J" +#define MARGIN " " void display(const char *format, ...) __attribute__((format(printf, 1, 2))); void display_table_header(const char *caption, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +void display_table_row(const char *margin, unsigned int ncolumns, ...); void display_table_footer(void); void display_error(const char *error); void display_command_line(const char *command_family, diff --git a/client/dpp.c b/client/dpp.c @@ -34,8 +34,111 @@ #include "client/device.h" #include "client/display.h" +struct dpp { + bool started; + char *role; + char *uri; +}; + +static void *dpp_create(void) +{ + return l_new(struct dpp, 1); +} + +static void dpp_destroy(void *data) +{ + struct dpp *dpp = data; + + if (dpp->role) + l_free(dpp->role); + if (dpp->uri) + l_free(dpp->uri); + + l_free(dpp); +} + +static void update_started(void *data, struct l_dbus_message_iter *variant) +{ + struct dpp *dpp = data; + bool value; + + if (!l_dbus_message_iter_get_variant(variant, "b", &value)) { + dpp->started = false; + return; + } + + dpp->started = value; +} + +static const char *started_tostr(const void *data) +{ + const struct dpp *dpp = data; + + return dpp->started ? "yes" : "no"; +} + +static void update_role(void *data, struct l_dbus_message_iter *variant) +{ + struct dpp *dpp = data; + const char *value; + + if (dpp->role) + l_free(dpp->role); + + if (!l_dbus_message_iter_get_variant(variant, "s", &value)) { + dpp->role = NULL; + return; + } + + dpp->role = l_strdup(value); +} + +static const char *role_tostr(const void *data) +{ + const struct dpp *dpp = data; + + return dpp->role; +} + +static void update_uri(void *data, struct l_dbus_message_iter *variant) +{ + struct dpp *dpp = data; + const char *value; + + if (dpp->uri) + l_free(dpp->uri); + + if (!l_dbus_message_iter_get_variant(variant, "s", &value)) { + dpp->uri = NULL; + return; + } + + dpp->uri = l_strdup(value); +} + +static const char *uri_tostr(const void *data) +{ + const struct dpp *dpp = data; + + return dpp->uri; +} + +static const struct proxy_interface_property dpp_properties[] = { + { "Started", "b", update_started, started_tostr }, + { "Role", "s", update_role, role_tostr }, + { "URI", "s", update_uri, uri_tostr }, + { } +}; + +static const struct proxy_interface_type_ops dpp_ops = { + .create = dpp_create, + .destroy = dpp_destroy, +}; + static struct proxy_interface_type dpp_interface_type = { .interface = IWD_DPP_INTERFACE, + .properties = dpp_properties, + .ops = &dpp_ops, }; static void check_errors_method_callback(struct l_dbus_message *message, @@ -174,6 +277,26 @@ static enum cmd_status cmd_stop(const char *device_name, return CMD_STATUS_TRIGGERED; } +static enum cmd_status cmd_show(const char *device_name, + char **argv, int argc) +{ + const struct proxy_interface *proxy = + device_proxy_find(device_name, IWD_DPP_INTERFACE); + char *caption = l_strdup_printf("%s: %s", "DPP", device_name); + + if (!proxy) { + display("No DPP interface on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_properties_display(proxy, caption, MARGIN, 20, 47); + l_free(caption); + + display_table_footer(); + + return CMD_STATUS_DONE; +} + static const struct command dpp_commands[] = { { NULL, "list", NULL, cmd_list, "List DPP-capable devices", true }, { "<wlan>", "start-enrollee", NULL, cmd_start_enrollee, @@ -181,6 +304,7 @@ static const struct command dpp_commands[] = { { "<wlan>", "start-configurator", NULL, cmd_start_configurator, "Starts a DPP Configurator" }, { "<wlan>", "stop", NULL, cmd_stop, "Aborts DPP operations" }, + { "<wlan>", "show", NULL, cmd_show, "Shows the DPP state", true }, { } }; diff --git a/client/known-networks.c b/client/known-networks.c @@ -210,9 +210,9 @@ static void known_network_display_inline(const char *margin, const void *data) l_strdup(format_iso8601(network->last_connected, "%b %e, %l:%M %p")); - display("%s%-*s%-*s%-*s%-*s\n", - margin, 32, network->name, 11, network->type, - 9, get_hidden_tostr(network), 19, last_connected ? : "-"); + display_table_row(margin, 4, 32, network->name, 11, network->type, + 9, get_hidden_tostr(network), + 19, last_connected ? : "-"); l_free(last_connected); } @@ -263,7 +263,7 @@ static void check_errors_method_callback(struct l_dbus_message *message, static enum cmd_status cmd_list(const char *entity, char **args, int argc) { - display_table_header("Known Networks", MARGIN "%-*s%-*s%-*s%-*s", + display_table_header("Known Networks", MARGIN "%-*s %-*s %-*s %-*s", 32, "Name", 11, "Security", 9, "Hidden", 19, "Last connected"); @@ -318,8 +318,8 @@ static const struct proxy_interface *known_network_proxy_find_by_name( if (!network_args.type) { display("Provided network name is ambiguous. " "Specify network security type as follows:\n"); - display("<\"network name" COLOR_BOLDGRAY ".security" - COLOR_OFF "\">\n"); + display("<\"network name" COLOR_BOLDGRAY(".security") + "\">\n"); display("\twhere '.security' is [.psk | .8021x | " ".open]\n"); } diff --git a/client/station.c b/client/station.c @@ -186,8 +186,7 @@ static void display_addresses(const char *device_name) continue; have_address = true; - display("%s%*s %-*s%-*s\n", MARGIN, 8, "", 20, - "IPv4 address", 47, addrstr); + display_table_row(MARGIN, 3, 8, "", 20, "IPv4 address", 47, addrstr); } } @@ -200,8 +199,7 @@ static void display_addresses(const char *device_name) if (r < 0 || r == 1) return; - display("%s%*s %-*s%-*s\n", MARGIN, 8, "", 20, - "No IP addresses", 47, "Is DHCP client configured?"); + display_table_row(MARGIN, 3, 8, "", 20, "No IP addresses", 47, "Is DHCP client configured?"); } @@ -215,9 +213,9 @@ static void display_station(const char *device_name, l_free(caption); if (station->connected_network) { - display("%s%*s %-*s%-*s\n", MARGIN, 8, "", 20, - "Connected network", 47, - network_get_name(station->connected_network)); + display_table_row(MARGIN, 3, 8, "", 20, "Connected network", + 47, network_get_name(station->connected_network)); + display_addresses(device_name); /* @@ -246,10 +244,8 @@ static void display_station_inline(const char *margin, const void *data) if (!identity) return; - display("%s%-*s%-*s%-*s\n", margin, - 20, identity, - 15, station->state ? : "", - 8, station->scanning ? "scanning" : ""); + display_table_row(margin, 3, 20, identity, 15, station->state ? : "", + 8, station->scanning ? "scanning" : ""); } static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) @@ -258,7 +254,8 @@ static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) struct l_queue *match = proxy_interface_find_all(IWD_STATION_INTERFACE, NULL, NULL); - display_table_header("Devices in Station Mode", MARGIN "%-*s%-*s%-*s", + display_table_header("Devices in Station Mode", + MARGIN "%-*s %-*s %-*s", 20, "Name", 15, "State", 8, "Scanning"); if (!match) { @@ -390,12 +387,12 @@ static const char *dbms_tostars(int16_t dbms) return "****"; if (dbms >= -6700) - return "***" COLOR_BOLDGRAY "*" COLOR_OFF; + return "***" COLOR_BOLDGRAY("*"); if (dbms >= -7500) - return "**" COLOR_BOLDGRAY "**" COLOR_OFF; + return "**" COLOR_BOLDGRAY("**"); - return "*" COLOR_BOLDGRAY "***" COLOR_OFF; + return "*" COLOR_BOLDGRAY("***"); } #define RSSI_DBMS "rssi-dbms" @@ -416,7 +413,7 @@ static void ordered_networks_display(struct l_queue *ordered_networks) char *dbms = NULL; const struct l_queue_entry *entry; - display_table_header("Available networks", "%s%-*s%-*s%-*s%*s", + display_table_header("Available networks", "%s%-*s %-*s %-*s %*s", MARGIN, 2, "", 32, "Network name", 18, "Security", 6, "Signal"); @@ -441,11 +438,11 @@ static void ordered_networks_display(struct l_queue *ordered_networks) if (display_signal_as_dbms) dbms = l_strdup_printf("%d", network->signal_strength); - display("%s%-*s%-*s%-*s%-*s\n", MARGIN, 2, - network_is_connected(network_i) ? - COLOR_BOLDGRAY "> " COLOR_OFF : "", - 32, network_name, 18, network_type, - 6, display_signal_as_dbms ? dbms : + display_table_row(MARGIN, 4, 2, + network_is_connected(network_i) ? + COLOR_BOLDGRAY("> ") : "", + 32, network_name, 18, network_type, 6, + display_signal_as_dbms ? dbms : dbms_tostars(network->signal_strength)); if (display_signal_as_dbms) { @@ -556,7 +553,7 @@ static void hidden_access_points_display(struct l_queue *access_points) { const struct l_queue_entry *entry; - display_table_header("Available hidden APs", MARGIN "%-*s%-*s%*s", + display_table_header("Available hidden APs", MARGIN "%-*s %-*s %*s", 20, "Address", 10, "Security", 6, "Signal"); if (l_queue_isempty(access_points)) { @@ -574,9 +571,8 @@ static void hidden_access_points_display(struct l_queue *access_points) if (display_signal_as_dbms) dbms = l_strdup_printf("%d", ap->signal_strength); - display(MARGIN "%-*s%-*s%-*s\n", - 20, ap->address, 10, ap->type, - 6, dbms ? : dbms_tostars(ap->signal_strength)); + display_table_row(MARGIN, 3, 20, ap->address, 10, ap->type, 6, + dbms ? : dbms_tostars(ap->signal_strength)); } display_table_footer(); @@ -676,7 +672,7 @@ static void get_diagnostics_callback(struct l_dbus_message *message, goto done; } - diagnostic_display(&iter, " ", 20, 20); + diagnostic_display(&iter, MARGIN, 20, 47); done: /* Finish the table started by cmd_show */ diff --git a/client/wsc.c b/client/wsc.c @@ -182,10 +182,10 @@ static enum cmd_status cmd_cancel(const char *device_name, static const struct command wsc_commands[] = { { NULL, "list", NULL, cmd_list, "List WSC-capable devices", true }, { "<wlan>", "push-button", NULL, cmd_push_button, "PushButton mode" }, - { "<wlan>", "start-user-pin", "<8 digit PIN>", cmd_start_user_pin, + { "<wlan>", "start-user-pin", "<PIN>", cmd_start_user_pin, "PIN mode" }, { "<wlan>", "start-pin", NULL, cmd_start_pin, - "PIN mode with generated\n\t\t\t\t\t\t 8 digit PIN" }, + "PIN mode with generated 8 digit PIN" }, { "<wlan>", "cancel", NULL, cmd_cancel, "Aborts WSC operations" }, { } }; diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ([2.69]) -AC_INIT([iwd],[1.28]) +AC_INIT([iwd],[1.29]) 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.51" + ell_min_version="0.52" else ell_min_version="0.5" fi diff --git a/doc/device-provisioning-api.txt b/doc/device-provisioning-api.txt @@ -56,3 +56,18 @@ Methods string StartEnrollee() net.connman.iwd.NotConfigured net.connman.iwd.NotSupported net.connman.iwd.Busy + +Properties boolean Started [readonly] + + True if DPP is currently active. + + string Role [readonly, optional] + + Indicates the DPP role. Possible values are "enrollee" + or "configurator". This property is only available when + Started is true. + + string URI [readonly, optional] + + Indicates the DPP URI. This property is only available + when Started is true. diff --git a/monitor/nlmon.c b/monitor/nlmon.c @@ -7944,7 +7944,7 @@ static bool nlmon_receive(struct l_io *io, void *user_data) unsigned char buf[8192]; unsigned char control[32]; ssize_t bytes_read; - int nlmsg_len; + uint32_t nlmsg_len; int fd; fd = l_io_get_fd(io); diff --git a/src/ap.c b/src/ap.c @@ -4084,6 +4084,8 @@ static void ap_remove_interface(struct netdev *netdev) { l_dbus_object_remove_interface(dbus_get_bus(), netdev_get_path(netdev), IWD_AP_INTERFACE); + l_dbus_object_remove_interface(dbus_get_bus(), + netdev_get_path(netdev), IWD_AP_DIAGNOSTIC_INTERFACE); } static void ap_netdev_watch(struct netdev *netdev, diff --git a/src/dpp.c b/src/dpp.c @@ -149,6 +149,71 @@ struct dpp_sm { bool roc_started : 1; }; +static bool dpp_get_started(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + bool started = (dpp->state != DPP_STATE_NOTHING); + + l_dbus_message_builder_append_basic(builder, 'b', &started); + + return true; +} + +static bool dpp_get_role(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *role; + + if (dpp->state == DPP_STATE_NOTHING) + return false; + + switch (dpp->role) { + case DPP_CAPABILITY_ENROLLEE: + role = "enrollee"; + break; + case DPP_CAPABILITY_CONFIGURATOR: + role = "configurator"; + break; + default: + return false; + } + + l_dbus_message_builder_append_basic(builder, 's', role); + return true; +} + +static bool dpp_get_uri(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + + if (dpp->state == DPP_STATE_NOTHING) + return false; + + l_dbus_message_builder_append_basic(builder, 's', dpp->uri); + return true; +} + +static void dpp_property_changed_notify(struct dpp_sm *dpp) +{ + const char *path = netdev_get_path(dpp->netdev); + + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "Started"); + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "Role"); + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "URI"); +} + static void *dpp_serialize_iovec(struct iovec *iov, size_t iov_len, size_t *out_len) { @@ -262,6 +327,8 @@ static void dpp_reset(struct dpp_sm *dpp) explicit_bzero(dpp->auth_tag, dpp->key_len); dpp_free_auth_data(dpp); + + dpp_property_changed_notify(dpp); } static void dpp_free(struct dpp_sm *dpp) @@ -2432,6 +2499,8 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, scan_periodic_stop(dpp->wdev_id); + dpp_property_changed_notify(dpp); + return NULL; } @@ -2562,6 +2631,8 @@ static struct l_dbus_message *dpp_start_configurator_common( scan_periodic_stop(dpp->wdev_id); + dpp_property_changed_notify(dpp); + l_debug("DPP Start Configurator: %s", dpp->uri); reply = l_dbus_message_new_method_return(message); @@ -2606,6 +2677,12 @@ static void dpp_setup_interface(struct l_dbus_interface *interface) dpp_dbus_configure_enrollee, "", "s", "uri"); l_dbus_interface_method(interface, "Stop", 0, dpp_dbus_stop, "", ""); + + l_dbus_interface_property(interface, "Started", 0, "b", dpp_get_started, + NULL); + l_dbus_interface_property(interface, "Role", 0, "s", dpp_get_role, + NULL); + l_dbus_interface_property(interface, "URI", 0, "s", dpp_get_uri, NULL); } static void dpp_destroy_interface(void *user_data) diff --git a/src/eap.c b/src/eap.c @@ -588,8 +588,11 @@ void eap_rx_packet(struct eap_state *eap, const uint8_t *pkt, size_t len) * the Success and Failure packets. In order to support * interoperability with these products we validate id against * eap->last_id and its incremented value. + * + * Note: Since last_id is stored as an int and id value is a + * byte, we need to support overflow properly. */ - if (id != eap->last_id && id != eap->last_id + 1) + if (id != eap->last_id && id != (eap->last_id + 1) % 256) return; if (eap_len != 4) diff --git a/src/eapol.c b/src/eapol.c @@ -443,7 +443,8 @@ static void eapol_key_data_append(struct eapol_key *ek, if (ek->error) \ return false \ -bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len) +bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len, + bool ptk_complete) { /* Verify according to 802.11, Section 11.6.6.2 */ VERIFY_PTK_COMMON(ek); @@ -457,7 +458,7 @@ bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len) if (ek->key_mic) return false; - if (ek->secure) + if (ek->secure != ptk_complete) return false; if (ek->encrypted_key_data) @@ -475,7 +476,7 @@ bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len) return true; } -bool eapol_verify_ptk_2_of_4(const struct eapol_key *ek) +bool eapol_verify_ptk_2_of_4(const struct eapol_key *ek, bool ptk_complete) { uint16_t key_len; @@ -491,7 +492,7 @@ bool eapol_verify_ptk_2_of_4(const struct eapol_key *ek) if (!ek->key_mic) return false; - if (ek->secure) + if (ek->secure != ptk_complete) return false; if (ek->encrypted_key_data) @@ -1151,7 +1152,8 @@ static void eapol_handle_ptk_1_of_4(struct eapol_sm *sm, l_debug("ifindex=%u", sm->handshake->ifindex); - if (!eapol_verify_ptk_1_of_4(ek, sm->mic_len)) + if (!eapol_verify_ptk_1_of_4(ek, sm->mic_len, + sm->handshake->ptk_complete)) return; if (sm->handshake->ptk_complete && unencrypted) { @@ -1523,7 +1525,7 @@ static void eapol_handle_ptk_2_of_4(struct eapol_sm *sm, l_debug("ifindex=%u", sm->handshake->ifindex); - if (!eapol_verify_ptk_2_of_4(ek)) + if (!eapol_verify_ptk_2_of_4(ek, sm->handshake->ptk_complete)) return; if (L_BE64_TO_CPU(ek->key_replay_counter) != sm->replay_counter) diff --git a/src/eapol.h b/src/eapol.h @@ -65,8 +65,9 @@ uint8_t *eapol_decrypt_key_data(enum ie_rsn_akm_suite akm, const uint8_t *kek, const struct eapol_key *frame, size_t *decrypted_size, size_t mic_len); -bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len); -bool eapol_verify_ptk_2_of_4(const struct eapol_key *ek); +bool eapol_verify_ptk_1_of_4(const struct eapol_key *ek, size_t mic_len, + bool ptk_complete); +bool eapol_verify_ptk_2_of_4(const struct eapol_key *ek, bool ptk_complete); bool eapol_verify_ptk_3_of_4(const struct eapol_key *ek, bool is_wpa, size_t mic_len); bool eapol_verify_ptk_4_of_4(const struct eapol_key *ek, bool is_wpa); diff --git a/src/fils.c b/src/fils.c @@ -572,6 +572,8 @@ static int fils_rx_associate(struct auth_proto *driver, const uint8_t *frame, handshake_state_set_pmk(fils->hs, fils->pmk, fils->pmk_len); handshake_state_set_pmkid(fils->hs, fils->pmkid); +_Pragma("GCC diagnostic push") +_Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") if (gtk) handshake_state_install_gtk(fils->hs, gtk_key_index, gtk, gtk_len, key_rsc, 6); @@ -579,6 +581,7 @@ static int fils_rx_associate(struct auth_proto *driver, const uint8_t *frame, if (igtk) handshake_state_install_igtk(fils->hs, igtk_key_index, igtk + 6, igtk_len - 6, igtk); +_Pragma("GCC diagnostic pop") handshake_state_set_ptk(fils->hs, fils->kek_and_tk, fils->kek_len + 16); handshake_state_install_ptk(fils->hs); diff --git a/src/netconfig.c b/src/netconfig.c @@ -515,6 +515,7 @@ static struct l_rtnl_address *netconfig_get_static6_address( { L_AUTO_FREE_VAR(char *, ip); char *p; + char *endp; struct l_rtnl_address *ret; uint32_t prefix_len = 128; @@ -530,8 +531,9 @@ static struct l_rtnl_address *netconfig_get_static6_address( if (*++p == '\0') goto no_prefix_len; - prefix_len = strtoul(p, NULL, 10); - if (!unlikely(errno == EINVAL || errno == ERANGE || + errno = 0; + prefix_len = strtoul(p, &endp, 10); + if (unlikely(*endp != '\0' || errno || !prefix_len || prefix_len > 128)) { l_error("netconfig: Invalid prefix '%s' provided in network" " configuration file", p); diff --git a/src/p2p.c b/src/p2p.c @@ -907,7 +907,7 @@ static void p2p_group_event(enum ap_event_type type, const void *event_data, { const struct ap_event_station_added_data *data = event_data; L_AUTO_FREE_VAR(uint8_t *, wfd_data) = NULL; - ssize_t wfd_data_len; + ssize_t wfd_data_len = 0; struct p2p_association_req req_info; int r; diff --git a/src/station.c b/src/station.c @@ -1635,6 +1635,9 @@ static void station_reset_connection_state(struct station *station) station_roam_state_clear(station); + if (station->netconfig) + netconfig_reset(station->netconfig); + /* Refresh the ordered network list */ network_rank_update(station->connected_network, false); l_queue_remove(station->networks_sorted, station->connected_network); @@ -1669,9 +1672,6 @@ static void station_disassociated(struct station *station) { l_debug("%u", netdev_get_ifindex(station->netdev)); - if (station->netconfig) - netconfig_reset(station->netconfig); - station_reset_connection_state(station); station_enter_state(station, STATION_STATE_DISCONNECTED); @@ -3114,9 +3114,6 @@ static void station_disconnect_onconnect(struct station *station, return; } - if (station->netconfig) - netconfig_reset(station->netconfig); - station_reset_connection_state(station); station_enter_state(station, STATION_STATE_DISCONNECTING); @@ -3430,9 +3427,6 @@ int station_disconnect(struct station *station) if (!station->connected_bss) return -ENOTCONN; - if (station->netconfig) - netconfig_reset(station->netconfig); - /* * If the disconnect somehow fails we won't know if we're still * connected so we may as well indicate now that we're no longer diff --git a/src/storage.c b/src/storage.c @@ -321,8 +321,12 @@ const char *storage_network_ssid_from_path(const char *path, if (!isalnum(*c) && !strchr("-_ ", *c)) break; - if (c < end) + if (c < end) { + l_warn("Provisioning file %s contains non-alphanumeric " + "characters in the name. Please hex-encode. " + "See man iwd.network", path); return NULL; + } memcpy(buf, filename, end - filename); buf[end - filename] = '\0'; @@ -456,11 +460,9 @@ char *__storage_encrypt(const struct l_settings *settings, const char *name, int __storage_decrypt(struct l_settings *settings, const char *ssid, bool *encrypt) { - _auto_(l_settings_free) struct l_settings *security = NULL; _auto_(l_free) uint8_t *encrypted = NULL; _auto_(l_free) uint8_t *decrypted = NULL; _auto_(l_free) uint8_t *salt = NULL; - _auto_(l_strv_free) char **embedded = NULL; _auto_(l_strv_free) char **groups = NULL; char **i; size_t elen, slen; @@ -599,8 +601,10 @@ struct l_settings *storage_network_open(enum security type, const char *ssid) settings = l_settings_new(); - if (!l_settings_load_from_file(settings, path)) + if (!l_settings_load_from_file(settings, path)) { + l_error("Error loading %s", path); goto error; + } if (type != SECURITY_NONE && !storage_decrypt(settings, path, ssid)) goto error; diff --git a/tools/run-tests b/tools/run-tests @@ -58,28 +58,34 @@ def exit_vm(): runner.stop() class Interface: - def __init__(self, name, config): + def __init__(self, name, config, ns): self.name = name self.ctrl_interface = '/var/run/hostapd/' + name self.config = config + self.ns = ns def __del__(self): - Process(['iw', 'dev', self.name, 'del']).wait() + Process(['iw', 'dev', self.name, 'del'], namespace=self.ns.name).wait() def set_interface_state(self, state): - Process(['ip', 'link', 'set', self.name, state]).wait() + Process(['ip', 'link', 'set', self.name, state], namespace=self.ns.name).wait() class Radio: - def __init__(self, name): + def __init__(self, name, default_ns): self.name = name # hostapd will reset this if this radio is used by it self.use = 'iwd' self.interface = None + self.ns = default_ns def __del__(self): print("Removing radio %s" % self.name) self.interface = None + def set_namespace(self, ns): + self.ns = ns + Process(['iw', 'phy', self.name, 'set', 'netns', 'name', ns.name]).wait() + def create_interface(self, config, use): global intf_id @@ -87,19 +93,21 @@ class Radio: intf_id += 1 - self.interface = Interface(ifname, config) + self.interface = Interface(ifname, config, self.ns) self.use = use Process(['iw', 'phy', self.name, 'interface', 'add', ifname, - 'type', 'managed']).wait() + 'type', 'managed'], namespace=self.ns.name).wait() return self.interface def __str__(self): ret = self.name + ':\n' - ret += '\tUsed By: %s ' % self.use + ret += '\tUsed By: %s' % self.use if self.interface: - ret += '(%s)' % self.interface.name + ret += ' (%s)' % self.interface.name + if self.ns is not None: + ret += ' (ns=%s)' % self.ns.name ret += '\n' @@ -113,7 +121,7 @@ class VirtualRadio(Radio): than the command line. ''' - def __init__(self, name, cfg=None): + def __init__(self, name, default_ns, cfg=None): global config self.disable_cipher = None @@ -129,7 +137,7 @@ class VirtualRadio(Radio): iftype_disable=self.disable_iftype, cipher_disable=self.disable_cipher) - super().__init__(self._radio.name) + super().__init__(self._radio.name, default_ns) def __del__(self): super().__del__() @@ -188,7 +196,7 @@ 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): + def __init__(self, ns, radios, configs, radius): if len(configs) != len(radios): raise Exception("Config (%d) and radio (%d) list length not equal" % \ (len(configs), len(radios))) @@ -198,8 +206,8 @@ class Hostapd: Process(['ip', 'link', 'set', 'eth0', 'up']).wait() Process(['ip', 'link', 'set', 'eth1', 'up']).wait() - self.global_ctrl_iface = '/var/run/hostapd/ctrl' - + self.ns = ns + self.global_ctrl_iface = '/var/run/hostapd/ctrl' + (str(ns.name) if ns.name else 'main') self.instances = [HostapdInstance(c, r) for c, r in zip(configs, radios)] ifaces = [rad.interface.name for rad in radios] @@ -227,7 +235,7 @@ class Hostapd: if Process.is_verbose('hostapd'): args.append('-d') - self.process = Process(args) + self.process = Process(args, namespace=ns.name) self.process.wait_for_socket(self.global_ctrl_iface, 30) @@ -326,9 +334,8 @@ class TestContext(Namespace): # 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')) + proc = self.start_process(args) + proc.wait_for_service(self, 'net.connman.hwsim', 20) for i in range(nradios): name = 'rad%u' % i @@ -341,7 +348,7 @@ class TestContext(Namespace): if self.hw_config.has_section(name): rad_config = self.hw_config[name] - self.radios.append(VirtualRadio(name, rad_config)) + self.radios.append(VirtualRadio(name, self, rad_config)) def discover_radios(self): import pyroute2 @@ -363,7 +370,7 @@ class TestContext(Namespace): break print('Discovered radios: %s' % str(phys)) - self.radios = [Radio(name) for name in phys] + self.radios = [Radio(name, self) for name in phys] def start_radios(self): reg_domain = self.hw_config['SETUP'].get('reg_domain', None) @@ -398,32 +405,44 @@ class TestContext(Namespace): # 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] - + hapd_configs = [conf for rad, conf in settings.items() if rad != 'radius_server'] + hapd_processes = [(self, self.radios[:len(hapd_configs)], hapd_configs)] 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'] + hapd_processes = [] + for ns in [self] + self.namespaces: + ns_radios = [rad for rad in ns.radios if rad.name in settings] + if len(ns_radios): + ns_configs = [settings[rad.name] for rad in ns_radios] + hapd_processes.append((ns, ns_radios, ns_configs)) + if not hapd_processes: + hapd_processes.append((self, [], [])) radius_config = settings.get('radius_server', None) - self.hostapd = Hostapd(hapd_radios, hapd_configs, radius_config) - self.hostapd.attach_cli() + self.hostapd = [Hostapd(ns, radios, configs, radius_config) + for ns, radios, configs in hapd_processes] + + for hapd in self.hostapd: + hapd.attach_cli() def get_frequencies(self): frequencies = [] - for hapd in self.hostapd.instances: - frequencies.append(hapd.cli.frequency) + for hapd in self.hostapd: + frequencies += [instance.cli.frequency for instance in hapd.instances] return frequencies + def get_hapd_instance(self, config=None): + instances = [i for hapd in self.hostapd for i in hapd.instances] + + if config is None: + return instances[0] + + for hapd in instances: + if hapd.config == config: + return hapd + def start_wpas_interfaces(self): if 'WPA_SUPPLICANT' not in self.hw_config: return @@ -544,11 +563,13 @@ class TestContext(Namespace): 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) + for hapd in self.hostapd: + ret += 'Hostapd (ns=%s):\n' % (hapd.ns.name,) + for h in hapd.instances: + ret += '\t%s\n' % (str(h),) else: + ret += 'Hostapd:\n' ret += '\tNo Hostapd instances\n' info = self.meminfo_to_dict() @@ -607,8 +628,10 @@ def build_test_list(args): # Run all tests if not args.autotests: # Get list of all autotests (committed in git) + Process(['git', 'config', '--system', '--add', 'safe.directory', + os.path.normpath(args.testhome)]).wait() tests = os.popen('git -C %s ls-files autotests/ | cut -f2 -d"/" \ - | grep "test*" | uniq' % args.testhome).read() \ + | grep "^test" | uniq' % args.testhome).read() \ .strip().split('\n') tests = [test_root + '/' + t for t in tests] else: @@ -1012,5 +1035,10 @@ runner = Runner() atexit.register(exit_vm) runner.prepare_environment() -run_tests(runner.args) + +if runner.args.start: + os.system(runner.args.start) +else: + run_tests(runner.args) + runner.cleanup_environment() diff --git a/tools/runner.py b/tools/runner.py @@ -36,6 +36,7 @@ mounts_common = [ MountInfo('tmpfs', 'tmpfs', '/run', 'mode=0755', MS_NOSUID|MS_NODEV|MS_STRICTATIME), MountInfo('tmpfs', 'tmpfs', '/tmp', '', 0), + MountInfo('tmpfs', 'tmpfs', '/etc', '', 0), MountInfo('tmpfs', 'tmpfs', '/usr/share/dbus-1', 'mode=0755', MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME), ] @@ -108,7 +109,7 @@ class RunnerCoreArgParse(ArgumentParser): help='Enables iwmon output to file') self.add_argument('--sub-tests', '-S', metavar='<subtests>', - type=str, nargs=1, help='List of subtests to run', + type=str, help='List of subtests to run', default=None, dest='sub_tests') self.add_argument('--result', '-e', type=os.path.abspath, @@ -117,8 +118,8 @@ class RunnerCoreArgParse(ArgumentParser): 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) + 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() @@ -131,8 +132,6 @@ class RunnerCoreArgParse(ArgumentParser): auto_unit_group.add_argument('--unit-tests', '-U', metavar='<tests>', type=str, - nargs='?', - const='*', help='List of unit tests to run', dest='unit_tests') @@ -141,7 +140,6 @@ class RunnerCoreArgParse(ArgumentParser): 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', @@ -156,7 +154,7 @@ class RunnerCoreArgParse(ArgumentParser): options = [] for k, v in os.environ.items(): - options.append('--' + k) + options.append('--' + k.replace('_', '-')) options.append(v) return self.parse_known_args(args=options, namespace=RunnerNamespace())[0] @@ -200,14 +198,6 @@ class Runner: 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: @@ -234,6 +224,16 @@ class RunnerAbstract: def __init__(self, args): self.args = args + if len(sys.argv) <= 1: + return + + if os.path.exists('run-tests'): + self.init = os.path.abspath('run-tests') + elif os.path.exists('tools/run-tests'): + self.init = os.path.abspath('tools/run-tests') + else: + raise Exception("Cannot locate run-tests binary") + def start(self): print("Starting %s" % self.name) os.execlpe(self.cmdline[0], *self.cmdline, self.env) @@ -282,6 +282,8 @@ class RunnerAbstract: fcntl.ioctl(STDIN_FILENO, TIOCSTTY, 1) + os.system('ip link set dev lo up') + def cleanup_environment(self): rmtree('/tmp/iwd') rmtree('/tmp/certs') @@ -416,7 +418,7 @@ class QemuRunner(RunnerAbstract): rootflags=trans=virtio \ acpi=off pci=noacpi %s ro \ mac80211_hwsim.radios=0 init=%s %s' % - (kern_log, args.start, args.to_cmd()), + (kern_log, self.init, args.to_cmd()), ] # Add two ethernet devices for testing EAD @@ -519,7 +521,7 @@ class UmlRunner(RunnerAbstract): 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] + '%s' % kern_log, 'init=%s' % self.init] cmd.extend(args.to_cmd().split(' ')) self.cmdline = cmd diff --git a/tools/test_runner_kernel_config b/tools/test_runner_kernel_config @@ -32,8 +32,8 @@ 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_CRYPTO_GCM scripts/config --enable CONFIG_KEYS scripts/config --enable CONFIG_KEY_DH_OPERATIONS scripts/config --enable CONFIG_ASYMMETRIC_KEY_TYPE diff --git a/tools/utils.py b/tools/utils.py @@ -8,7 +8,8 @@ import dbus from gi.repository import GLib from weakref import WeakValueDictionary -from re import match +from re import fullmatch +from time import sleep from runner import RunnerCoreArgParse @@ -79,13 +80,14 @@ class Process(subprocess.Popen): @staticmethod def is_verbose(process, log=True): + exclude = ['iwd-rtnl'] 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: + if log and Process.testargs.log and process not in exclude: return True if process in Process.testargs.verbose: @@ -98,7 +100,7 @@ class Process(subprocess.Popen): # Handle any regex matches for item in Process.testargs.verbose: try: - if match(item, process): + if fullmatch(item, process): return True except Exception as e: print("%s is not a valid regex" % item) @@ -212,7 +214,24 @@ class Process(subprocess.Popen): self.write_fds.append(f) def wait_for_socket(self, socket, wait): - Namespace.non_block_wait(os.path.exists, wait, socket) + def _wait(socket): + if not os.path.exists(socket): + sleep(0.1) + return False + return True + + Namespace.non_block_wait(_wait, wait, socket, + exception=Exception("Timed out waiting for %s" % socket)) + + def wait_for_service(self, ns, service, wait): + def _wait(ns, service): + if not ns._bus.name_has_owner(service): + sleep(0.1) + return False + return True + + Namespace.non_block_wait(_wait, wait, ns, service, + exception=Exception("Timed out waiting for %s" % service)) # Wait for both process termination and HUP signal def __wait(self, timeout): @@ -258,7 +277,7 @@ class Process(subprocess.Popen): try: self.wait(timeout=15) except: - print("Process %s did not complete in 15 seconds!" % self.name) + print("Process %s did not complete in 15 seconds!" % self.args[0]) super().kill() self._cleanup() @@ -305,7 +324,7 @@ class Namespace: Process(['ip', 'netns', 'add', name]).wait() for r in radios: - Process(['iw', 'phy', r.name, 'set', 'netns', 'name', name]).wait() + r.set_namespace(self) self.start_dbus() @@ -341,10 +360,24 @@ class Namespace: def stop_process(self, p, force=False): p.kill(force) + def _is_running(self, pid): + try: + os.kill(pid, 0) + except OSError: + return False + + return True + def is_process_running(self, process): for p in Process.get_all(): - if p.namespace == self.name and p.args[0] == process: - return True + # Namespace processes are actually started by 'ip' where + # the actual process name is at index 4 of the arguments. + idx = 0 if not p.namespace else 4 + + if p.namespace == self.name and p.args[idx] == process: + # The process object exists, but make sure its + # actually running. + return self._is_running(p.pid) return False def _cleanup_dbus(self): @@ -405,7 +438,14 @@ class Namespace: if Process.is_verbose('iwd-acd'): env['IWD_ACD_DEBUG'] = '1' - return self.start_process(args, env=env) + if Process.is_verbose('iwd-rtnl'): + env['IWD_RTNL_DEBUG'] = '1' + + proc = self.start_process(args, env=env) + + proc.wait_for_service(self, 'net.connman.iwd', 20) + + return proc @staticmethod def non_block_wait(func, timeout, *args, exception=True): diff --git a/unit/test-eapol.c b/unit/test-eapol.c @@ -1768,13 +1768,13 @@ static void eapol_4way_test(const void *data) step1 = eapol_key_validate(eapol_key_data_3, sizeof(eapol_key_data_3), 16); assert(step1); - assert(eapol_verify_ptk_1_of_4(step1, 16)); + assert(eapol_verify_ptk_1_of_4(step1, 16, false)); memcpy(anonce, step1->key_nonce, sizeof(step1->key_nonce)); step2 = eapol_key_validate(eapol_key_data_4, sizeof(eapol_key_data_4), 16); assert(step2); - assert(eapol_verify_ptk_2_of_4(step2)); + assert(eapol_verify_ptk_2_of_4(step2, false)); memcpy(snonce, step2->key_nonce, sizeof(step2->key_nonce)); assert(!crypto_psk_from_passphrase(passphrase, (uint8_t *) ssid, @@ -1853,13 +1853,13 @@ static void eapol_wpa2_handshake_test(const void *data) ptk_step1 = eapol_key_validate(eapol_key_data_7, sizeof(eapol_key_data_7), 16); assert(ptk_step1); - assert(eapol_verify_ptk_1_of_4(ptk_step1, 16)); + assert(eapol_verify_ptk_1_of_4(ptk_step1, 16, false)); memcpy(anonce, ptk_step1->key_nonce, sizeof(ptk_step1->key_nonce)); ptk_step2 = eapol_key_validate(eapol_key_data_8, sizeof(eapol_key_data_8), 16); assert(ptk_step2); - assert(eapol_verify_ptk_2_of_4(ptk_step2)); + assert(eapol_verify_ptk_2_of_4(ptk_step2, false)); memcpy(snonce, ptk_step2->key_nonce, sizeof(ptk_step2->key_nonce)); assert(!crypto_psk_from_passphrase(passphrase, (uint8_t *) ssid, @@ -1983,13 +1983,13 @@ static void eapol_wpa_handshake_test(const void *data) ptk_step1 = eapol_key_validate(eapol_key_data_13, sizeof(eapol_key_data_13), 16); assert(ptk_step1); - assert(eapol_verify_ptk_1_of_4(ptk_step1, 16)); + assert(eapol_verify_ptk_1_of_4(ptk_step1, 16, false)); memcpy(anonce, ptk_step1->key_nonce, sizeof(ptk_step1->key_nonce)); ptk_step2 = eapol_key_validate(eapol_key_data_14, sizeof(eapol_key_data_14), 16); assert(ptk_step2); - assert(eapol_verify_ptk_2_of_4(ptk_step2)); + assert(eapol_verify_ptk_2_of_4(ptk_step2, false)); memcpy(snonce, ptk_step2->key_nonce, sizeof(ptk_step2->key_nonce)); assert(!crypto_psk_from_passphrase(passphrase, (uint8_t *) ssid,