diff options
author | Sayed Shah <sayshah@redhat.com> | 2020-06-09 16:28:32 -0400 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2020-06-15 16:40:38 +0200 |
commit | be822b52e6b27c32cdc9ef34856c852ba4174024 (patch) | |
tree | 290db5117adefdb6b85db2b185af285b864fe235 | |
parent | b6febb0fd088ecc93d154b60d758593ec50aa37e (diff) | |
download | NetworkManager-be822b52e6b27c32cdc9ef34856c852ba4174024.tar.gz |
all: reformat python files with python black
Part of !537.
https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/537
44 files changed, 3232 insertions, 2014 deletions
diff --git a/clients/tests/test-client.py b/clients/tests/test-client.py index 8bbbdbfc47..062fc9f354 100755 --- a/clients/tests/test-client.py +++ b/clients/tests/test-client.py @@ -39,33 +39,33 @@ from __future__ import print_function # (optional) The build dir. Optional, mainly used to find the nmcli binary (in case # ENV_NM_TEST_CLIENT_NMCLI_PATH is not set. -ENV_NM_TEST_CLIENT_BUILDDIR = 'NM_TEST_CLIENT_BUILDDIR' +ENV_NM_TEST_CLIENT_BUILDDIR = "NM_TEST_CLIENT_BUILDDIR" # (optional) Path to nmcli. By default, it looks for nmcli in build dir. # In particular, you can test also a nmcli binary installed somewhere else. -ENV_NM_TEST_CLIENT_NMCLI_PATH = 'NM_TEST_CLIENT_NMCLI_PATH' +ENV_NM_TEST_CLIENT_NMCLI_PATH = "NM_TEST_CLIENT_NMCLI_PATH" # (optional) The test also compares tranlsated output (l10n). This requires, # that you first install the translation in the right place. So, by default, # if a test for a translation fails, it will mark the test as skipped, and not # fail the tests. Under the assumption, that the test cannot succeed currently. # By setting NM_TEST_CLIENT_CHECK_L10N=1, you can force a failure of the test. -ENV_NM_TEST_CLIENT_CHECK_L10N = 'NM_TEST_CLIENT_CHECK_L10N' +ENV_NM_TEST_CLIENT_CHECK_L10N = "NM_TEST_CLIENT_CHECK_L10N" # Regenerate the .expected files. Instead of asserting, rewrite the files # on disk with the expected output. -ENV_NM_TEST_REGENERATE = 'NM_TEST_REGENERATE' +ENV_NM_TEST_REGENERATE = "NM_TEST_REGENERATE" # whether the file location should include the line number. That is useful # only for debugging, to correlate the expected output with the test. # Obviously, since the expected output is commited to git without line numbers, # you'd have to first NM_TEST_REGENERATE the test expected data, with line # numbers enabled. -ENV_NM_TEST_WITH_LINENO = 'NM_TEST_WITH_LINENO' +ENV_NM_TEST_WITH_LINENO = "NM_TEST_WITH_LINENO" -ENV_NM_TEST_ASAN_OPTIONS = 'NM_TEST_ASAN_OPTIONS' -ENV_NM_TEST_LSAN_OPTIONS = 'NM_TEST_LSAN_OPTIONS' -ENV_NM_TEST_UBSAN_OPTIONS = 'NM_TEST_UBSAN_OPTIONS' +ENV_NM_TEST_ASAN_OPTIONS = "NM_TEST_ASAN_OPTIONS" +ENV_NM_TEST_LSAN_OPTIONS = "NM_TEST_LSAN_OPTIONS" +ENV_NM_TEST_UBSAN_OPTIONS = "NM_TEST_UBSAN_OPTIONS" # ############################################################################### @@ -76,7 +76,7 @@ try: import gi from gi.repository import GLib - gi.require_version('NM', '1.0') + gi.require_version("NM", "1.0") from gi.repository import NM except Exception as e: GLib = None @@ -100,8 +100,8 @@ import io ############################################################################### -class PathConfiguration: +class PathConfiguration: @staticmethod def srcdir(): # this is the directory where the test script itself lies. @@ -115,16 +115,19 @@ class PathConfiguration: @staticmethod def test_networkmanager_service_path(): - v = os.path.abspath(PathConfiguration.top_srcdir() + "/tools/test-networkmanager-service.py") - assert os.path.exists(v), ("Cannot find test server at \"%s\"" % (v)) + v = os.path.abspath( + PathConfiguration.top_srcdir() + "/tools/test-networkmanager-service.py" + ) + assert os.path.exists(v), 'Cannot find test server at "%s"' % (v) return v @staticmethod def canonical_script_filename(): - p = 'clients/tests/test-client.py' - assert (PathConfiguration.top_srcdir() + '/' + p) == os.path.abspath(__file__) + p = "clients/tests/test-client.py" + assert (PathConfiguration.top_srcdir() + "/" + p) == os.path.abspath(__file__) return p + ############################################################################### dbus_session_inited = False @@ -134,17 +137,18 @@ _UNSTABLE_OUTPUT = object() ############################################################################### + class Util: _signal_no_lookup = { - 1: "SIGHUP", - 2: "SIGINT", - 3: "SIGQUIT", - 4: "SIGILL", - 5: "SIGTRAP", - 6: "SIGABRT", - 8: "SIGFPE", - 9: "SIGKILL", + 1: "SIGHUP", + 2: "SIGINT", + 3: "SIGQUIT", + 4: "SIGILL", + 5: "SIGTRAP", + 6: "SIGABRT", + 8: "SIGFPE", + 9: "SIGKILL", 11: "SIGSEGV", 12: "SIGSYS", 13: "SIGPIPE", @@ -174,10 +178,10 @@ class Util: return s @staticmethod - def python_has_version(major, minor = 0): - return sys.version_info[0] > major \ - or ( sys.version_info[0] == major \ - and sys.version_info[1] >= minor) + def python_has_version(major, minor=0): + return sys.version_info[0] > major or ( + sys.version_info[0] == major and sys.version_info[1] >= minor + ) @staticmethod def is_string(s): @@ -190,14 +194,17 @@ class Util: @staticmethod def memoize_nullary(nullary_func): result = [] + def closure(): if not result: result.append(nullary_func()) return result[0] + return closure - _find_unsafe = re.compile(r'[^\w@%+=:,./-]', - re.ASCII if sys.version_info[0] >= 3 else 0).search + _find_unsafe = re.compile( + r"[^\w@%+=:,./-]", re.ASCII if sys.version_info[0] >= 3 else 0 + ).search @staticmethod def quote(s): @@ -210,16 +217,18 @@ class Util: return "'" + s.replace("'", "'\"'\"'") + "'" @staticmethod - def popen_wait(p, timeout = 0): - (res, b_stdout, b_stderr) = Util.popen_wait_read(p, timeout = timeout, read_std_pipes = False) + def popen_wait(p, timeout=0): + (res, b_stdout, b_stderr) = Util.popen_wait_read( + p, timeout=timeout, read_std_pipes=False + ) return res @staticmethod - def popen_wait_read(p, timeout = 0, read_std_pipes = True): + def popen_wait_read(p, timeout=0, read_std_pipes=True): start = NM.utils_get_timestamp_msec() delay = 0.0005 - b_stdout = b'' - b_stderr = b'' + b_stdout = b"" + b_stderr = b"" res = None while True: if read_std_pipes: @@ -230,7 +239,7 @@ class Util: break if timeout == 0: break - assert(timeout > 0) + assert timeout > 0 remaining = timeout - ((NM.utils_get_timestamp_msec() - start) / 1000.0) if remaining <= 0: break @@ -240,14 +249,14 @@ class Util: @staticmethod def buffer_read(buf): - b = b'' + b = b"" while True: try: b1 = buf.read() except io.BlockingIOError: - b1 = b'' + b1 = b"" except IOError: - b1 = b'' + b1 = b"" if not b1: return b b += b1 @@ -280,14 +289,14 @@ class Util: idx = 0 rx = 0 while True: - rx += (l - idx) + rx += l - idx if rx >= r or idx == l - 1: yield jobs[idx] break idx += 1 @staticmethod - def iter_single(itr, min_num = 1, max_num = 1): + def iter_single(itr, min_num=1, max_num=1): itr = list(itr) n = 0 v = None @@ -297,15 +306,19 @@ class Util: break v = c if n < min_num: - raise AssertionError("Expected at least %s elements, but %s found" % (min_num, n)) + raise AssertionError( + "Expected at least %s elements, but %s found" % (min_num, n) + ) if n > max_num: - raise AssertionError("Expected at most %s elements, but %s found" % (max_num, n)) + raise AssertionError( + "Expected at most %s elements, but %s found" % (max_num, n) + ) return v @staticmethod def file_read(filename): try: - with open(filename, 'rb') as f: + with open(filename, "rb") as f: return f.read() except: return None @@ -316,7 +329,7 @@ class Util: return text needs_encode = Util.python_has_version(3) and Util.is_string(text) if needs_encode: - text = text.encode('utf-8') + text = text.encode("utf-8") text = [text] for replace in replace_arr: try: @@ -327,8 +340,8 @@ class Util: if not v_search: continue v_replace = replace[1] - v_search = v_search.encode('utf-8') - v_replace = v_replace.encode('utf-8') + v_search = v_search.encode("utf-8") + v_replace = v_replace.encode("utf-8") text2 = [] for t in text: if isinstance(t, tuple): @@ -337,42 +350,40 @@ class Util: t2 = t.split(v_search) text2.append(t2[0]) for t3 in t2[1:]: - text2.append( (v_replace,) ) + text2.append((v_replace,)) text2.append(t3) text = text2 - bb = b''.join([(t[0] if isinstance(t, tuple) else t) for t in text]) + bb = b"".join([(t[0] if isinstance(t, tuple) else t) for t in text]) if needs_encode: - bb = bb.decode('utf-8') + bb = bb.decode("utf-8") return bb @staticmethod def replace_text_sort_list(lst, replace_arr): - lst = [ (Util.replace_text(elem, replace_arr), elem) for elem in lst ] + lst = [(Util.replace_text(elem, replace_arr), elem) for elem in lst] lst = sorted(lst) - lst = [ tup[1] for tup in lst ] + lst = [tup[1] for tup in lst] return list(lst) @staticmethod def debug_dbus_interface(): # this is for printf debugging, not used in actual code. - os.system('busctl --user --verbose call org.freedesktop.NetworkManager /org/freedesktop org.freedesktop.DBus.ObjectManager GetManagedObjects | cat') + os.system( + "busctl --user --verbose call org.freedesktop.NetworkManager /org/freedesktop org.freedesktop.DBus.ObjectManager GetManagedObjects | cat" + ) @staticmethod def iter_nmcli_output_modes(): - for mode in [[], - ['--mode', 'tabular'], - ['--mode', 'multiline']]: - for fmt in [[], - ['--pretty'], - ['--terse']]: - for color in [[], - ['--color', 'yes']]: + for mode in [[], ["--mode", "tabular"], ["--mode", "multiline"]]: + for fmt in [[], ["--pretty"], ["--terse"]]: + for color in [[], ["--color", "yes"]]: yield mode + fmt + color + ############################################################################### -class Configuration: +class Configuration: def __init__(self): self._values = {} @@ -381,14 +392,18 @@ class Configuration: if name in self._values: return v if name == ENV_NM_TEST_CLIENT_BUILDDIR: - v = os.environ.get(ENV_NM_TEST_CLIENT_BUILDDIR, PathConfiguration.top_srcdir()) + v = os.environ.get( + ENV_NM_TEST_CLIENT_BUILDDIR, PathConfiguration.top_srcdir() + ) if not os.path.isdir(v): raise Exception("Missing builddir. Set NM_TEST_CLIENT_BUILDDIR?") elif name == ENV_NM_TEST_CLIENT_NMCLI_PATH: v = os.environ.get(ENV_NM_TEST_CLIENT_NMCLI_PATH, None) if v is None: try: - v = os.path.abspath(self.get(ENV_NM_TEST_CLIENT_BUILDDIR) + "/clients/cli/nmcli") + v = os.path.abspath( + self.get(ENV_NM_TEST_CLIENT_BUILDDIR) + "/clients/cli/nmcli" + ) except: pass if not os.path.exists(v): @@ -402,41 +417,48 @@ class Configuration: # # Only by setting NM_TEST_CLIENT_CHECK_L10N=1, these tests are included # as well. - v = (os.environ.get(ENV_NM_TEST_CLIENT_CHECK_L10N, '0') == '1') + v = os.environ.get(ENV_NM_TEST_CLIENT_CHECK_L10N, "0") == "1" elif name == ENV_NM_TEST_REGENERATE: # in the "regenerate" mode, the tests will rewrite the files on disk against # which we assert. That is useful, if there are intentional changes and # we want to regenerate the expected output. - v = (os.environ.get(ENV_NM_TEST_REGENERATE, '0') == '1') + v = os.environ.get(ENV_NM_TEST_REGENERATE, "0") == "1" elif name == ENV_NM_TEST_WITH_LINENO: - v = (os.environ.get(ENV_NM_TEST_WITH_LINENO, '0') == '1') - elif name in [ ENV_NM_TEST_ASAN_OPTIONS, ENV_NM_TEST_LSAN_OPTIONS, ENV_NM_TEST_UBSAN_OPTIONS ]: + v = os.environ.get(ENV_NM_TEST_WITH_LINENO, "0") == "1" + elif name in [ + ENV_NM_TEST_ASAN_OPTIONS, + ENV_NM_TEST_LSAN_OPTIONS, + ENV_NM_TEST_UBSAN_OPTIONS, + ]: v = os.environ.get(name, None) if v is None: if name == ENV_NM_TEST_ASAN_OPTIONS: - v = 'detect_leaks=1' - #v += ' fast_unwind_on_malloc=false' + v = "detect_leaks=1" + # v += ' fast_unwind_on_malloc=false' elif name == ENV_NM_TEST_LSAN_OPTIONS: - v = '' + v = "" elif name == ENV_NM_TEST_UBSAN_OPTIONS: - v = 'print_stacktrace=1:halt_on_error=1' + v = "print_stacktrace=1:halt_on_error=1" else: - assert(False) + assert False else: raise Exception() self._values[name] = v return v + conf = Configuration() ############################################################################### -class NMStubServer: +class NMStubServer: @staticmethod def _conn_get_main_object(conn): try: - return conn.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') + return conn.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) except: return None @@ -444,18 +466,22 @@ class NMStubServer: service_path = PathConfiguration.test_networkmanager_service_path() self._conn = dbus.SessionBus() env = os.environ.copy() - env['NM_TEST_NETWORKMANAGER_SERVICE_SEED'] = seed - p = subprocess.Popen([sys.executable, service_path], - stdin = subprocess.PIPE, - env = env) + env["NM_TEST_NETWORKMANAGER_SERVICE_SEED"] = seed + p = subprocess.Popen( + [sys.executable, service_path], stdin=subprocess.PIPE, env=env + ) start = NM.utils_get_timestamp_msec() while True: if p.poll() is not None: p.stdin.close() if p.returncode == 77: - raise unittest.SkipTest('the stub service %s exited with status 77' % (service_path)) - raise Exception('the stub service %s exited unexpectedly' % (service_path)) + raise unittest.SkipTest( + "the stub service %s exited with status 77" % (service_path) + ) + raise Exception( + "the stub service %s exited unexpectedly" % (service_path) + ) nmobj = self._conn_get_main_object(self._conn) if nmobj is not None: break @@ -463,10 +489,14 @@ class NMStubServer: p.stdin.close() p.kill() Util.popen_wait(p, 1) - raise Exception("after starting stub service the D-Bus name was not claimed in time") + raise Exception( + "after starting stub service the D-Bus name was not claimed in time" + ) self._nmobj = nmobj - self._nmiface = dbus.Interface(nmobj, "org.freedesktop.NetworkManager.LibnmGlibTest") + self._nmiface = dbus.Interface( + nmobj, "org.freedesktop.NetworkManager.LibnmGlibTest" + ) self._p = p def shutdown(self): @@ -481,14 +511,17 @@ class NMStubServer: if Util.popen_wait(p, 1) is None: raise Exception("Stub service did not exit in time") if self._conn_get_main_object(conn) is not None: - raise Exception("Stub service is not still here although it should shut down") + raise Exception( + "Stub service is not still here although it should shut down" + ) class _MethodProxy: def __init__(self, parent, method_name): self._parent = parent self._method_name = method_name + def __call__(self, *args, **kwargs): - dbus_iface = kwargs.pop('dbus_iface', None) + dbus_iface = kwargs.pop("dbus_iface", None) if dbus_iface is None: dbus_iface = self._parent._nmiface method = dbus_iface.get_dbus_method(self._method_name) @@ -504,60 +537,57 @@ class NMStubServer: raise AttributeError(member) return self._MethodProxy(self, member[3:]) - def addConnection(self, connection, do_verify_strict = True): + def addConnection(self, connection, do_verify_strict=True): return self.op_AddConnection(connection, do_verify_strict) def findConnections(self, **kwargs): if kwargs: lst = self.op_FindConnections(**kwargs) else: - lst = self.op_FindConnections( { } ) - return list([ (str(elem[0]), str(elem[1]), str(elem[2])) for elem in lst ]) + lst = self.op_FindConnections({}) + return list([(str(elem[0]), str(elem[1]), str(elem[2])) for elem in lst]) - def findConnectionUuid(self, con_id, required = True): + def findConnectionUuid(self, con_id, required=True): try: - u = Util.iter_single(self.findConnections(con_id = con_id))[1] - assert u, ("Invalid uuid %s" % (u)) + u = Util.iter_single(self.findConnections(con_id=con_id))[1] + assert u, "Invalid uuid %s" % (u) except Exception as e: if not required: return None - raise AssertionError("Unexpectedly not found connection %s: %s" % (con_id, str(e))) + raise AssertionError( + "Unexpectedly not found connection %s: %s" % (con_id, str(e)) + ) return u - def setProperty(self, path, propname, value, iface_name = None): + def setProperty(self, path, propname, value, iface_name=None): if iface_name is None: - iface_name = '' - self.op_SetProperties([ - (path, [ - (iface_name, [ - (propname, value), - ]), - ]), - ]) + iface_name = "" + self.op_SetProperties( + [(path, [(iface_name, [(propname, value),]),]),] + ) + ############################################################################### -class AsyncProcess(): - def __init__(self, - args, - env, - complete_cb, - max_waittime_msec = 20000): +class AsyncProcess: + def __init__(self, args, env, complete_cb, max_waittime_msec=20000): self._args = list(args) self._env = env self._complete_cb = complete_cb self._max_waittime_msec = max_waittime_msec def start(self): - if not hasattr(self, '_p'): + if not hasattr(self, "_p"): self._p_start_timestamp = NM.utils_get_timestamp_msec() - self._p_stdout_buf = b'' - self._p_stderr_buf = b'' - self._p = subprocess.Popen(self._args, - stdout = subprocess.PIPE, - stderr = subprocess.PIPE, - env = self._env) + self._p_stdout_buf = b"" + self._p_stderr_buf = b"" + self._p = subprocess.Popen( + self._args, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=self._env, + ) Util.buffer_set_nonblock(self._p.stdout) Util.buffer_set_nonblock(self._p.stderr) @@ -568,9 +598,11 @@ class AsyncProcess(): # frequently. # Worst case, we will think that the process did not time out, # when in fact it was running longer than max-waittime. - return self._max_waittime_msec - (NM.utils_get_timestamp_msec() - self._p_start_timestamp) + return self._max_waittime_msec - ( + NM.utils_get_timestamp_msec() - self._p_start_timestamp + ) - def poll(self, timeout = 0): + def poll(self, timeout=0): self.start() (return_code, b_stdout, b_stderr) = Util.popen_wait_read(self._p, timeout) @@ -578,9 +610,10 @@ class AsyncProcess(): self._p_stdout_buf += b_stdout self._p_stderr_buf += b_stderr - if return_code is None \ - and self._timeout_remaining_time() <= 0: - raise Exception("process is still running after timeout: %s" % (' '.join(self._args))) + if return_code is None and self._timeout_remaining_time() <= 0: + raise Exception( + "process is still running after timeout: %s" % (" ".join(self._args)) + ) return return_code def wait_and_complete(self): @@ -589,7 +622,9 @@ class AsyncProcess(): p = self._p self._p = None - (return_code, b_stdout, b_stderr) = Util.popen_wait_read(p, max(0, self._timeout_remaining_time()) / 1000) + (return_code, b_stdout, b_stderr) = Util.popen_wait_read( + p, max(0, self._timeout_remaining_time()) / 1000 + ) (stdout, stderr) = (p.stdout.read(), p.stderr.read()) p.stdout.close() p.stderr.close() @@ -602,35 +637,40 @@ class AsyncProcess(): if return_code is None: print(stdout) print(stderr) - raise Exception("process did not complete in time: %s" % (' '.join(self._args))) + raise Exception( + "process did not complete in time: %s" % (" ".join(self._args)) + ) self._complete_cb(self, return_code, stdout, stderr) + ############################################################################### + class NmTestBase(unittest.TestCase): pass + MAX_JOBS = 15 -class TestNmcli(NmTestBase): +class TestNmcli(NmTestBase): @staticmethod def _read_expected(filename): results_expect = [] content_expect = Util.file_read(filename) try: base_idx = 0 - size_prefix = 'size: '.encode('utf8') + size_prefix = "size: ".encode("utf8") while True: - if not content_expect[base_idx:base_idx + 10].startswith(size_prefix): + if not content_expect[base_idx : base_idx + 10].startswith(size_prefix): raise Exception("Unexpected token") j = base_idx + len(size_prefix) i = j if Util.python_has_version(3, 0): - eol = ord('\n') + eol = ord("\n") else: - eol = '\n' + eol = "\n" while content_expect[i] != eol: i += 1 i = i + 1 + int(content_expect[j:i]) @@ -643,52 +683,57 @@ class TestNmcli(NmTestBase): return content_expect, results_expect - def call_nmcli_l(self, - args, - check_on_disk = _DEFAULT_ARG, - fatal_warnings = _DEFAULT_ARG, - expected_returncode = _DEFAULT_ARG, - expected_stdout = _DEFAULT_ARG, - expected_stderr = _DEFAULT_ARG, - replace_stdout = None, - replace_stderr = None, - replace_cmd = None, - sort_lines_stdout = False, - extra_env = None, - sync_barrier = False): + def call_nmcli_l( + self, + args, + check_on_disk=_DEFAULT_ARG, + fatal_warnings=_DEFAULT_ARG, + expected_returncode=_DEFAULT_ARG, + expected_stdout=_DEFAULT_ARG, + expected_stderr=_DEFAULT_ARG, + replace_stdout=None, + replace_stderr=None, + replace_cmd=None, + sort_lines_stdout=False, + extra_env=None, + sync_barrier=False, + ): frame = sys._getframe(1) - for lang in [ 'C', 'pl' ]: - self._call_nmcli(args, - lang, - check_on_disk, - fatal_warnings, - expected_returncode, - expected_stdout, - expected_stderr, - replace_stdout, - replace_stderr, - replace_cmd, - sort_lines_stdout, - extra_env, - sync_barrier, - frame) - - - def call_nmcli(self, - args, - langs = None, - lang = None, - check_on_disk = _DEFAULT_ARG, - fatal_warnings = _DEFAULT_ARG, - expected_returncode = _DEFAULT_ARG, - expected_stdout = _DEFAULT_ARG, - expected_stderr = _DEFAULT_ARG, - replace_stdout = None, - replace_stderr = None, - replace_cmd = None, - sort_lines_stdout = False, - extra_env = None, - sync_barrier = None): + for lang in ["C", "pl"]: + self._call_nmcli( + args, + lang, + check_on_disk, + fatal_warnings, + expected_returncode, + expected_stdout, + expected_stderr, + replace_stdout, + replace_stderr, + replace_cmd, + sort_lines_stdout, + extra_env, + sync_barrier, + frame, + ) + + def call_nmcli( + self, + args, + langs=None, + lang=None, + check_on_disk=_DEFAULT_ARG, + fatal_warnings=_DEFAULT_ARG, + expected_returncode=_DEFAULT_ARG, + expected_stdout=_DEFAULT_ARG, + expected_stderr=_DEFAULT_ARG, + replace_stdout=None, + replace_stderr=None, + replace_cmd=None, + sort_lines_stdout=False, + extra_env=None, + sync_barrier=None, + ): frame = sys._getframe(1) @@ -696,43 +741,47 @@ class TestNmcli(NmTestBase): assert lang is None else: if lang is None: - lang = 'C' + lang = "C" langs = [lang] if sync_barrier is None: - sync_barrier = (len(langs) == 1) + sync_barrier = len(langs) == 1 for lang in langs: - self._call_nmcli(args, - lang, - check_on_disk, - fatal_warnings, - expected_returncode, - expected_stdout, - expected_stderr, - replace_stdout, - replace_stderr, - replace_cmd, - sort_lines_stdout, - extra_env, - sync_barrier, - frame) - - def _call_nmcli(self, - args, - lang, - check_on_disk, - fatal_warnings, - expected_returncode, - expected_stdout, - expected_stderr, - replace_stdout, - replace_stderr, - replace_cmd, - sort_lines_stdout, - extra_env, - sync_barrier, - frame): + self._call_nmcli( + args, + lang, + check_on_disk, + fatal_warnings, + expected_returncode, + expected_stdout, + expected_stderr, + replace_stdout, + replace_stderr, + replace_cmd, + sort_lines_stdout, + extra_env, + sync_barrier, + frame, + ) + + def _call_nmcli( + self, + args, + lang, + check_on_disk, + fatal_warnings, + expected_returncode, + expected_stdout, + expected_stderr, + replace_stdout, + replace_stderr, + replace_cmd, + sort_lines_stdout, + extra_env, + sync_barrier, + frame, + ): if sync_barrier: self.async_wait() @@ -741,51 +790,63 @@ class TestNmcli(NmTestBase): calling_num = self._calling_num.get(calling_fcn, 0) + 1 self._calling_num[calling_fcn] = calling_num - test_name = '%s-%03d' % (calling_fcn, calling_num) + test_name = "%s-%03d" % (calling_fcn, calling_num) # we cannot use frame.f_code.co_filename directly, because it might be different depending # on where the file lies and which is CWD. We still want to give the location of # the file, so that the user can easier find the source (when looking at the .expected files) - self.assertTrue(os.path.abspath(frame.f_code.co_filename).endswith('/'+PathConfiguration.canonical_script_filename())) + self.assertTrue( + os.path.abspath(frame.f_code.co_filename).endswith( + "/" + PathConfiguration.canonical_script_filename() + ) + ) if conf.get(ENV_NM_TEST_WITH_LINENO): - calling_location = '%s:%d:%s()/%d' % (PathConfiguration.canonical_script_filename(), frame.f_lineno, frame.f_code.co_name, calling_num) + calling_location = "%s:%d:%s()/%d" % ( + PathConfiguration.canonical_script_filename(), + frame.f_lineno, + frame.f_code.co_name, + calling_num, + ) else: - calling_location = '%s:%s()/%d' % (PathConfiguration.canonical_script_filename(), frame.f_code.co_name, calling_num) - - if lang is None or lang == 'C': - lang = 'C' - language = '' - elif lang == 'de': - lang = 'de_DE.utf8' - language = 'de' - elif lang == 'pl': - lang = 'pl_PL.UTF-8' - language = 'pl' + calling_location = "%s:%s()/%d" % ( + PathConfiguration.canonical_script_filename(), + frame.f_code.co_name, + calling_num, + ) + + if lang is None or lang == "C": + lang = "C" + language = "" + elif lang == "de": + lang = "de_DE.utf8" + language = "de" + elif lang == "pl": + lang = "pl_PL.UTF-8" + language = "pl" else: - self.fail('invalid language %s' % (lang)) + self.fail("invalid language %s" % (lang)) env = {} if extra_env is not None: for k, v in extra_env.items(): env[k] = v - for k in ['LD_LIBRARY_PATH', - 'DBUS_SESSION_BUS_ADDRESS']: + for k in ["LD_LIBRARY_PATH", "DBUS_SESSION_BUS_ADDRESS"]: val = os.environ.get(k, None) if val is not None: env[k] = val - env['LANG'] = lang - env['LANGUAGE'] = language - env['LIBNM_USE_SESSION_BUS'] = '1' - env['LIBNM_USE_NO_UDEV'] = '1' - env['TERM'] = 'linux' - env['ASAN_OPTIONS'] = conf.get(ENV_NM_TEST_ASAN_OPTIONS) - env['LSAN_OPTIONS'] = conf.get(ENV_NM_TEST_LSAN_OPTIONS) - env['LBSAN_OPTIONS'] = conf.get(ENV_NM_TEST_UBSAN_OPTIONS) - env['XDG_CONFIG_HOME'] = PathConfiguration.srcdir() - env['NM_TEST_CALLING_NUM'] = str(calling_num) + env["LANG"] = lang + env["LANGUAGE"] = language + env["LIBNM_USE_SESSION_BUS"] = "1" + env["LIBNM_USE_NO_UDEV"] = "1" + env["TERM"] = "linux" + env["ASAN_OPTIONS"] = conf.get(ENV_NM_TEST_ASAN_OPTIONS) + env["LSAN_OPTIONS"] = conf.get(ENV_NM_TEST_LSAN_OPTIONS) + env["LBSAN_OPTIONS"] = conf.get(ENV_NM_TEST_UBSAN_OPTIONS) + env["XDG_CONFIG_HOME"] = PathConfiguration.srcdir() + env["NM_TEST_CALLING_NUM"] = str(calling_num) if fatal_warnings is _DEFAULT_ARG or fatal_warnings: - env['G_DEBUG'] = 'fatal-warnings' + env["G_DEBUG"] = "fatal-warnings" args = [conf.get(ENV_NM_TEST_CLIENT_NMCLI_PATH)] + list(args) @@ -797,9 +858,17 @@ class TestNmcli(NmTestBase): replace_cmd = list(replace_cmd) if check_on_disk is _DEFAULT_ARG: - check_on_disk = ( expected_returncode is _DEFAULT_ARG - and (expected_stdout is _DEFAULT_ARG or expected_stdout is _UNSTABLE_OUTPUT) - and (expected_stderr is _DEFAULT_ARG or expected_stderr is _UNSTABLE_OUTPUT)) + check_on_disk = ( + expected_returncode is _DEFAULT_ARG + and ( + expected_stdout is _DEFAULT_ARG + or expected_stdout is _UNSTABLE_OUTPUT + ) + and ( + expected_stderr is _DEFAULT_ARG + or expected_stderr is _UNSTABLE_OUTPUT + ) + ) if expected_returncode is _DEFAULT_ARG: expected_returncode = None if expected_stdout is _DEFAULT_ARG: @@ -810,26 +879,24 @@ class TestNmcli(NmTestBase): results_idx = len(self._results) self._results.append(None) - def complete_cb(async_job, - returncode, - stdout, - stderr): + def complete_cb(async_job, returncode, stdout, stderr): if expected_stdout is _UNSTABLE_OUTPUT: - stdout = '<UNSTABLE OUTPUT>'.encode('utf-8') + stdout = "<UNSTABLE OUTPUT>".encode("utf-8") else: stdout = Util.replace_text(stdout, replace_stdout) if expected_stderr is _UNSTABLE_OUTPUT: - stderr = '<UNSTABLE OUTPUT>'.encode('utf-8') + stderr = "<UNSTABLE OUTPUT>".encode("utf-8") else: stderr = Util.replace_text(stderr, replace_stderr) if sort_lines_stdout: - stdout = b'\n'.join(sorted(stdout.split(b'\n'))) + stdout = b"\n".join(sorted(stdout.split(b"\n"))) - ignore_l10n_diff = ( lang != 'C' - and not conf.get(ENV_NM_TEST_CLIENT_CHECK_L10N)) + ignore_l10n_diff = lang != "C" and not conf.get( + ENV_NM_TEST_CLIENT_CHECK_L10N + ) if expected_stderr is not None and expected_stderr is not _UNSTABLE_OUTPUT: if expected_stderr != stderr: @@ -851,47 +918,53 @@ class TestNmcli(NmTestBase): self.assertNotEqual(returncode, -5) elif fatal_warnings: if expected_returncode is None: - self.assertEqual(returncode, -5) + self.assertEqual(returncode, -5) if check_on_disk: - cmd = '$NMCLI %s' % (' '.join([Util.quote(a) for a in args[1:]])) + cmd = "$NMCLI %s" % (" ".join([Util.quote(a) for a in args[1:]])) cmd = Util.replace_text(cmd, replace_cmd) if returncode < 0: - returncode_str = '%d (SIGNAL %s)' % (returncode, Util.signal_no_to_str(-returncode)) + returncode_str = "%d (SIGNAL %s)" % ( + returncode, + Util.signal_no_to_str(-returncode), + ) else: - returncode_str = '%d' % (returncode) - - content = ('location: %s\n' % (calling_location)).encode('utf8') + \ - ('cmd: %s\n' % (cmd)).encode('utf8') + \ - ('lang: %s\n' % (lang)).encode('utf8') + \ - ('returncode: %s\n' % (returncode_str)).encode('utf8') + returncode_str = "%d" % (returncode) + + content = ( + ("location: %s\n" % (calling_location)).encode("utf8") + + ("cmd: %s\n" % (cmd)).encode("utf8") + + ("lang: %s\n" % (lang)).encode("utf8") + + ("returncode: %s\n" % (returncode_str)).encode("utf8") + ) if len(stdout) > 0: - content += ('stdout: %d bytes\n>>>\n' % (len(stdout))).encode('utf8') + \ - stdout + \ - '\n<<<\n'.encode('utf8') + content += ( + ("stdout: %d bytes\n>>>\n" % (len(stdout))).encode("utf8") + + stdout + + "\n<<<\n".encode("utf8") + ) if len(stderr) > 0: - content += ('stderr: %d bytes\n>>>\n' % (len(stderr))).encode('utf8') + \ - stderr + \ - '\n<<<\n'.encode('utf8') - content = ('size: %s\n' % (len(content))).encode('utf8') + \ - content + content += ( + ("stderr: %d bytes\n>>>\n" % (len(stderr))).encode("utf8") + + stderr + + "\n<<<\n".encode("utf8") + ) + content = ("size: %s\n" % (len(content))).encode("utf8") + content self._results[results_idx] = { - 'test_name' : test_name, - 'ignore_l10n_diff' : ignore_l10n_diff, - 'content' : content, + "test_name": test_name, + "ignore_l10n_diff": ignore_l10n_diff, + "content": content, } - async_job = AsyncProcess(args = args, - env = env, - complete_cb = complete_cb) + async_job = AsyncProcess(args=args, env=env, complete_cb=complete_cb) self._async_jobs.append(async_job) - self.async_start(wait_all = sync_barrier) + self.async_start(wait_all=sync_barrier) - def async_start(self, wait_all = False): + def async_start(self, wait_all=False): while True: @@ -922,13 +995,13 @@ class TestNmcli(NmTestBase): # completes. Note that poll() itself will raise an exception if a # jobs times out. for async_job in Util.random_job(jobs_running): - if async_job.poll(timeout = 0.03) is not None: + if async_job.poll(timeout=0.03) is not None: self._async_jobs.remove(async_job) async_job.wait_and_complete() break def async_wait(self): - return self.async_start(wait_all = True) + return self.async_start(wait_all=True) def _nm_test_pre(self): self._calling_num = {} @@ -955,7 +1028,12 @@ class TestNmcli(NmTestBase): test_name = self._testMethodName - filename = os.path.abspath(PathConfiguration.srcdir() + '/test-client.check-on-disk/' + test_name + '.expected') + filename = os.path.abspath( + PathConfiguration.srcdir() + + "/test-client.check-on-disk/" + + test_name + + ".expected" + ) regenerate = conf.get(ENV_NM_TEST_REGENERATE) @@ -963,41 +1041,71 @@ class TestNmcli(NmTestBase): if results_expect is None: if not regenerate: - self.fail("Failed to parse expected file '%s'. Let the test write the file by rerunning with NM_TEST_REGENERATE=1" % (filename)) + self.fail( + "Failed to parse expected file '%s'. Let the test write the file by rerunning with NM_TEST_REGENERATE=1" + % (filename) + ) else: for i in range(0, min(len(results_expect), len(results))): n = results[i] - if results_expect[i] == n['content']: + if results_expect[i] == n["content"]: continue if regenerate: continue - if n['ignore_l10n_diff']: - skip_test_for_l10n_diff.append(n['test_name']) + if n["ignore_l10n_diff"]: + skip_test_for_l10n_diff.append(n["test_name"]) continue - print("\n\n\nThe file '%s' does not have the expected content:" % (filename)) - print("ACTUAL OUTPUT:\n[[%s]]\n" % (n['content'])) + print( + "\n\n\nThe file '%s' does not have the expected content:" + % (filename) + ) + print("ACTUAL OUTPUT:\n[[%s]]\n" % (n["content"])) print("EXPECT OUTPUT:\n[[%s]]\n" % (results_expect[i])) - print("Let the test write the file by rerunning with NM_TEST_REGENERATE=1") - print("See howto in %s for details.\n" % (PathConfiguration.canonical_script_filename())) + print( + "Let the test write the file by rerunning with NM_TEST_REGENERATE=1" + ) + print( + "See howto in %s for details.\n" + % (PathConfiguration.canonical_script_filename()) + ) sys.stdout.flush() - self.fail("Unexpected output of command, expected %s. Rerun test with NM_TEST_REGENERATE=1 to regenerate files" % (filename)) + self.fail( + "Unexpected output of command, expected %s. Rerun test with NM_TEST_REGENERATE=1 to regenerate files" + % (filename) + ) if len(results_expect) != len(results): if not regenerate: - print("\n\n\nThe number of tests in %s does not match the expected content (%s vs %s):" % (filename, len(results_expect), len(results))) + print( + "\n\n\nThe number of tests in %s does not match the expected content (%s vs %s):" + % (filename, len(results_expect), len(results)) + ) if len(results_expect) < len(results): - print("ACTUAL OUTPUT:\n[[%s]]\n" % (results[len(results_expect)]['content'])) + print( + "ACTUAL OUTPUT:\n[[%s]]\n" + % (results[len(results_expect)]["content"]) + ) else: - print("EXPECT OUTPUT:\n[[%s]]\n" % (results_expect[len(results)])) - print("Let the test write the file by rerunning with NM_TEST_REGENERATE=1") - print("See howto in %s for details.\n" % (PathConfiguration.canonical_script_filename())) + print( + "EXPECT OUTPUT:\n[[%s]]\n" % (results_expect[len(results)]) + ) + print( + "Let the test write the file by rerunning with NM_TEST_REGENERATE=1" + ) + print( + "See howto in %s for details.\n" + % (PathConfiguration.canonical_script_filename()) + ) sys.stdout.flush() - self.fail("Unexpected output of command, expected %s. Rerun test with NM_TEST_REGENERATE=1 to regenerate files" % (filename)) + self.fail( + "Unexpected output of command, expected %s. Rerun test with NM_TEST_REGENERATE=1 to regenerate files" + % (filename) + ) if regenerate: - content_new = b''.join([r['content'] for r in results]) + content_new = b"".join([r["content"] for r in results]) if content_new != content_expect: try: - with open(filename, 'wb') as content_file: + with open(filename, "wb") as content_file: content_file.write(content_new) except Exception as e: self.fail("Failure to write '%s': %s" % (filename, e)) @@ -1006,102 +1114,98 @@ class TestNmcli(NmTestBase): # nmcli loads translations from the installation path. This failure commonly # happens because you did not install the binary in the --prefix, before # running the test. Hence, translations are not available or differ. - self.skipTest("Skipped asserting for localized tests %s. Set NM_TEST_CLIENT_CHECK_L10N=1 to force fail." % (','.join(skip_test_for_l10n_diff))) + self.skipTest( + "Skipped asserting for localized tests %s. Set NM_TEST_CLIENT_CHECK_L10N=1 to force fail." + % (",".join(skip_test_for_l10n_diff)) + ) def nm_test(func): def f(self): self._nm_test_pre() func(self) self._nm_test_post() + return f def setUp(self): if not dbus_session_inited: - self.skipTest("Own D-Bus session for testing is not initialized. Do you have dbus-run-session available?") + self.skipTest( + "Own D-Bus session for testing is not initialized. Do you have dbus-run-session available?" + ) if NM is None: self.skipTest("gi.NM is not available. Did you build with introspection?") def init_001(self): - self.srv.op_AddObj('WiredDevice', - iface = 'eth0') - self.srv.op_AddObj('WiredDevice', - iface = 'eth1') - self.srv.op_AddObj('WifiDevice', - iface = 'wlan0') - self.srv.op_AddObj('WifiDevice', - iface = 'wlan1') + self.srv.op_AddObj("WiredDevice", iface="eth0") + self.srv.op_AddObj("WiredDevice", iface="eth1") + self.srv.op_AddObj("WifiDevice", iface="wlan0") + self.srv.op_AddObj("WifiDevice", iface="wlan1") # add another device with an identical ifname. The D-Bus API itself # does not enforce the ifnames are unique. - self.srv.op_AddObj('WifiDevice', - ident = 'wlan1/x', - iface = 'wlan1') + self.srv.op_AddObj("WifiDevice", ident="wlan1/x", iface="wlan1") - self.srv.op_AddObj('WifiAp', - device = 'wlan0', - rsnf = 0x0) + self.srv.op_AddObj("WifiAp", device="wlan0", rsnf=0x0) - self.srv.op_AddObj('WifiAp', - device = 'wlan0') + self.srv.op_AddObj("WifiAp", device="wlan0") - NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags') + NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags") rsnf = 0x0 rsnf = rsnf | NM_AP_FLAGS.PAIR_TKIP rsnf = rsnf | NM_AP_FLAGS.PAIR_CCMP rsnf = rsnf | NM_AP_FLAGS.GROUP_TKIP rsnf = rsnf | NM_AP_FLAGS.GROUP_CCMP rsnf = rsnf | NM_AP_FLAGS.KEY_MGMT_SAE - self.srv.op_AddObj('WifiAp', - device = 'wlan0', - wpaf = 0x0, - rsnf = rsnf) + self.srv.op_AddObj("WifiAp", device="wlan0", wpaf=0x0, rsnf=rsnf) - self.srv.op_AddObj('WifiAp', - device = 'wlan1') + self.srv.op_AddObj("WifiAp", device="wlan1") - self.srv.addConnection( { - 'connection': { - 'type': '802-3-ethernet', - 'id': 'con-1', - }, - }) + self.srv.addConnection( + {"connection": {"type": "802-3-ethernet", "id": "con-1",},} + ) @nm_test def test_001(self): self.call_nmcli_l([]) - self.call_nmcli_l(['-f', 'AP', '-mode', 'multiline', '-p', 'd', 'show', 'wlan0']) + self.call_nmcli_l( + ["-f", "AP", "-mode", "multiline", "-p", "d", "show", "wlan0"] + ) - self.call_nmcli_l(['c', 's']) + self.call_nmcli_l(["c", "s"]) - self.call_nmcli_l(['bogus', 's']) + self.call_nmcli_l(["bogus", "s"]) for mode in Util.iter_nmcli_output_modes(): - self.call_nmcli_l(mode + ['general', 'permissions']) + self.call_nmcli_l(mode + ["general", "permissions"]) @nm_test def test_002(self): self.init_001() - self.call_nmcli_l(['d']) + self.call_nmcli_l(["d"]) - self.call_nmcli_l(['-f', 'all', 'd']) + self.call_nmcli_l(["-f", "all", "d"]) self.call_nmcli_l([]) - self.call_nmcli_l(['-f', 'AP', '-mode', 'multiline', 'd', 'show', 'wlan0']) - self.call_nmcli_l(['-f', 'AP', '-mode', 'multiline', '-p', 'd', 'show', 'wlan0']) - self.call_nmcli_l(['-f', 'AP', '-mode', 'multiline', '-t', 'd', 'show', 'wlan0']) - self.call_nmcli_l(['-f', 'AP', '-mode', 'tabular', 'd', 'show', 'wlan0']) - self.call_nmcli_l(['-f', 'AP', '-mode', 'tabular', '-p', 'd', 'show', 'wlan0']) - self.call_nmcli_l(['-f', 'AP', '-mode', 'tabular', '-t', 'd', 'show', 'wlan0']) + self.call_nmcli_l(["-f", "AP", "-mode", "multiline", "d", "show", "wlan0"]) + self.call_nmcli_l( + ["-f", "AP", "-mode", "multiline", "-p", "d", "show", "wlan0"] + ) + self.call_nmcli_l( + ["-f", "AP", "-mode", "multiline", "-t", "d", "show", "wlan0"] + ) + self.call_nmcli_l(["-f", "AP", "-mode", "tabular", "d", "show", "wlan0"]) + self.call_nmcli_l(["-f", "AP", "-mode", "tabular", "-p", "d", "show", "wlan0"]) + self.call_nmcli_l(["-f", "AP", "-mode", "tabular", "-t", "d", "show", "wlan0"]) - self.call_nmcli_l(['-f', 'ALL', 'd', 'wifi']) + self.call_nmcli_l(["-f", "ALL", "d", "wifi"]) - self.call_nmcli_l(['c']) + self.call_nmcli_l(["c"]) - self.call_nmcli_l(['c', 's', 'con-1']) + self.call_nmcli_l(["c", "s", "con-1"]) @nm_test def test_003(self): @@ -1109,36 +1213,76 @@ class TestNmcli(NmTestBase): replace_uuids = [] - replace_uuids.append((Util.memoize_nullary(lambda: self.srv.findConnectionUuid('con-xx1')), 'UUID-con-xx1-REPLACED-REPLACED-REPLA')) - - self.call_nmcli(['c', 'add', 'type', 'ethernet', 'ifname', '*', 'con-name', 'con-xx1'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(['c', 's'], - replace_stdout = replace_uuids) - - replace_uuids.append((Util.memoize_nullary(lambda: self.srv.findConnectionUuid('con-gsm1')), 'UUID-con-gsm1-REPLACED-REPLACED-REPL')) - - self.call_nmcli(['connection', 'add', 'type', 'gsm', 'autoconnect', 'no', 'con-name', 'con-gsm1', 'ifname', '*', 'apn', 'xyz.con-gsm1', 'serial.baud', '5', 'serial.send-delay', '100', 'serial.pari', '1', 'ipv4.dns-options', ' '], - replace_stdout = replace_uuids) - - replace_uuids.append((Util.memoize_nullary(lambda: self.srv.findConnectionUuid('ethernet')), 'UUID-ethernet-REPLACED-REPLACED-REPL')) - - self.call_nmcli(['c', 'add', 'type', 'ethernet', 'ifname', '*'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(['c', 's'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(['-f', 'ALL', 'c', 's'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(['--complete-args', '-f', 'ALL', 'c', 's', ''], - replace_stdout = replace_uuids, - sort_lines_stdout = True) - - self.call_nmcli_l(['con', 's', 'con-gsm1'], - replace_stdout = replace_uuids) + replace_uuids.append( + ( + Util.memoize_nullary(lambda: self.srv.findConnectionUuid("con-xx1")), + "UUID-con-xx1-REPLACED-REPLACED-REPLA", + ) + ) + + self.call_nmcli( + ["c", "add", "type", "ethernet", "ifname", "*", "con-name", "con-xx1"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l(["c", "s"], replace_stdout=replace_uuids) + + replace_uuids.append( + ( + Util.memoize_nullary(lambda: self.srv.findConnectionUuid("con-gsm1")), + "UUID-con-gsm1-REPLACED-REPLACED-REPL", + ) + ) + + self.call_nmcli( + [ + "connection", + "add", + "type", + "gsm", + "autoconnect", + "no", + "con-name", + "con-gsm1", + "ifname", + "*", + "apn", + "xyz.con-gsm1", + "serial.baud", + "5", + "serial.send-delay", + "100", + "serial.pari", + "1", + "ipv4.dns-options", + " ", + ], + replace_stdout=replace_uuids, + ) + + replace_uuids.append( + ( + Util.memoize_nullary(lambda: self.srv.findConnectionUuid("ethernet")), + "UUID-ethernet-REPLACED-REPLACED-REPL", + ) + ) + + self.call_nmcli( + ["c", "add", "type", "ethernet", "ifname", "*"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l(["c", "s"], replace_stdout=replace_uuids) + + self.call_nmcli_l(["-f", "ALL", "c", "s"], replace_stdout=replace_uuids) + + self.call_nmcli_l( + ["--complete-args", "-f", "ALL", "c", "s", ""], + replace_stdout=replace_uuids, + sort_lines_stdout=True, + ) + + self.call_nmcli_l(["con", "s", "con-gsm1"], replace_stdout=replace_uuids) # activate the same profile on multiple devices. Our stub-implmentation # is fine with that... although NetworkManager service would reject @@ -1150,72 +1294,91 @@ class TestNmcli(NmTestBase): # does not allow that multiple profiles *stay* connected at the same # time, there is always the possibility that a profile is activating/active # on a device, while also activating/deactivating in parallel. - for dev in ['eth0', 'eth1']: - self.call_nmcli(['con', 'up', 'ethernet', 'ifname', dev]) + for dev in ["eth0", "eth1"]: + self.call_nmcli(["con", "up", "ethernet", "ifname", dev]) - self.call_nmcli_l(['con'], - replace_stdout = replace_uuids) + self.call_nmcli_l(["con"], replace_stdout=replace_uuids) - self.call_nmcli_l(['-f', 'ALL', 'con'], - replace_stdout = replace_uuids) + self.call_nmcli_l(["-f", "ALL", "con"], replace_stdout=replace_uuids) - self.call_nmcli_l(['-f', 'ALL', 'con', 's', '-a'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "con", "s", "-a"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(['-f', 'ACTIVE-PATH,DEVICE,UUID', 'con', 's', '-act'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ACTIVE-PATH,DEVICE,UUID", "con", "s", "-act"], + replace_stdout=replace_uuids, + ) - self.call_nmcli_l(['-f', 'UUID,NAME', 'con', 's', '--active'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "UUID,NAME", "con", "s", "--active"], + replace_stdout=replace_uuids, + ) - self.call_nmcli_l(['-f', 'ALL', 'con', 's', 'ethernet'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "con", "s", "ethernet"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(['-f', 'GENERAL.STATE', 'con', 's', 'ethernet'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "GENERAL.STATE", "con", "s", "ethernet"], + replace_stdout=replace_uuids, + ) - self.call_nmcli_l(['con', 's', 'ethernet'], - replace_stdout = replace_uuids) + self.call_nmcli_l(["con", "s", "ethernet"], replace_stdout=replace_uuids) - self.call_nmcli_l(['-f', 'ALL', 'dev', 'status'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "dev", "status"], replace_stdout=replace_uuids + ) # test invalid call ('s' abbrevates 'status' and not 'show' - self.call_nmcli_l(['-f', 'ALL', 'dev', 's', 'eth0'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "dev", "s", "eth0"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(['-f', 'ALL', 'dev', 'show', 'eth0'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "dev", "show", "eth0"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(['-f', 'ALL', '-t', 'dev', 'show', 'eth0'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + ["-f", "ALL", "-t", "dev", "show", "eth0"], replace_stdout=replace_uuids + ) self.async_wait() - self.srv.setProperty('/org/freedesktop/NetworkManager/ActiveConnection/1', - 'State', - dbus.UInt32(NM.ActiveConnectionState.DEACTIVATING)) + self.srv.setProperty( + "/org/freedesktop/NetworkManager/ActiveConnection/1", + "State", + dbus.UInt32(NM.ActiveConnectionState.DEACTIVATING), + ) for i in [0, 1]: if i == 1: self.async_wait() - self.srv.op_ConnectionSetVisible(False, con_id = 'ethernet') + self.srv.op_ConnectionSetVisible(False, con_id="ethernet") for mode in Util.iter_nmcli_output_modes(): - self.call_nmcli_l(mode + ['-f', 'ALL', 'con'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["-f", "ALL", "con"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(mode + ['-f', 'UUID,TYPE', 'con'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["-f", "UUID,TYPE", "con"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(mode + ['con', 's', 'ethernet'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["con", "s", "ethernet"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(mode + ['c', 's', '/org/freedesktop/NetworkManager/ActiveConnection/1'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + + ["c", "s", "/org/freedesktop/NetworkManager/ActiveConnection/1"], + replace_stdout=replace_uuids, + ) - self.call_nmcli_l(mode + ['-f', 'all', 'dev', 'show', 'eth0'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["-f", "all", "dev", "show", "eth0"], + replace_stdout=replace_uuids, + ) @nm_test def test_004(self): @@ -1223,131 +1386,275 @@ class TestNmcli(NmTestBase): replace_uuids = [] - replace_uuids.append((Util.memoize_nullary(lambda: self.srv.findConnectionUuid('con-xx1')), 'UUID-con-xx1-REPLACED-REPLACED-REPLA')) - - self.call_nmcli(['c', 'add', 'type', 'wifi', 'ifname', '*', 'ssid', 'foobar', 'con-name', 'con-xx1'], - replace_stdout = replace_uuids) - - self.call_nmcli(['connection', 'mod', 'con-xx1', 'ip.gateway', '']) - self.call_nmcli(['connection', 'mod', 'con-xx1', 'ipv4.gateway', '172.16.0.1'], lang = 'pl') - self.call_nmcli(['connection', 'mod', 'con-xx1', 'ipv6.gateway', '::99']) - self.call_nmcli(['connection', 'mod', 'con-xx1', '802.abc', '']) - self.call_nmcli(['connection', 'mod', 'con-xx1', '802-11-wireless.band', 'a']) - self.call_nmcli(['connection', 'mod', 'con-xx1', 'ipv4.addresses', '192.168.77.5/24', 'ipv4.routes', '2.3.4.5/32 192.168.77.1', 'ipv6.addresses', '1:2:3:4::6/64', 'ipv6.routes', '1:2:3:4:5:6::5/128']) - self.call_nmcli_l(['con', 's', 'con-xx1'], - replace_stdout = replace_uuids) + replace_uuids.append( + ( + Util.memoize_nullary(lambda: self.srv.findConnectionUuid("con-xx1")), + "UUID-con-xx1-REPLACED-REPLACED-REPLA", + ) + ) + + self.call_nmcli( + [ + "c", + "add", + "type", + "wifi", + "ifname", + "*", + "ssid", + "foobar", + "con-name", + "con-xx1", + ], + replace_stdout=replace_uuids, + ) + + self.call_nmcli(["connection", "mod", "con-xx1", "ip.gateway", ""]) + self.call_nmcli( + ["connection", "mod", "con-xx1", "ipv4.gateway", "172.16.0.1"], lang="pl" + ) + self.call_nmcli(["connection", "mod", "con-xx1", "ipv6.gateway", "::99"]) + self.call_nmcli(["connection", "mod", "con-xx1", "802.abc", ""]) + self.call_nmcli(["connection", "mod", "con-xx1", "802-11-wireless.band", "a"]) + self.call_nmcli( + [ + "connection", + "mod", + "con-xx1", + "ipv4.addresses", + "192.168.77.5/24", + "ipv4.routes", + "2.3.4.5/32 192.168.77.1", + "ipv6.addresses", + "1:2:3:4::6/64", + "ipv6.routes", + "1:2:3:4:5:6::5/128", + ] + ) + self.call_nmcli_l(["con", "s", "con-xx1"], replace_stdout=replace_uuids) self.async_wait() - replace_uuids.append((Util.memoize_nullary(lambda: self.srv.findConnectionUuid('con-vpn-1')), 'UUID-con-vpn-1-REPLACED-REPLACED-REP')) - - self.call_nmcli(['connection', 'add', 'type', 'vpn', 'con-name', 'con-vpn-1', 'ifname', '*', 'vpn-type', 'openvpn', 'vpn.data', 'key1 = val1, key2 = val2, key3=val3'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(['con', 's'], - replace_stdout = replace_uuids) - self.call_nmcli_l(['con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) - - self.call_nmcli(['con', 'up', 'con-xx1']) - self.call_nmcli_l(['con', 's'], - replace_stdout = replace_uuids) - - self.call_nmcli(['con', 'up', 'con-vpn-1']) - self.call_nmcli_l(['con', 's'], - replace_stdout = replace_uuids) - self.call_nmcli_l(['con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) + replace_uuids.append( + ( + Util.memoize_nullary(lambda: self.srv.findConnectionUuid("con-vpn-1")), + "UUID-con-vpn-1-REPLACED-REPLACED-REP", + ) + ) + + self.call_nmcli( + [ + "connection", + "add", + "type", + "vpn", + "con-name", + "con-vpn-1", + "ifname", + "*", + "vpn-type", + "openvpn", + "vpn.data", + "key1 = val1, key2 = val2, key3=val3", + ], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l(["con", "s"], replace_stdout=replace_uuids) + self.call_nmcli_l(["con", "s", "con-vpn-1"], replace_stdout=replace_uuids) + + self.call_nmcli(["con", "up", "con-xx1"]) + self.call_nmcli_l(["con", "s"], replace_stdout=replace_uuids) + + self.call_nmcli(["con", "up", "con-vpn-1"]) + self.call_nmcli_l(["con", "s"], replace_stdout=replace_uuids) + self.call_nmcli_l(["con", "s", "con-vpn-1"], replace_stdout=replace_uuids) self.async_wait() - self.srv.setProperty('/org/freedesktop/NetworkManager/ActiveConnection/2', - 'VpnState', - dbus.UInt32(NM.VpnConnectionState.ACTIVATED)) + self.srv.setProperty( + "/org/freedesktop/NetworkManager/ActiveConnection/2", + "VpnState", + dbus.UInt32(NM.VpnConnectionState.ACTIVATED), + ) - uuids = Util.replace_text_sort_list([ c[1] for c in self.srv.findConnections() ], replace_uuids) + uuids = Util.replace_text_sort_list( + [c[1] for c in self.srv.findConnections()], replace_uuids + ) for mode in Util.iter_nmcli_output_modes(): - self.call_nmcli_l(mode + ['con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["con", "s", "con-vpn-1"], replace_stdout=replace_uuids + ) + self.call_nmcli_l( + mode + ["con", "s", "con-vpn-1"], replace_stdout=replace_uuids + ) - self.call_nmcli_l(mode + ['-f', 'ALL', 'con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) + self.call_nmcli_l( + mode + ["-f", "ALL", "con", "s", "con-vpn-1"], + replace_stdout=replace_uuids, + ) # This only filters 'vpn' settings from the connection profile. # Contrary to '-f GENERAL' below, it does not show the properties of # the activated VPN connection. This is a nmcli bug. - self.call_nmcli_l(mode + ['-f', 'VPN', 'con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'GENERAL', 'con', 's', 'con-vpn-1'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['dev', 's'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'all', 'dev', 'status'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['dev', 'show'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'all', 'dev', 'show'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['dev', 'show', 'wlan0'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'all', 'dev', 'show', 'wlan0'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'GENERAL,GENERAL.HWADDR,WIFI-PROPERTIES', 'dev', 'show', 'wlan0'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'GENERAL,GENERAL.HWADDR,WIFI-PROPERTIES', 'dev', 'show', 'wlan0'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'DEVICE,TYPE,DBUS-PATH', 'dev'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'ALL', 'device', 'wifi', 'list' ], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'COMMON', 'device', 'wifi', 'list' ], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'NAME,SSID,SSID-HEX,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY,WPA-FLAGS,RSN-FLAGS,DEVICE,ACTIVE,IN-USE,DBUS-PATH', - 'device', 'wifi', 'list'], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'ALL', 'device', 'wifi', 'list', 'bssid', 'C0:E2:BE:E8:EF:B6'], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'COMMON', 'device', 'wifi', 'list', 'bssid', 'C0:E2:BE:E8:EF:B6'], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'NAME,SSID,SSID-HEX,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY,WPA-FLAGS,RSN-FLAGS,DEVICE,ACTIVE,IN-USE,DBUS-PATH', - 'device', 'wifi', 'list', 'bssid', 'C0:E2:BE:E8:EF:B6'], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'ALL', 'device', 'show', 'wlan0' ], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'COMMON', 'device', 'show', 'wlan0' ], - replace_stdout = replace_uuids) - self.call_nmcli_l(mode + ['-f', 'GENERAL,CAPABILITIES,WIFI-PROPERTIES,AP,WIRED-PROPERTIES,WIMAX-PROPERTIES,NSP,IP4,DHCP4,IP6,DHCP6,BOND,TEAM,BRIDGE,VLAN,BLUETOOTH,CONNECTIONS', 'device', 'show', 'wlan0' ], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['dev', 'lldp', 'list', 'ifname', 'eth0'], - replace_stdout = replace_uuids) - - self.call_nmcli_l(mode + ['-f', 'connection.id,connection.uuid,connection.type,connection.interface-name,802-3-ethernet.mac-address,vpn.user-name', 'connection', 'show' ] + uuids, - replace_stdout = replace_uuids, - replace_cmd = replace_uuids) + self.call_nmcli_l( + mode + ["-f", "VPN", "con", "s", "con-vpn-1"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + ["-f", "GENERAL", "con", "s", "con-vpn-1"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l(mode + ["dev", "s"], replace_stdout=replace_uuids) + + self.call_nmcli_l( + mode + ["-f", "all", "dev", "status"], replace_stdout=replace_uuids + ) + + self.call_nmcli_l(mode + ["dev", "show"], replace_stdout=replace_uuids) + + self.call_nmcli_l( + mode + ["-f", "all", "dev", "show"], replace_stdout=replace_uuids + ) + + self.call_nmcli_l( + mode + ["dev", "show", "wlan0"], replace_stdout=replace_uuids + ) + + self.call_nmcli_l( + mode + ["-f", "all", "dev", "show", "wlan0"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + + [ + "-f", + "GENERAL,GENERAL.HWADDR,WIFI-PROPERTIES", + "dev", + "show", + "wlan0", + ], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + + [ + "-f", + "GENERAL,GENERAL.HWADDR,WIFI-PROPERTIES", + "dev", + "show", + "wlan0", + ], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + ["-f", "DEVICE,TYPE,DBUS-PATH", "dev"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + ["-f", "ALL", "device", "wifi", "list"], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + ["-f", "COMMON", "device", "wifi", "list"], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + + [ + "-f", + "NAME,SSID,SSID-HEX,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY,WPA-FLAGS,RSN-FLAGS,DEVICE,ACTIVE,IN-USE,DBUS-PATH", + "device", + "wifi", + "list", + ], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + + ["-f", "ALL", "device", "wifi", "list", "bssid", "C0:E2:BE:E8:EF:B6"], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + + [ + "-f", + "COMMON", + "device", + "wifi", + "list", + "bssid", + "C0:E2:BE:E8:EF:B6", + ], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + + [ + "-f", + "NAME,SSID,SSID-HEX,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY,WPA-FLAGS,RSN-FLAGS,DEVICE,ACTIVE,IN-USE,DBUS-PATH", + "device", + "wifi", + "list", + "bssid", + "C0:E2:BE:E8:EF:B6", + ], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + ["-f", "ALL", "device", "show", "wlan0"], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + ["-f", "COMMON", "device", "show", "wlan0"], + replace_stdout=replace_uuids, + ) + self.call_nmcli_l( + mode + + [ + "-f", + "GENERAL,CAPABILITIES,WIFI-PROPERTIES,AP,WIRED-PROPERTIES,WIMAX-PROPERTIES,NSP,IP4,DHCP4,IP6,DHCP6,BOND,TEAM,BRIDGE,VLAN,BLUETOOTH,CONNECTIONS", + "device", + "show", + "wlan0", + ], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + ["dev", "lldp", "list", "ifname", "eth0"], + replace_stdout=replace_uuids, + ) + + self.call_nmcli_l( + mode + + [ + "-f", + "connection.id,connection.uuid,connection.type,connection.interface-name,802-3-ethernet.mac-address,vpn.user-name", + "connection", + "show", + ] + + uuids, + replace_stdout=replace_uuids, + replace_cmd=replace_uuids, + ) ############################################################################### + def main(): global dbus_session_inited - if len(sys.argv) >= 2 and sys.argv[1] == '--started-with-dbus-session': + if len(sys.argv) >= 2 and sys.argv[1] == "--started-with-dbus-session": dbus_session_inited = True del sys.argv[1] @@ -1356,37 +1663,64 @@ def main(): # a new dbus-session. try: try: - os.execlp('dbus-run-session', 'dbus-run-session', '--', sys.executable, __file__, '--started-with-dbus-session', *sys.argv[1:]) + os.execlp( + "dbus-run-session", + "dbus-run-session", + "--", + sys.executable, + __file__, + "--started-with-dbus-session", + *sys.argv[1:] + ) except OSError as e: if e.errno != errno.ENOENT: raise # we have no dbus-run-session in path? Fall-through # to skip tests gracefully else: - raise Exception('unknown error during exec') + raise Exception("unknown error during exec") except Exception as e: - assert False, ("Failure to re-exec dbus-run-session: %s" % (str(e))) + assert False, "Failure to re-exec dbus-run-session: %s" % (str(e)) if not dbus_session_inited: # we still don't have a D-Bus session. Probably dbus-run-session is not available. # retry with dbus-launch - if os.system('type dbus-launch 1>/dev/null') == 0: + if os.system("type dbus-launch 1>/dev/null") == 0: try: - os.execlp('bash', 'bash', '-e', '-c', - 'eval `dbus-launch --sh-syntax`;\n' + \ - 'trap "kill $DBUS_SESSION_BUS_PID" EXIT;\n' + \ - '\n' + \ - ' '.join([Util.quote(a) for a in [sys.executable, __file__, '--started-with-dbus-session'] + sys.argv[1:]]) + ' \n' + \ - '') + os.execlp( + "bash", + "bash", + "-e", + "-c", + "eval `dbus-launch --sh-syntax`;\n" + + 'trap "kill $DBUS_SESSION_BUS_PID" EXIT;\n' + + "\n" + + " ".join( + [ + Util.quote(a) + for a in [ + sys.executable, + __file__, + "--started-with-dbus-session", + ] + + sys.argv[1:] + ] + ) + + " \n" + + "", + ) except Exception as e: m = str(e) else: - m = 'unknown error' - assert False, ('Failure to re-exec to start script with dbus-launch: %s' % (m)) + m = "unknown error" + assert False, "Failure to re-exec to start script with dbus-launch: %s" % ( + m + ) - r = unittest.main(exit = False) + r = unittest.main(exit=False) sys.exit(not r.result.wasSuccessful()) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/examples/python/dbus/add-connection-compat.py b/examples/python/dbus/add-connection-compat.py index 6c389f1b37..6acec734bc 100755 --- a/examples/python/dbus/add-connection-compat.py +++ b/examples/python/dbus/add-connection-compat.py @@ -20,34 +20,40 @@ import socket, struct, dbus, uuid def ip_to_int(ip_string): return struct.unpack("=I", socket.inet_aton(ip_string))[0] + def int_to_ip(ip_int): return socket.inet_ntoa(struct.pack("=I", ip_int)) -s_wired = dbus.Dictionary({'duplex': 'full'}) -s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': 'MyConnectionExample'}) -addr1 = dbus.Array([ip_to_int("10.1.2.3"), dbus.UInt32(8), ip_to_int("10.1.2.1")], signature=dbus.Signature('u')) -s_ip4 = dbus.Dictionary({ - 'addresses': dbus.Array([addr1], signature=dbus.Signature('au')), - 'method': 'manual'}) +s_wired = dbus.Dictionary({"duplex": "full"}) +s_con = dbus.Dictionary( + {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"} +) + +addr1 = dbus.Array( + [ip_to_int("10.1.2.3"), dbus.UInt32(8), ip_to_int("10.1.2.1")], + signature=dbus.Signature("u"), +) +s_ip4 = dbus.Dictionary( + { + "addresses": dbus.Array([addr1], signature=dbus.Signature("au")), + "method": "manual", + } +) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) -con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) +con = dbus.Dictionary( + {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} +) -print("Creating connection:", s_con['id'], "-", s_con['uuid']) +print("Creating connection:", s_con["id"], "-", s_con["uuid"]) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-connection.py b/examples/python/dbus/add-connection.py index fec9343033..ee2deb2633 100755 --- a/examples/python/dbus/add-connection.py +++ b/examples/python/dbus/add-connection.py @@ -17,34 +17,33 @@ import dbus, uuid -s_wired = dbus.Dictionary({'duplex': 'full'}) -s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': 'MyConnectionExample'}) +s_wired = dbus.Dictionary({"duplex": "full"}) +s_con = dbus.Dictionary( + {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"} +) -addr1 = dbus.Dictionary({ - 'address': '10.1.2.3', - 'prefix': dbus.UInt32(8)}) -s_ip4 = dbus.Dictionary({ - 'address-data': dbus.Array([addr1], signature=dbus.Signature('a{sv}')), - 'gateway': '10.1.2.1', - 'method': 'manual'}) +addr1 = dbus.Dictionary({"address": "10.1.2.3", "prefix": dbus.UInt32(8)}) +s_ip4 = dbus.Dictionary( + { + "address-data": dbus.Array([addr1], signature=dbus.Signature("a{sv}")), + "gateway": "10.1.2.1", + "method": "manual", + } +) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) -con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) +con = dbus.Dictionary( + {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} +) -print("Creating connection:", s_con['id'], "-", s_con['uuid']) +print("Creating connection:", s_con["id"], "-", s_con["uuid"]) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-wifi-eap-connection.py b/examples/python/dbus/add-wifi-eap-connection.py index 26111138aa..0386084da1 100755 --- a/examples/python/dbus/add-wifi-eap-connection.py +++ b/examples/python/dbus/add-wifi-eap-connection.py @@ -6,45 +6,57 @@ import dbus, uuid -def path_to_value(path): - return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8")) - -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': str(uuid.uuid4()), - 'id': 'My Wifi'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("homewifi".encode("utf-8")), - 'security': '802-11-wireless-security'}) - -s_wsec = dbus.Dictionary({'key-mgmt': 'wpa-eap'}) -s_8021x = dbus.Dictionary({ - 'eap': ['tls'], - 'identity': 'Bill Smith', - 'client-cert': path_to_value("/some/place/client.pem"), - 'ca-cert': path_to_value("/some/place/ca-cert.pem"), - 'private-key': path_to_value("/some/place/privkey.pem"), - 'private-key-password': "12345testing"}) - -s_ip4 = dbus.Dictionary({'method': 'auto'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - '802-1x': s_8021x, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +def path_to_value(path): + return dbus.ByteArray( + "file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8") + ) + + +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My Wifi"} +) + +s_wifi = dbus.Dictionary( + { + "ssid": dbus.ByteArray("homewifi".encode("utf-8")), + "security": "802-11-wireless-security", + } +) + +s_wsec = dbus.Dictionary({"key-mgmt": "wpa-eap"}) + +s_8021x = dbus.Dictionary( + { + "eap": ["tls"], + "identity": "Bill Smith", + "client-cert": path_to_value("/some/place/client.pem"), + "ca-cert": path_to_value("/some/place/ca-cert.pem"), + "private-key": path_to_value("/some/place/privkey.pem"), + "private-key-password": "12345testing", + } +) + +s_ip4 = dbus.Dictionary({"method": "auto"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "802-1x": s_8021x, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-wifi-psk-connection.py b/examples/python/dbus/add-wifi-psk-connection.py index 8f2294f2fe..3e4f9da56f 100755 --- a/examples/python/dbus/add-wifi-psk-connection.py +++ b/examples/python/dbus/add-wifi-psk-connection.py @@ -6,38 +6,37 @@ import dbus, uuid -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': str(uuid.uuid4()), - 'id': 'My-WPA-PSK'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("best-wifi".encode("utf-8")), - 'mode': 'infrastructure', -}) - -s_wsec = dbus.Dictionary({ - 'key-mgmt': 'wpa-psk', - 'auth-alg': 'open', - 'psk': 'super-secret-password', -}) - -s_ip4 = dbus.Dictionary({'method': 'auto'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My-WPA-PSK"} +) + +s_wifi = dbus.Dictionary( + {"ssid": dbus.ByteArray("best-wifi".encode("utf-8")), "mode": "infrastructure",} +) + +s_wsec = dbus.Dictionary( + {"key-mgmt": "wpa-psk", "auth-alg": "open", "psk": "super-secret-password",} +) + +s_ip4 = dbus.Dictionary({"method": "auto"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/checkpoint.py b/examples/python/dbus/checkpoint.py index 1ea1b1a7fc..54b450daf3 100755 --- a/examples/python/dbus/checkpoint.py +++ b/examples/python/dbus/checkpoint.py @@ -12,14 +12,18 @@ import dbus, sys # Get a proxy for the base NetworkManager object bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") allDevs = manager.GetDevices() + def Usage(): print "Usage: %s <ROLLBACK-INTERVAL> [INTERFACE]..." % sys.argv[0] sys.exit(1) + def GetDevicePath(ifname): for dev in allDevs: dev_proxy = bus.get_object("org.freedesktop.NetworkManager", dev) @@ -29,6 +33,7 @@ def GetDevicePath(ifname): return dev return + if len(sys.argv) < 2: Usage() @@ -46,12 +51,11 @@ for arg in sys.argv[2:]: else: devList.append(path) -checkpoint = manager.CheckpointCreate(devList, - interval, - 1); # DESTROY_ALL +checkpoint = manager.CheckpointCreate(devList, interval, 1) +# DESTROY_ALL -choice = raw_input('Do you want to rollback [y/n]? ').lower() -if choice == 'y': +choice = raw_input("Do you want to rollback [y/n]? ").lower() +if choice == "y": print "Rollback checkpoint" results = manager.CheckpointRollback(checkpoint) for d in results: diff --git a/examples/python/dbus/create-bond.py b/examples/python/dbus/create-bond.py index 1ce988c34b..458c9c0618 100755 --- a/examples/python/dbus/create-bond.py +++ b/examples/python/dbus/create-bond.py @@ -17,51 +17,59 @@ from gi.repository import GObject DBusGMainLoop(set_as_default=True) + def add_connection(con): bus = dbus.SystemBus() - proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") return settings.AddConnection(con) + def create_bond(bond_name): - bond_opts = dbus.Dictionary({'mode': '4'}) - s_bond = dbus.Dictionary({'options': bond_opts}) - s_con = dbus.Dictionary({ - 'type': 'bond', - 'uuid': str(uuid.uuid4()), - 'id': bond_name, - 'interface-name': bond_name, - 'autoconnect': False, - 'autoconnect-slaves': 1}) - s_ip4 = dbus.Dictionary({'method': 'auto'}) - s_ip6 = dbus.Dictionary({'method': 'ignore'}) - - con = dbus.Dictionary({ - 'bond': s_bond, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) + bond_opts = dbus.Dictionary({"mode": "4"}) + s_bond = dbus.Dictionary({"options": bond_opts}) + s_con = dbus.Dictionary( + { + "type": "bond", + "uuid": str(uuid.uuid4()), + "id": bond_name, + "interface-name": bond_name, + "autoconnect": False, + "autoconnect-slaves": 1, + } + ) + s_ip4 = dbus.Dictionary({"method": "auto"}) + s_ip6 = dbus.Dictionary({"method": "ignore"}) + + con = dbus.Dictionary( + {"bond": s_bond, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} + ) print("Creating bond connection: %s" % bond_name) return add_connection(con) + def create_slave(device, master): - slave_name = 'bond-' + master + '-slave-' + device - s_wired = dbus.Dictionary({'duplex': 'full'}) - s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': slave_name, - 'interface-name': device, - 'autoconnect': False, - 'master': master, - 'slave-type': 'bond'}) - - con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con}) + slave_name = "bond-" + master + "-slave-" + device + s_wired = dbus.Dictionary({"duplex": "full"}) + s_con = dbus.Dictionary( + { + "type": "802-3-ethernet", + "uuid": str(uuid.uuid4()), + "id": slave_name, + "interface-name": device, + "autoconnect": False, + "master": master, + "slave-type": "bond", + } + ) + + con = dbus.Dictionary({"802-3-ethernet": s_wired, "connection": s_con}) print("Creating slave connection: %s" % slave_name) add_connection(con) + def usage(): print("Usage: %s <bond_name> <ifname1> ..." % sys.argv[0]) sys.exit(0) @@ -78,22 +86,27 @@ for ifname in sys.argv[2:]: # Activate the bond bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") ac = manager.ActivateConnection(bond_path, "/", "/") print("Activating bond: %s (%s)" % (bond_name, ac)) # Monitor the active bond connection loop = GObject.MainLoop() + + def properties_changed(props): - if 'State' in props: - if props['State'] == 2: + if "State" in props: + if props["State"] == 2: print("Successfully connected") loop.quit() - if props['State'] == 3 or props['State'] == 4: + if props["State"] == 3 or props["State"] == 4: print("Bond activation failed") loop.quit() + obj = bus.get_object("org.freedesktop.NetworkManager", ac) iface = dbus.Interface(obj, "org.freedesktop.NetworkManager.Connection.Active") iface.connect_to_signal("PropertiesChanged", properties_changed) diff --git a/examples/python/dbus/disconnect-device.py b/examples/python/dbus/disconnect-device.py index 2387daf672..1b257025c5 100755 --- a/examples/python/dbus/disconnect-device.py +++ b/examples/python/dbus/disconnect-device.py @@ -16,7 +16,9 @@ if len(sys.argv) != 2: bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") dpath = None @@ -45,4 +47,3 @@ if state <= 3: # Tell NM to disconnect it dev_iface.Disconnect() - diff --git a/examples/python/dbus/get-active-connection-uuids.py b/examples/python/dbus/get-active-connection-uuids.py index dd168c0aab..e138ce60a3 100755 --- a/examples/python/dbus/get-active-connection-uuids.py +++ b/examples/python/dbus/get-active-connection-uuids.py @@ -13,11 +13,15 @@ import dbus bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -m_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +m_proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager") mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties") -s_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +s_proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings") # Find the device the user wants to disconnect @@ -31,12 +35,18 @@ for a in active: uuid = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Uuid") # Grab the connection object path so we can get all the connection's settings - connection_path = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") + connection_path = a_props.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) c_proxy = bus.get_object("org.freedesktop.NetworkManager", connection_path) - connection = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + connection = dbus.Interface( + c_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) settings = connection.GetSettings() - print("%s (%s) - %s" % (settings['connection']['id'], uuid, settings['connection']['type'])) + print( + "%s (%s) - %s" + % (settings["connection"]["id"], uuid, settings["connection"]["type"]) + ) if len(active) == 0: print("No active connections") - diff --git a/examples/python/dbus/is-wwan-default.py b/examples/python/dbus/is-wwan-default.py index d6e2b12e03..38dc1735c6 100755 --- a/examples/python/dbus/is-wwan-default.py +++ b/examples/python/dbus/is-wwan-default.py @@ -30,8 +30,9 @@ proxy = bus.get_object(NM_SERVICE_NAME, "/org/freedesktop/NetworkManager") manager = dbus.Interface(proxy, NM_MANAGER_IFACE) props = dbus.Interface(proxy, DBUS_PROPS_IFACE) + def found_connection_type(ctype): - if ctype == '': + if ctype == "": print("No active connection") elif ctype in ["gsm", "cdma", "bluetooth"]: print("WWAN is default") @@ -39,6 +40,7 @@ def found_connection_type(ctype): print("WWAN is not default") sys.exit(0) + # Shortcut #1, for NM 1.0 try: ctype = props.Get(NM_MANAGER_IFACE, "PrimaryConnectionType") @@ -50,7 +52,7 @@ except KeyError: try: primary = props.Get(NM_MANAGER_IFACE, "PrimaryConnection") if not primary: - found_connection_type('') + found_connection_type("") primary_proxy = bus.get_object(NM_SERVICE_NAME, primary) primary_props = dbus.Interface(primary_proxy, DBUS_PROPS_IFACE) ctype = primary_props.Get(NM_ACTIVE_CONNECTION_INTERFACE, "Type") @@ -83,4 +85,3 @@ if default_is_wwan: print("WWAN is default") else: print("WWAN is not default") - diff --git a/examples/python/dbus/list-connections.py b/examples/python/dbus/list-connections.py index 43a9c4e04f..2e096b632c 100755 --- a/examples/python/dbus/list-connections.py +++ b/examples/python/dbus/list-connections.py @@ -12,6 +12,7 @@ import dbus bus = dbus.SystemBus() + def merge_secrets(proxy, config, setting_name): try: # returns a dict of dicts mapping name::setting, where setting is a dict @@ -25,6 +26,7 @@ def merge_secrets(proxy, config, setting_name): except Exception as e: pass + def dict_to_string(d, indent): # Try to trivially translate a dictionary's elements into nice string # formatting. @@ -48,6 +50,7 @@ def dict_to_string(d, indent): dstr += "%s%s: %s\n" % (indent, key, str_val) return dstr + def connection_to_string(config): # dump a connection configuration to a the console for setting_name in config: @@ -66,29 +69,31 @@ def print_connections(): # List each connection's name, UUID, and type for path in connection_paths: con_proxy = bus.get_object(service_name, path) - settings_connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings_connection = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) config = settings_connection.GetSettings() # Now get secrets too; we grab the secrets for each type of connection # (since there isn't a "get all secrets" call because most of the time # you only need 'wifi' secrets or '802.1x' secrets, not everything) and # merge that into the configuration data - merge_secrets(settings_connection, config, '802-11-wireless') - merge_secrets(settings_connection, config, '802-11-wireless-security') - merge_secrets(settings_connection, config, '802-1x') - merge_secrets(settings_connection, config, 'gsm') - merge_secrets(settings_connection, config, 'cdma') - merge_secrets(settings_connection, config, 'ppp') + merge_secrets(settings_connection, config, "802-11-wireless") + merge_secrets(settings_connection, config, "802-11-wireless-security") + merge_secrets(settings_connection, config, "802-1x") + merge_secrets(settings_connection, config, "gsm") + merge_secrets(settings_connection, config, "cdma") + merge_secrets(settings_connection, config, "ppp") # Get the details of the 'connection' setting - s_con = config['connection'] - print(" name: %s" % s_con['id']) - print(" uuid: %s" % s_con['uuid']) - print(" type: %s" % s_con['type']) + s_con = config["connection"] + print(" name: %s" % s_con["id"]) + print(" uuid: %s" % s_con["uuid"]) + print(" type: %s" % s_con["type"]) print(" ------------------------------------------") connection_to_string(config) print("") -print_connections() +print_connections() diff --git a/examples/python/dbus/list-devices.py b/examples/python/dbus/list-devices.py index aebc902bbe..882841e6a0 100755 --- a/examples/python/dbus/list-devices.py +++ b/examples/python/dbus/list-devices.py @@ -9,44 +9,49 @@ import dbus # This example lists basic information about network interfaces known to NM # For the types see include/NetworkManager.h -devtypes = { 1: "Ethernet", - 2: "Wi-Fi", - 5: "Bluetooth", - 6: "OLPC", - 7: "WiMAX", - 8: "Modem", - 9: "InfiniBand", - 10: "Bond", - 11: "VLAN", - 12: "ADSL", - 13: "Bridge", - 14: "Generic", - 15: "Team", - 16: "TUN", - 17: "IPTunnel", - 18: "MACVLAN", - 19: "VXLAN", - 20: "Veth" - } +devtypes = { + 1: "Ethernet", + 2: "Wi-Fi", + 5: "Bluetooth", + 6: "OLPC", + 7: "WiMAX", + 8: "Modem", + 9: "InfiniBand", + 10: "Bond", + 11: "VLAN", + 12: "ADSL", + 13: "Bridge", + 14: "Generic", + 15: "Team", + 16: "TUN", + 17: "IPTunnel", + 18: "MACVLAN", + 19: "VXLAN", + 20: "Veth", +} -states = { 0: "Unknown", - 10: "Unmanaged", - 20: "Unavailable", - 30: "Disconnected", - 40: "Prepare", - 50: "Config", - 60: "Need Auth", - 70: "IP Config", - 80: "IP Check", - 90: "Secondaries", - 100: "Activated", - 110: "Deactivating", - 120: "Failed" } +states = { + 0: "Unknown", + 10: "Unmanaged", + 20: "Unavailable", + 30: "Disconnected", + 40: "Prepare", + 50: "Config", + 60: "Need Auth", + 70: "IP Config", + 80: "IP Check", + 90: "Secondaries", + 100: "Activated", + 110: "Deactivating", + 120: "Failed", +} bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") # Get all devices known to NM and print their properties @@ -57,18 +62,17 @@ for d in devices: props = prop_iface.GetAll("org.freedesktop.NetworkManager.Device") print("============================") - print("Interface: %s" % props['Interface']) + print("Interface: %s" % props["Interface"]) try: - devtype = devtypes[props['DeviceType']] + devtype = devtypes[props["DeviceType"]] except KeyError: devtype = "Unknown" print("Type: %s" % devtype) - print("Driver: %s" % props['Driver']) + print("Driver: %s" % props["Driver"]) try: - state = states[props['State']] + state = states[props["State"]] except KeyError: state = "Unknown" print("State: %s" % state) - diff --git a/examples/python/dbus/nm-state.py b/examples/python/dbus/nm-state.py index 38d10ae60d..c380bd093c 100755 --- a/examples/python/dbus/nm-state.py +++ b/examples/python/dbus/nm-state.py @@ -7,38 +7,46 @@ import dbus # Device states from include/NetworkManager.h -device_states = { 0: "Unknown", - 10: "Unmanaged", - 20: "Unavailable", - 30: "Disconnected", - 40: "Prepare", - 50: "Config", - 60: "Need Auth", - 70: "IP Config", - 80: "IP Check", - 90: "Secondaries", - 100: "Activated", - 110: "Deactivating", - 120: "Failed" } +device_states = { + 0: "Unknown", + 10: "Unmanaged", + 20: "Unavailable", + 30: "Disconnected", + 40: "Prepare", + 50: "Config", + 60: "Need Auth", + 70: "IP Config", + 80: "IP Check", + 90: "Secondaries", + 100: "Activated", + 110: "Deactivating", + 120: "Failed", +} -connectivity_states = { 0: "Unknown", - 1: "Activating", - 2: "Activated", - 3: "Deactivating", - 4: "Deactivated" } +connectivity_states = { + 0: "Unknown", + 1: "Activating", + 2: "Activated", + 3: "Deactivating", + 4: "Deactivated", +} -nm_state = { 0: "Unknown", - 10: "Asleep", - 20: "Disconnected", - 30: "Disconnecting", - 40: "Connecting", - 50: "Connected-Local", - 60: "Connected-Site", - 70: "Connected-Global" } +nm_state = { + 0: "Unknown", + 10: "Asleep", + 20: "Disconnected", + 30: "Disconnecting", + 40: "Connecting", + 50: "Connected-Local", + 60: "Connected-Site", + 70: "Connected-Global", +} bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") # Get overall NM connection state @@ -55,7 +63,7 @@ for d in devices: name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") # and print them out - if state == 100 : # activated + if state == 100: # activated print("Device %s is activated" % name) else: print("Device %s is not activated (state=%s)" % (name, device_states[state])) @@ -72,10 +80,14 @@ for a in active: # Connections in NM are a collection of settings that describe everything # needed to connect to a specific network. Lets get those details so we # can find the user-readable name of the connection. - con_path = prop_iface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") + con_path = prop_iface.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) service_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - con_iface = dbus.Interface(service_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + con_iface = dbus.Interface( + service_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) con_details = con_iface.GetSettings() - con_name = con_details['connection']['id'] + con_name = con_details["connection"]["id"] print("Connection '%s' is %s" % (con_name, connectivity_states[state].lower())) diff --git a/examples/python/dbus/show-bssids.py b/examples/python/dbus/show-bssids.py index b4217a5546..1e7181fece 100755 --- a/examples/python/dbus/show-bssids.py +++ b/examples/python/dbus/show-bssids.py @@ -14,7 +14,9 @@ import dbus bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") all_aps = [] @@ -35,20 +37,26 @@ for d in devices: # Get device's type; we only want wifi devices iface = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") dtype = prop_iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType") - if dtype == 2: # WiFi + if dtype == 2: # WiFi # Get a proxy for the wifi interface - wifi_iface = dbus.Interface(dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless") + wifi_iface = dbus.Interface( + dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless" + ) wifi_prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties") # Get the associated AP's object path - connected_path = wifi_prop_iface.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint") + connected_path = wifi_prop_iface.Get( + "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint" + ) # Get all APs the card can see aps = wifi_iface.GetAccessPoints() for path in aps: ap_proxy = bus.get_object("org.freedesktop.NetworkManager", path) ap_prop_iface = dbus.Interface(ap_proxy, "org.freedesktop.DBus.Properties") - bssid = ap_prop_iface.Get("org.freedesktop.NetworkManager.AccessPoint", "HwAddress") + bssid = ap_prop_iface.Get( + "org.freedesktop.NetworkManager.AccessPoint", "HwAddress" + ) # Cache the BSSID if not bssid in all_aps: @@ -62,4 +70,3 @@ for d in devices: print("\nFound APs:") for bssid in all_aps: print(bssid) - diff --git a/examples/python/dbus/update-ip4-method.py b/examples/python/dbus/update-ip4-method.py index 2c12c2bb5b..98927903a0 100755 --- a/examples/python/dbus/update-ip4-method.py +++ b/examples/python/dbus/update-ip4-method.py @@ -30,42 +30,49 @@ if method == "static": method = "manual" bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") for c_path in settings.ListConnections(): c_proxy = bus.get_object("org.freedesktop.NetworkManager", c_path) - c_obj = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + c_obj = dbus.Interface( + c_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) c_settings = c_obj.GetSettings() # Look for the requested connection UUID - if c_settings['connection']['uuid'] != sys.argv[1]: + if c_settings["connection"]["uuid"] != sys.argv[1]: continue # add IPv4 setting if it doesn't yet exist - if 'ipv4' not in c_settings: - c_settings['ipv4'] = {} + if "ipv4" not in c_settings: + c_settings["ipv4"] = {} # clear existing address info - if c_settings['ipv4'].has_key('addresses'): - del c_settings['ipv4']['addresses'] - if c_settings['ipv4'].has_key('address-data'): - del c_settings['ipv4']['address-data'] - if c_settings['ipv4'].has_key('gateway'): - del c_settings['ipv4']['gateway'] + if c_settings["ipv4"].has_key("addresses"): + del c_settings["ipv4"]["addresses"] + if c_settings["ipv4"].has_key("address-data"): + del c_settings["ipv4"]["address-data"] + if c_settings["ipv4"].has_key("gateway"): + del c_settings["ipv4"]["gateway"] # set the method and change properties - c_settings['ipv4']['method'] = method + c_settings["ipv4"]["method"] = method if method == "manual": # Add the static IP address, prefix, and (optional) gateway - addr = dbus.Dictionary({'address': sys.argv[3], 'prefix': dbus.UInt32(int(sys.argv[4]))}) - c_settings['ipv4']['address-data'] = dbus.Array([addr], signature=dbus.Signature('a{sv}')) + addr = dbus.Dictionary( + {"address": sys.argv[3], "prefix": dbus.UInt32(int(sys.argv[4]))} + ) + c_settings["ipv4"]["address-data"] = dbus.Array( + [addr], signature=dbus.Signature("a{sv}") + ) if len(sys.argv) == 6: - c_settings['ipv4']['gateway'] = sys.argv[5] + c_settings["ipv4"]["gateway"] = sys.argv[5] # Save all the updated settings back to NetworkManager c_obj.Update(c_settings) break sys.exit(0) - diff --git a/examples/python/dbus/update-secrets.py b/examples/python/dbus/update-secrets.py index a0b53b7c76..d5c20b2d4b 100755 --- a/examples/python/dbus/update-secrets.py +++ b/examples/python/dbus/update-secrets.py @@ -18,6 +18,7 @@ import sys bus = dbus.SystemBus() + def change_secrets_in_one_setting(proxy, config, setting_name): # Add new secret values to the connection config try: @@ -29,50 +30,62 @@ def change_secrets_in_one_setting(proxy, config, setting_name): # Ask user for new secrets and put them into our connection config for setting in secrets: for key in secrets[setting]: - new_secret = raw_input ("Enter new secret for '%s' in '%s': " % (key, setting)) + new_secret = raw_input( + "Enter new secret for '%s' in '%s': " % (key, setting) + ) config[setting_name][key] = new_secret except Exception as e: - #code = str(e).split(':')[0] - #print("Exception:" + str(e)) + # code = str(e).split(':')[0] + # print("Exception:" + str(e)) pass + def change_secrets(con_path, config): # Get existing secrets; we grab the secrets for each type of connection # (since there isn't a "get all secrets" call because most of the time # you only need 'wifi' secrets or '802.1x' secrets, not everything) and # set new values into the connection settings (config) con_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - connection_secrets = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") - change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless') - change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless-security') - change_secrets_in_one_setting(connection_secrets, config, '802-1x') - change_secrets_in_one_setting(connection_secrets, config, 'gsm') - change_secrets_in_one_setting(connection_secrets, config, 'cdma') - change_secrets_in_one_setting(connection_secrets, config, 'ppp') + connection_secrets = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) + change_secrets_in_one_setting(connection_secrets, config, "802-11-wireless") + change_secrets_in_one_setting( + connection_secrets, config, "802-11-wireless-security" + ) + change_secrets_in_one_setting(connection_secrets, config, "802-1x") + change_secrets_in_one_setting(connection_secrets, config, "gsm") + change_secrets_in_one_setting(connection_secrets, config, "cdma") + change_secrets_in_one_setting(connection_secrets, config, "ppp") + def find_connection(name): # Ask the settings service for the list of connections it provides global con_path - proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") connection_paths = settings.ListConnections() # Get the settings and look for connection's name for path in connection_paths: con_proxy = bus.get_object("org.freedesktop.NetworkManager", path) - connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + connection = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) try: config = connection.GetSettings() except Exception as e: pass # Find connection by the id - s_con = config['connection'] - if name == s_con['id']: + s_con = config["connection"] + if name == s_con["id"]: con_path = path return config # Find connection by the uuid - if name == s_con['uuid']: + if name == s_con["uuid"]: con_path = path return config @@ -96,8 +109,9 @@ if con: # Change the connection with Update() proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings = dbus.Interface( + proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) settings.Update(con) else: sys.exit("No connection '%s' found" % sys.argv[1]) - diff --git a/examples/python/dbus/vpn.py b/examples/python/dbus/vpn.py index 14fa2f1d2e..ed38137280 100755 --- a/examples/python/dbus/vpn.py +++ b/examples/python/dbus/vpn.py @@ -8,11 +8,11 @@ # Run this script without any arguments to list the available connection uuids. # The uuid of the connection to activate -CONNECTION_UUID="ac6dc9b2-85ef-4311-83d8-add5d7db3f59" +CONNECTION_UUID = "ac6dc9b2-85ef-4311-83d8-add5d7db3f59" # UID to use. Note that NM only allows the owner of the connection to activate it. -#UID=1000 -UID=0 +# UID=1000 +UID = 0 import sys import os @@ -22,20 +22,27 @@ import gobject DBusGMainLoop(set_as_default=True) + def get_connections(): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings" + ) return iface.ListConnections() def get_connection_by_uuid(uuid): bus = dbus.SystemBus() for c in get_connections(): - proxy = bus.get_object('org.freedesktop.NetworkManager', c) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", c) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - if settings['connection']['uuid'] == uuid: + if settings["connection"]["uuid"] == uuid: return c return None @@ -44,29 +51,39 @@ def get_connection_by_uuid(uuid): def list_uuids(): bus = dbus.SystemBus() for c in get_connections(): - proxy = bus.get_object('org.freedesktop.NetworkManager', c) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", c) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - conn = settings['connection'] - print("%s - %s (%s)" % (conn['uuid'], conn['id'], conn['type'])) + conn = settings["connection"] + print("%s - %s (%s)" % (conn["uuid"], conn["id"], conn["type"])) def get_active_connection_path(uuid): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + active_connections = iface.Get( + "org.freedesktop.NetworkManager", "ActiveConnections" + ) for a in active_connections: - proxy = bus.get_object('org.freedesktop.NetworkManager', a) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') - - proxy = bus.get_object('org.freedesktop.NetworkManager', path) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", a) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + path = iface.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) + + proxy = bus.get_object("org.freedesktop.NetworkManager", path) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - if settings['connection']['uuid'] == uuid: + if settings["connection"]["uuid"] == uuid: return a return None @@ -74,19 +91,21 @@ def get_active_connection_path(uuid): def get_wifi_device_path(): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager") devices = iface.GetDevices() for d in devices: - proxy = bus.get_object('org.freedesktop.NetworkManager', d) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - devtype = iface.Get('org.freedesktop.NetworkManager.Device', 'DeviceType') + proxy = bus.get_object("org.freedesktop.NetworkManager", d) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + devtype = iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType") if devtype == 2: return d return None -def activate_connection(connection_path, device_path): +def activate_connection(connection_path, device_path): def reply_handler(opath): print("Success: device activating") sys.exit(0) @@ -96,14 +115,18 @@ def activate_connection(connection_path, device_path): sys.exit(1) bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') - iface.ActivateConnection('org.freedesktop.NetworkManager', - connection_path, - device_path, - "/", - reply_handler=reply_handler, - error_handler=error_handler) + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager") + iface.ActivateConnection( + "org.freedesktop.NetworkManager", + connection_path, + device_path, + "/", + reply_handler=reply_handler, + error_handler=error_handler, + ) # Change the UID first if required @@ -135,4 +158,3 @@ print("Activating connection...") activate_connection(connection_path, device_path) loop = gobject.MainLoop() loop.run() - diff --git a/examples/python/dbus/wifi-active-ap.py b/examples/python/dbus/wifi-active-ap.py index b81c06a933..33fae0b219 100755 --- a/examples/python/dbus/wifi-active-ap.py +++ b/examples/python/dbus/wifi-active-ap.py @@ -31,7 +31,9 @@ devpath = nm.GetDeviceByIpIface(iface) # Get a proxy to the wifi device and get the active access point's object path proxy = bus.get_object(service_name, devpath) props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") -active_ap_path = props.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint") +active_ap_path = props.Get( + "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint" +) if active_ap_path == "/": print("%s is not currently associated" % sys.argv[1]) sys.exit(0) @@ -50,4 +52,3 @@ for c in raw_ssid: print("%s is associated to '%s' (%s)" % (sys.argv[1], ssid, bssid)) sys.exit(0) - diff --git a/examples/python/dbus/wifi-hotspot.py b/examples/python/dbus/wifi-hotspot.py index d4f17d074b..a3c573a643 100755 --- a/examples/python/dbus/wifi-hotspot.py +++ b/examples/python/dbus/wifi-hotspot.py @@ -13,38 +13,42 @@ import dbus, sys, time -our_uuid = '2b0d0f1d-b79d-43af-bde1-71744625642e' - -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': our_uuid, - 'id': 'Test Hotspot'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("My Hotspot".encode("utf-8")), - 'mode': "ap", - 'band': "bg", - 'channel': dbus.UInt32(1)}) - -s_wsec = dbus.Dictionary({ - 'key-mgmt': 'wpa-psk', - 'psk': 'great password'}) - -s_ip4 = dbus.Dictionary({'method': 'shared'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +our_uuid = "2b0d0f1d-b79d-43af-bde1-71744625642e" + +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": our_uuid, "id": "Test Hotspot"} +) + +s_wifi = dbus.Dictionary( + { + "ssid": dbus.ByteArray("My Hotspot".encode("utf-8")), + "mode": "ap", + "band": "bg", + "channel": dbus.UInt32(1), + } +) + +s_wsec = dbus.Dictionary({"key-mgmt": "wpa-psk", "psk": "great password"}) + +s_ip4 = dbus.Dictionary({"method": "shared"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) + def usage(): print("Usage: %s <ifname> [up|down]" % sys.argv[0]) sys.exit(0) + bus = dbus.SystemBus() service_name = "org.freedesktop.NetworkManager" proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") @@ -62,9 +66,11 @@ devpath = nm.GetDeviceByIpIface(iface) connection_path = None for path in settings.ListConnections(): proxy = bus.get_object(service_name, path) - settings_connection = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings_connection = dbus.Interface( + proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) config = settings_connection.GetSettings() - if config['connection']['uuid'] == our_uuid: + if config["connection"]["uuid"] == our_uuid: connection_path = path break @@ -84,7 +90,9 @@ if operation == "up": # Wait for the hotspot to start up start = time.time() while time.time() < start + 10: - state = active_props.Get("org.freedesktop.NetworkManager.Connection.Active", "State") + state = active_props.Get( + "org.freedesktop.NetworkManager.Connection.Active", "State" + ) if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED print("Access point started") sys.exit(0) @@ -96,4 +104,3 @@ else: usage() sys.exit(0) - diff --git a/examples/python/gi/add_connection.py b/examples/python/gi/add_connection.py index 9cf9e348f1..ac537eada4 100755 --- a/examples/python/gi/add_connection.py +++ b/examples/python/gi/add_connection.py @@ -14,15 +14,18 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys, uuid main_loop = None + def print_values(setting, key, value, flags, data): print(" %s.%s: %s" % (setting.get_name(), key, value)) + # create an Ethernet connection and return it def create_profile(name): profile = NM.SimpleConnection.new() @@ -49,6 +52,7 @@ def create_profile(name): return profile + # callback function def added_cb(client, result, data): try: @@ -58,16 +62,17 @@ def added_cb(client, result, data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() + if __name__ == "__main__": # parse arguments persistent = False if len(sys.argv) != 2 and len(sys.argv) != 3: - sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0]) + sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0]) if len(sys.argv) == 3: if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p": persistent = True else: - sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0]) + sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0]) profile_name = sys.argv[1] main_loop = GLib.MainLoop() @@ -82,4 +87,3 @@ if __name__ == "__main__": client.add_connection_async(con, persistent, None, added_cb, None) main_loop.run() - diff --git a/examples/python/gi/checkpoint.py b/examples/python/gi/checkpoint.py index a695a64613..6dfd3d4488 100755 --- a/examples/python/gi/checkpoint.py +++ b/examples/python/gi/checkpoint.py @@ -7,32 +7,52 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM ############################################################################### + def usage(): print("Usage: %s [COMMAND [ARG]...]" % sys.argv[0]) print("") print(" COMMANDS: [show]") - print(" create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]...") + print( + " create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]..." + ) print(" destroy PATH|NUMBER") print(" rollback PATH|NUMBER") print(" adjust-rollback-timeout PATH|NUMBER TIMEOUT") print("") sys.exit(1) -def show(c, ts = None): + +def show(c, ts=None): cr = c.get_created() rt = c.get_rollback_timeout() print("%s:" % c.get_path()) - print(" created: %u%s" % (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0)))) + print( + " created: %u%s" + % (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0))) + ) if rt == 0: print(" timeout: infinity") else: - print(" timeout: %u seconds%s" % (rt, "" if ts is None else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)))) - print(" devices: %s" % (' '.join(sorted(map(lambda x: x.get_iface(), c.get_devices()))))) + print( + " timeout: %u seconds%s" + % ( + rt, + "" + if ts is None + else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)), + ) + ) + print( + " devices: %s" + % (" ".join(sorted(map(lambda x: x.get_iface(), c.get_devices())))) + ) + def find_checkpoint(client, path): for c in client.get_checkpoints(): @@ -40,6 +60,7 @@ def find_checkpoint(client, path): return c return None + def validate_path(path, client): try: num = int(path) @@ -47,8 +68,8 @@ def validate_path(path, client): except Exception as e: pass - if not path or path[0] != '/': - sys.exit('Invalid checkpoint path \"%s\"' % (path)) + if not path or path[0] != "/": + sys.exit('Invalid checkpoint path "%s"' % (path)) if client is not None: checkpoint = find_checkpoint(client, path) @@ -57,6 +78,7 @@ def validate_path(path, client): return path + def do_create(client): flags = NM.CheckpointCreateFlags.NONE if len(sys.argv) < 3: @@ -65,13 +87,13 @@ def do_create(client): timeout = int(sys.argv[2]) devices = [] for arg in sys.argv[3:]: - if arg == '--destroy-all': + if arg == "--destroy-all": flags |= NM.CheckpointCreateFlags.DESTROY_ALL - elif arg == '--delete-new-connections': + elif arg == "--delete-new-connections": flags |= NM.CheckpointCreateFlags.DELETE_NEW_CONNECTIONS - elif arg == '--disconnect-new-devices': + elif arg == "--disconnect-new-devices": flags |= NM.CheckpointCreateFlags.DISCONNECT_NEW_DEVICES - elif arg == '--allow-overlapping': + elif arg == "--allow-overlapping": flags |= NM.CheckpointCreateFlags.ALLOW_OVERLAPPING else: d = client.get_device_by_iface(arg) @@ -89,6 +111,7 @@ def do_create(client): client.checkpoint_create(devices, timeout, flags, None, create_cb, None) + def do_destroy(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -105,6 +128,7 @@ def do_destroy(client): client.checkpoint_destroy(path, None, destroy_cb, None) + def do_rollback(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -127,6 +151,7 @@ def do_rollback(client): client.checkpoint_rollback(path, None, rollback_cb, None) + def do_adjust_rollback_timeout(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -147,27 +172,31 @@ def do_adjust_rollback_timeout(client): sys.stderr.write("Failed: %s\n" % e.message) main_loop.quit() - client.checkpoint_adjust_rollback_timeout(path, add_timeout, None, adjust_rollback_timeout_cb, None) + client.checkpoint_adjust_rollback_timeout( + path, add_timeout, None, adjust_rollback_timeout_cb, None + ) + def do_show(client): ts = NM.utils_get_timestamp_msec() for c in client.get_checkpoints(): show(c, ts) -if __name__ == '__main__': + +if __name__ == "__main__": nm_client = NM.Client.new(None) main_loop = GLib.MainLoop() - if len(sys.argv) < 2 or sys.argv[1] == 'show': + if len(sys.argv) < 2 or sys.argv[1] == "show": do_show(nm_client) sys.exit(0) - elif sys.argv[1] == 'create': + elif sys.argv[1] == "create": do_create(nm_client) - elif sys.argv[1] == 'destroy': + elif sys.argv[1] == "destroy": do_destroy(nm_client) - elif sys.argv[1] == 'rollback': + elif sys.argv[1] == "rollback": do_rollback(nm_client) - elif sys.argv[1] == 'adjust-rollback-timeout': + elif sys.argv[1] == "adjust-rollback-timeout": do_adjust_rollback_timeout(nm_client) else: usage() diff --git a/examples/python/gi/deactivate-all.py b/examples/python/gi/deactivate-all.py index 7e528d0b3e..cc181dd97c 100755 --- a/examples/python/gi/deactivate-all.py +++ b/examples/python/gi/deactivate-all.py @@ -16,24 +16,25 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # supported connection types connection_types = { - NM.SETTING_VPN_SETTING_NAME, - NM.SETTING_WIRELESS_SETTING_NAME, - NM.SETTING_WIRED_SETTING_NAME, - NM.SETTING_BOND_SETTING_NAME, - NM.SETTING_BRIDGE_SETTING_NAME, - NM.SETTING_TEAM_SETTING_NAME, - NM.SETTING_INFINIBAND_SETTING_NAME, - NM.SETTING_PPPOE_SETTING_NAME, - NM.SETTING_ADSL_SETTING_NAME, - NM.SETTING_BLUETOOTH_SETTING_NAME, - NM.SETTING_WIMAX_SETTING_NAME, - NM.SETTING_OLPC_MESH_SETTING_NAME, - NM.SETTING_GENERIC_SETTING_NAME, + NM.SETTING_VPN_SETTING_NAME, + NM.SETTING_WIRELESS_SETTING_NAME, + NM.SETTING_WIRED_SETTING_NAME, + NM.SETTING_BOND_SETTING_NAME, + NM.SETTING_BRIDGE_SETTING_NAME, + NM.SETTING_TEAM_SETTING_NAME, + NM.SETTING_INFINIBAND_SETTING_NAME, + NM.SETTING_PPPOE_SETTING_NAME, + NM.SETTING_ADSL_SETTING_NAME, + NM.SETTING_BLUETOOTH_SETTING_NAME, + NM.SETTING_WIMAX_SETTING_NAME, + NM.SETTING_OLPC_MESH_SETTING_NAME, + NM.SETTING_GENERIC_SETTING_NAME, } @@ -45,9 +46,14 @@ if __name__ == "__main__": if len(sys.argv) == 2: ctype = sys.argv[1] if ctype not in connection_types: - sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types)) + sys.exit( + "Usage: %s [<type>]\nAllowed types: %s" + % (sys.argv[0], allowed_types) + ) else: - sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types)) + sys.exit( + "Usage: %s [<type>]\nAllowed types: %s" % (sys.argv[0], allowed_types) + ) # create Client object client = NM.Client.new(None) @@ -63,5 +69,4 @@ if __name__ == "__main__": client.deactivate_connection(ac, None) sys.stdout.write("\033[32m -> succeeded\033[0m\n") except Exception as e: - sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message) - + sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message) diff --git a/examples/python/gi/device-state-ip4config.py b/examples/python/gi/device-state-ip4config.py index 18848d07fc..038b8a725f 100755 --- a/examples/python/gi/device-state-ip4config.py +++ b/examples/python/gi/device-state-ip4config.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # @@ -18,6 +19,7 @@ from gi.repository import GLib, NM main_loop = None + def do_notify(self, property): print("notify: %s" % property) ip4cfg = self.get_ip4_config() @@ -25,26 +27,26 @@ def do_notify(self, property): print("ip4-config: %s" % ip4cfg.get_path()) main_loop.quit() + def state_changed(obj, arg1, arg2, arg3): print("State changed: New: %d, Old: %d, Reason: %d" % (arg1, arg2, arg3)) # Device is connected if arg1 == 100: - obj.connect('notify::ip4-config', do_notify) + obj.connect("notify::ip4-config", do_notify) if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name)) print("---------------------------------------") - dev.connect('state-changed', state_changed) + dev.connect("state-changed", state_changed) main_loop = GLib.MainLoop() main_loop.run() - diff --git a/examples/python/gi/dns.py b/examples/python/gi/dns.py index da2a6a6c43..c4c5190152 100755 --- a/examples/python/gi/dns.py +++ b/examples/python/gi/dns.py @@ -5,24 +5,26 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # This example shows how to monitor the DNS configuration main_loop = None + def handle_config(config): print " ---- new configuration ----" for entry in config: - print " * servers: %s" % ', '.join(map(str, entry.get_nameservers())) + print " * servers: %s" % ", ".join(map(str, entry.get_nameservers())) domains = entry.get_domains() if domains and domains[0]: - print " domains: %s" % ', '.join(map(str, domains)) + print " domains: %s" % ", ".join(map(str, domains)) if entry.get_interface(): - print " interface: %s" % entry.get_interface() + print " interface: %s" % entry.get_interface() print " priority: %d" % entry.get_priority() @@ -31,9 +33,11 @@ def handle_config(config): print "" + def dns_config_changed(self, property): handle_config(self.get_dns_configuration()) + main_loop = None if __name__ == "__main__": diff --git a/examples/python/gi/firewall-zone.py b/examples/python/gi/firewall-zone.py index 6cbd8c2549..3de06f5255 100755 --- a/examples/python/gi/firewall-zone.py +++ b/examples/python/gi/firewall-zone.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # @@ -26,13 +27,15 @@ from gi.repository import GLib, NM main_loop = None + def connection_saved(connection, error, data): - print ("Connection '%s' saved.") % (connection.get_id()) + print("Connection '%s' saved.") % (connection.get_id()) main_loop.quit() + if __name__ == "__main__": if len(sys.argv) != 2 and len(sys.argv) != 3: - sys.exit('Usage: %s <connection name or UUID> [new zone]' % sys.argv[0]) + sys.exit("Usage: %s <connection name or UUID> [new zone]" % sys.argv[0]) main_loop = GLib.MainLoop() client = NM.Client.new(None) diff --git a/examples/python/gi/get-active-connections.py b/examples/python/gi/get-active-connections.py index 6da8b61890..c2f261abe0 100755 --- a/examples/python/gi/get-active-connections.py +++ b/examples/python/gi/get-active-connections.py @@ -7,7 +7,8 @@ # This example lists currently active connections import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -16,6 +17,4 @@ if __name__ == "__main__": for ac in acons: print("%s (%s) - %s" % (ac.get_id(), ac.get_uuid(), ac.get_connection_type())) if len(acons) == 0: - print("No active connections") - - + print("No active connections") diff --git a/examples/python/gi/get-devices.py b/examples/python/gi/get-devices.py index 88bcc8945b..057db5ace0 100755 --- a/examples/python/gi/get-devices.py +++ b/examples/python/gi/get-devices.py @@ -7,7 +7,8 @@ # This example lists all devices, both real and placeholder ones import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -18,11 +19,18 @@ if __name__ == "__main__": print "------------" for d in devices: if d.is_real(): - print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state()) + print "%s (%s): %s" % ( + d.get_iface(), + d.get_type_description(), + d.get_state(), + ) print "\nUnrealized/placeholder devices" print "------------------------------" for d in devices: if not d.is_real(): - print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state()) - + print "%s (%s): %s" % ( + d.get_iface(), + d.get_type_description(), + d.get_state(), + ) diff --git a/examples/python/gi/get-interface-flags.py b/examples/python/gi/get-interface-flags.py index e1d1721a4f..2b4fa3b4ea 100755 --- a/examples/python/gi/get-interface-flags.py +++ b/examples/python/gi/get-interface-flags.py @@ -5,7 +5,8 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -13,7 +14,10 @@ if __name__ == "__main__": devices = client.get_devices() for d in devices: - print("{:<16} {:<16} {}".format(d.get_iface(), - "(" + d.get_type_description() + ")", - NM.utils_enum_to_str(NM.DeviceInterfaceFlags, - d.get_interface_flags()))) + print( + "{:<16} {:<16} {}".format( + d.get_iface(), + "(" + d.get_type_description() + ")", + NM.utils_enum_to_str(NM.DeviceInterfaceFlags, d.get_interface_flags()), + ) + ) diff --git a/examples/python/gi/get-lldp-neighbors.py b/examples/python/gi/get-lldp-neighbors.py index d1bed32c6b..b84a1c7389 100755 --- a/examples/python/gi/get-lldp-neighbors.py +++ b/examples/python/gi/get-lldp-neighbors.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # This example shows how to get a list of LLDP neighbors for a given interface. @@ -15,24 +16,24 @@ main_loop = None if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) neighbors = dev.get_lldp_neighbors() for neighbor in neighbors: - ret, chassis = neighbor.get_attr_string_value('chassis-id') - ret, port = neighbor.get_attr_string_value('port-id') + ret, chassis = neighbor.get_attr_string_value("chassis-id") + ret, port = neighbor.get_attr_string_value("port-id") print "Neighbor: %s - %s" % (chassis, port) for attr in neighbor.get_attr_names(): attr_type = neighbor.get_attr_type(attr) - if attr_type.equal(GLib.VariantType.new('s')): + if attr_type.equal(GLib.VariantType.new("s")): ret, value = neighbor.get_attr_string_value(attr) print " %-32s: %s" % (attr, value) - elif attr_type.equal(GLib.VariantType.new('u')): + elif attr_type.equal(GLib.VariantType.new("u")): ret, value = neighbor.get_attr_uint_value(attr) print " %-32s: %u" % (attr, value) diff --git a/examples/python/gi/get_ips.py b/examples/python/gi/get_ips.py index 75be2f8c5d..07d6f0cc39 100755 --- a/examples/python/gi/get_ips.py +++ b/examples/python/gi/get_ips.py @@ -6,7 +6,8 @@ import sys, socket import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # @@ -14,11 +15,12 @@ from gi.repository import NM # from NMIP4Config and NMIP6Config (got out of NMDevice) # + def show_addresses(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") @@ -35,8 +37,9 @@ def show_addresses(dev, family): print("%s/%d") % (addr, prefix) + def show_gateway(dev, family): - if (family == socket.AF_INET): + if family == socket.AF_INET: ip_cfg = dev.get_ip4_config() else: ip_cfg = dev.get_ip6_config() @@ -45,16 +48,17 @@ def show_gateway(dev, family): gw = "None" else: gw = ip_cfg.get_gateway() - if gw == '': + if gw == "": gw = "None" print(gw) + def show_routes(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") @@ -75,31 +79,31 @@ def show_routes(dev, family): def show_dns(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") return - print ("Nameservers: %s") % (ip_cfg.get_nameservers()) - print ("Domains: %s") % (ip_cfg.get_domains()) - print ("Searches: %s") % (ip_cfg.get_searches()) - if (family == socket.AF_INET): - print ("WINS: %s") % (ip_cfg.get_wins_servers()) + print("Nameservers: %s") % (ip_cfg.get_nameservers()) + print("Domains: %s") % (ip_cfg.get_domains()) + print("Searches: %s") % (ip_cfg.get_searches()) + if family == socket.AF_INET: + print("WINS: %s") % (ip_cfg.get_wins_servers()) if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name)) print("---------------------------------------") @@ -142,4 +146,3 @@ if __name__ == "__main__": print("------------") show_dns(dev, socket.AF_INET6) print - diff --git a/examples/python/gi/list-connections.py b/examples/python/gi/list-connections.py index 7278fafd9b..ba4f50e2fa 100755 --- a/examples/python/gi/list-connections.py +++ b/examples/python/gi/list-connections.py @@ -5,14 +5,17 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # This example asks settings service for all configured connections. + def print_values(setting, key, value, flags, data): print(" %s.%s: %s" % (setting.get_name(), key, value)) + if __name__ == "__main__": # create Client object client = NM.Client.new(None) @@ -25,4 +28,3 @@ if __name__ == "__main__": print("=== %s : %s ===" % (c.get_id(), c.get_path())) c.for_each_setting_value(print_values, None) print("\n") - diff --git a/examples/python/gi/nm-add-connection2.py b/examples/python/gi/nm-add-connection2.py index c5ec3f3bbe..f487e0bbe4 100755 --- a/examples/python/gi/nm-add-connection2.py +++ b/examples/python/gi/nm-add-connection2.py @@ -7,40 +7,47 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def find_connections(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: yield c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: yield c + def find_connection_first(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id): return f + def con_to_str(con): s_con = con.get_setting_connection() return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) + def usage(): arg0 = sys.argv[0] - arg0_spaced = ' ' * len(arg0) - print('Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\' % (arg0)) - print(' %s [ --to-disk | --in-memory ] \\' % (arg0_spaced)) - print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) - print(' %s [ --id <new-id> ] \\' % (arg0_spaced)) - print(' %s [ --uuid <new-uuid> ] \\' % (arg0_spaced)) + arg0_spaced = " " * len(arg0) + print("Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\" % (arg0)) + print(" %s [ --to-disk | --in-memory ] \\" % (arg0_spaced)) + print(" %s [ --block-autoconnect ] \\" % (arg0_spaced)) + print(" %s [ --id <new-id> ] \\" % (arg0_spaced)) + print(" %s [ --uuid <new-uuid> ] \\" % (arg0_spaced)) return 1 + def die(msg, print_usage=False): print(msg) if print_usage: usage() sys.exit(1) + def main(): main_loop = GLib.MainLoop() @@ -56,56 +63,62 @@ def main(): argv = list(sys.argv[1:]) while argv: - if argv[0] == '--clone': + if argv[0] == "--clone": match_type = None if len(argv) < 2: - die('missing argument for --clone option') - if argv[0] in ['id', 'uuid']: + die("missing argument for --clone option") + if argv[0] in ["id", "uuid"]: match_type = argv[0] if len(argv) < 3: die('missing argument for "--clone %s" option' % (match_type)) argv = argv[1:] if cons: - die('cannot specify --clone argument more than once') + die("cannot specify --clone argument more than once") cons.extend(find_connections(nm_client, match_type, argv[1])) if len(cons) == 0: - die('could not find connection for "--clone %s%s"' % ((match_type or ''), argv[1])) + die( + 'could not find connection for "--clone %s%s"' + % ((match_type or ""), argv[1]) + ) if len(cons) != 1: - die('could not find unique connection for "--clone %s%s"' % ((match_type or ''), argv[1])) + die( + 'could not find unique connection for "--clone %s%s"' + % ((match_type or ""), argv[1]) + ) argv = argv[2:] continue - if argv[0] in ['--block-autoconnect']: + if argv[0] in ["--block-autoconnect"]: arg_block_autoconnect = NM.SettingsAddConnection2Flags.BLOCK_AUTOCONNECT argv = argv[1:] continue - if argv[0] in ['--to-disk', '--in-memory']: - if argv[0] == '--to-disk': + if argv[0] in ["--to-disk", "--in-memory"]: + if argv[0] == "--to-disk": v = NM.SettingsAddConnection2Flags.TO_DISK - elif argv[0] == '--in-memory': + elif argv[0] == "--in-memory": v = NM.SettingsAddConnection2Flags.IN_MEMORY else: - assert(False) + assert False if arg_mode is not None: die('duplicate storage modes ("%s")' % (argv[0])) arg_mode = v argv = argv[1:] continue - if argv[0] in ['--id']: + if argv[0] in ["--id"]: if len(argv) < 2: - die('missing argument for --id option') + die("missing argument for --id option") arg_id = argv[1] argv = argv[2:] continue - if argv[0] in ['--uuid']: + if argv[0] in ["--uuid"]: if len(argv) < 2: - die('missing argument for --uuid option') + die("missing argument for --uuid option") arg_uuid = argv[1] argv = argv[2:] continue die('unknown argument "%s"' % (argv[0])) if len(cons) != 1: - die('missing --clone argument', True) + die("missing --clone argument", True) con = cons[0] @@ -117,31 +130,46 @@ def main(): s_con.set_property(NM.SETTING_CONNECTION_UUID, arg_uuid or NM.utils_uuid_generate()) result = {} + def _add_connection2_cb(cl, async_result, user_data): try: c, r = nm_client.add_connection2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r - result['connection'] = c + result["result"] = r + result["connection"] = c main_loop.quit() - nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - (arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK) - | arg_block_autoconnect, - None, - False, - None, - _add_connection2_cb, - None) + nm_client.add_connection2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + (arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK) + | arg_block_autoconnect, + None, + False, + None, + _add_connection2_cb, + None, + ) main_loop.run() - if 'error' in result: - die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) + if "error" in result: + die( + "update connection %s failed [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["error"]) + ) + + print( + "update connection %s succeeded [%s]: %s, %s" + % ( + con_to_str(con2), + " ".join(sys.argv), + result["connection"].get_path(), + result["result"], + ) + ) - print('update connection %s succeeded [%s]: %s, %s' % (con_to_str(con2), ' '.join(sys.argv), result['connection'].get_path(), result['result'])) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/python/gi/nm-connection-update-stable-id.py b/examples/python/gi/nm-connection-update-stable-id.py index 3629d07230..091a67d618 100755 --- a/examples/python/gi/nm-connection-update-stable-id.py +++ b/examples/python/gi/nm-connection-update-stable-id.py @@ -11,33 +11,37 @@ import sys import re import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def usage(): - print('Usage: %s [[id] <id>]' % (sys.argv[0])) - print(' %s [[uuid] <uuid>]' % (sys.argv[0])) + print("Usage: %s [[id] <id>]" % (sys.argv[0])) + print(" %s [[uuid] <uuid>]" % (sys.argv[0])) return 1 + def find_connection(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: return c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: return c + def main(): if len(sys.argv) < 2 or len(sys.argv) > 3: return usage() if len(sys.argv) == 3: arg_type = sys.argv[1] arg_id = sys.argv[2] - if arg_type not in ['id', 'uuid']: + if arg_type not in ["id", "uuid"]: return usage() else: arg_type = None arg_id = sys.argv[1] - arg_log = '%s"%s"' % ((' with %s ' % (arg_type)) if arg_type else '', arg_id) + arg_log = '%s"%s"' % ((" with %s " % (arg_type)) if arg_type else "", arg_id) main_loop = GLib.MainLoop() @@ -45,57 +49,61 @@ def main(): con = find_connection(nm_client, arg_type, arg_id) if con is None: - print('could not find a connection %s' % (arg_log)) + print("could not find a connection %s" % (arg_log)) return 1 s_con = con.get_setting_connection() if s_con is None: - print('connection %s has no [connection] setting' % (arg_log)) + print("connection %s has no [connection] setting" % (arg_log)) return 1 arg_log = '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) stable_id = s_con.get_stable_id() if not stable_id: - print('connection %s has no stable-id set' % (arg_log)) + print("connection %s has no stable-id set" % (arg_log)) return 1 - re_match = re.search('\A(.*)-([0-9]+)\Z', stable_id) + re_match = re.search("\A(.*)-([0-9]+)\Z", stable_id) if not re_match: - stable_id = stable_id + '-1' + stable_id = stable_id + "-1" else: - stable_id = re_match.group(1) + '-' + str(int(re_match.group(2)) + 1) + stable_id = re_match.group(1) + "-" + str(int(re_match.group(2)) + 1) con2 = NM.SimpleConnection.new_clone(con) s_con = con2.get_setting_connection() s_con.set_property(NM.SETTING_CONNECTION_STABLE_ID, stable_id) result = {} + def _update2_cb(con, async_result, user_data): try: r = con.update2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r + result["result"] = r main_loop.quit() - con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT, - None, - None, - _update2_cb, - None) + con.update2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT, + None, + None, + _update2_cb, + None, + ) main_loop.run() - if 'error' in result: - print('update connection %s failed: %s' % (arg_log, result['error'])) + if "error" in result: + print("update connection %s failed: %s" % (arg_log, result["error"])) return 1 - print('update connection %s succeeded: %s' % (arg_log, result['result'])) + print("update connection %s succeeded: %s" % (arg_log, result["result"])) print('set stable-id to "%s"' % (stable_id)) return 0 -if __name__ == '__main__': + +if __name__ == "__main__": sys.exit(main()) diff --git a/examples/python/gi/nm-update2.py b/examples/python/gi/nm-update2.py index 23e277c78d..192768eeec 100755 --- a/examples/python/gi/nm-update2.py +++ b/examples/python/gi/nm-update2.py @@ -7,40 +7,50 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def find_connections(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: yield c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: yield c + def find_connection_first(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id): return f + def con_to_str(con): s_con = con.get_setting_connection() return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) + def usage(): arg0 = sys.argv[0] - arg0_spaced = ' ' * len(arg0) - print('Usage: %s [ [id] <id> | [uuid] <uuid> ] \\' % (arg0)) - print(' %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\' % (arg0_spaced)) - print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) - print(' %s [ --volatile ] \\' % (arg0_spaced)) - print(' %s [ --no-reapply ] \\' % (arg0_spaced)) + arg0_spaced = " " * len(arg0) + print("Usage: %s [ [id] <id> | [uuid] <uuid> ] \\" % (arg0)) + print( + " %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\" + % (arg0_spaced) + ) + print(" %s [ --block-autoconnect ] \\" % (arg0_spaced)) + print(" %s [ --volatile ] \\" % (arg0_spaced)) + print(" %s [ --no-reapply ] \\" % (arg0_spaced)) return 1 + def die(msg, print_usage=False): print(msg) if print_usage: usage() sys.exit(1) + def main(): main_loop = GLib.MainLoop() @@ -56,9 +66,9 @@ def main(): argv = list(sys.argv[1:]) while argv: - if argv[0] in ['id', 'uuid']: + if argv[0] in ["id", "uuid"]: if cons: - die('cannot specify multiple connections') + die("cannot specify multiple connections") if len(argv) < 2: die('missing argument for "%s" specifier' % (argv[0])) cons.extend(find_connections(nm_client, argv[0], argv[1])) @@ -68,31 +78,36 @@ def main(): die('could not find unique connection for "%s %s"' % (argv[0], argv[1])) argv = argv[2:] continue - if argv[0] in ['--block-autoconnect']: + if argv[0] in ["--block-autoconnect"]: arg_block_autoconnect = NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT argv = argv[1:] continue - if argv[0] in ['--volatile']: + if argv[0] in ["--volatile"]: arg_volatile = NM.SettingsUpdate2Flags.VOLATILE argv = argv[1:] continue - if argv[0] in ['--no-reapply']: + if argv[0] in ["--no-reapply"]: arg_no_reapply = NM.SettingsUpdate2Flags.NO_REAPPLY argv = argv[1:] continue - if argv[0] in ['--to-disk', '--in-memory', '--in-memory-detached', '--in-memory-only']: - if argv[0] == '--to-disk': + if argv[0] in [ + "--to-disk", + "--in-memory", + "--in-memory-detached", + "--in-memory-only", + ]: + if argv[0] == "--to-disk": v = NM.SettingsUpdate2Flags.TO_DISK - elif argv[0] == '--in-memory': + elif argv[0] == "--in-memory": v = NM.SettingsUpdate2Flags.IN_MEMORY - elif argv[0] == '--in-memory-detached': + elif argv[0] == "--in-memory-detached": v = NM.SettingsUpdate2Flags.IN_MEMORY_DETACHED - elif argv[0] == '--in-memory-only': + elif argv[0] == "--in-memory-only": v = NM.SettingsUpdate2Flags.IN_MEMORY_ONLY - elif argv[0] == '--keep': + elif argv[0] == "--keep": v = NM.SettingsUpdate2Flags.NONE else: - assert(False) + assert False if arg_mode is not None: die('duplicate storage modes ("%s")' % (argv[0])) arg_mode = v @@ -102,45 +117,55 @@ def main(): die('unknown argument "%s"' % (argv[0])) cons.extend(find_connections(nm_client, None, argv[0])) if len(cons) == 0: - die('could not find connection for "%s"' % (argv[0])) + die('could not find connection for "%s"' % (argv[0])) if len(cons) != 1: - die('could not find unique connection for "%s"' % (argv[0])) + die('could not find unique connection for "%s"' % (argv[0])) argv = argv[1:] continue if len(cons) != 1: - die('missing connection argument', True) + die("missing connection argument", True) con = cons[0] con2 = NM.SimpleConnection.new_clone(con) result = {} + def _update2_cb(con, async_result, user_data): try: r = con.update2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r + result["result"] = r main_loop.quit() - con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - (arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE) - | arg_block_autoconnect - | arg_volatile - | arg_no_reapply, - None, - None, - _update2_cb, - None) + con.update2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + (arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE) + | arg_block_autoconnect + | arg_volatile + | arg_no_reapply, + None, + None, + _update2_cb, + None, + ) main_loop.run() - if 'error' in result: - die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) + if "error" in result: + die( + "update connection %s failed [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["error"]) + ) + + print( + "update connection %s succeeded [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["result"]) + ) - print('update connection %s succeeded [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['result'])) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/python/gi/setting-user-data.py b/examples/python/gi/setting-user-data.py index fd86445b84..e21940743d 100755 --- a/examples/python/gi/setting-user-data.py +++ b/examples/python/gi/setting-user-data.py @@ -39,59 +39,60 @@ import sys import re import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM + def pr(v): import pprint + pprint.pprint(v, indent=4, depth=5, width=60) + def parse_args(): - args = { - 'set': False, - 'set-gobject': False, - 'filter': [], - 'data': [] - } + args = {"set": False, "set-gobject": False, "filter": [], "data": []} i = 1 while i < len(sys.argv): a = sys.argv[i] if i == 1: - if a in ['s', 'set']: - args['set'] = True + if a in ["s", "set"]: + args["set"] = True i += 1 continue - elif a in ['g', 'get']: - args['set'] = False + elif a in ["g", "get"]: + args["set"] = False i += 1 continue - if a in ['id', 'uuid']: - args['filter'].append((a, sys.argv[i+1])) + if a in ["id", "uuid"]: + args["filter"].append((a, sys.argv[i + 1])) i += 2 continue - if a in ['--set-gobject']: - args['set-gobject'] = True + if a in ["--set-gobject"]: + args["set-gobject"] = True i += 1 continue - if a == 'data': + if a == "data": i += 1 a = sys.argv[i] - if args['set']: - if a == '-d': - args['data'].append((sys.argv[i+1], None)) + if args["set"]: + if a == "-d": + args["data"].append((sys.argv[i + 1], None)) else: - args['data'].append((a, sys.argv[i+1])) + args["data"].append((a, sys.argv[i + 1])) i += 2 else: - args['data'].append(a) + args["data"].append(a) i += 1 return args + def connection_to_str(connection): - return '%s (%s)' % (connection.get_id(), connection.get_uuid()) + return "%s (%s)" % (connection.get_id(), connection.get_uuid()) + def connections_filter(connections, filter_data): connections = list(sorted(connections, key=connection_to_str)) @@ -102,20 +103,21 @@ def connections_filter(connections, filter_data): # them multiple times. l = [] for f in filter_data: - if f[0] == 'id': + if f[0] == "id": for c in connections: if f[1] == c.get_id(): l.append(c) else: - assert(f[0] == 'uuid') + assert f[0] == "uuid" for c in connections: if f[1] == c.get_uuid(): l.append(c) return l -def print_user_data(connection, data_allow_regex, data, prefix=''): + +def print_user_data(connection, data_allow_regex, data, prefix=""): s_u = connection.get_setting(NM.SettingUser) - n = 'none' + n = "none" keys_len = 0 keys = [] if s_u is not None: @@ -123,17 +125,17 @@ def print_user_data(connection, data_allow_regex, data, prefix=''): keys_len = len(all_keys) if data: for d in data: - if data_allow_regex and len(d) > 0 and d[0] == '~': + if data_allow_regex and len(d) > 0 and d[0] == "~": r = re.compile(d[1:]) keys.extend([k for k in all_keys if r.match(k)]) else: - keys.append (d) + keys.append(d) else: keys.extend(all_keys) - n = '%s' % (keys_len) + n = "%s" % (keys_len) - print('%s%s [%s]' % (prefix, connection_to_str(connection), n)) - dd = { } + print("%s%s [%s]" % (prefix, connection_to_str(connection), n)) + dd = {} if s_u is not None: dd = s_u.get_property(NM.SETTING_USER_DATA) for k in keys: @@ -145,7 +147,7 @@ def print_user_data(connection, data_allow_regex, data, prefix=''): else: print('%s MISSING: "%s"' % (prefix, k)) else: - assert(v == dd.get(k, None)) + assert v == dd.get(k, None) print('%s SET: "%s" = "%s"' % (prefix, k, v)) else: print('%s MISSING: "%s"' % (prefix, k)) @@ -155,20 +157,19 @@ def do_get(connections, data): first_line = True connections = list(connections) if not connections: - print('no matching connections (use id|uuid argument)') + print("no matching connections (use id|uuid argument)") sys.exit(1) for c in connections: if first_line: first_line = False else: - print('') + print("") print_user_data(c, True, data) + def do_set(connection, data, set_gobject): - print_user_data(connection, False, - [d[0] for d in data], - prefix = 'BEFORE: ') - print('') + print_user_data(connection, False, [d[0] for d in data], prefix="BEFORE: ") + print("") s_u = connection.get_setting(NM.SettingUser) if s_u is None: connection.add_setting(NM.SettingUser()) @@ -197,35 +198,37 @@ def do_set(connection, data, set_gobject): print('error setting key "%s" = "%s": %s' % (key, val, e)) sys.exit(1) - try: connection.commit_changes(True, None) except Exception as e: - print('failure to commit connection: %s' % (e)) + print("failure to commit connection: %s" % (e)) sys.exit(1) - print('') - print_user_data(connection, False, - [d[0] for d in data], - prefix = 'AFTER: ') + print("") + print_user_data(connection, False, [d[0] for d in data], prefix="AFTER: ") + ############################################################################### -if __name__ == '__main__': +if __name__ == "__main__": args = parse_args() nm_client = NM.Client.new(None) - connections = connections_filter(nm_client.get_connections(), args['filter']) + connections = connections_filter(nm_client.get_connections(), args["filter"]) - if args['set']: - if not args['data']: - print('Requires one or more arguments to set or delete') + if args["set"]: + if not args["data"]: + print("Requires one or more arguments to set or delete") sys.exit(1) if len(connections) != 1: - print('To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])' % - (len(connections), ', '.join([connection_to_str(c) for c in connections]))) + print( + "To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])" + % ( + len(connections), + ", ".join([connection_to_str(c) for c in connections]), + ) + ) sys.exit(1) - do_set(connections[0], args['data'], args['set-gobject']) + do_set(connections[0], args["data"], args["set-gobject"]) else: - do_get(connections, args['data']) - + do_get(connections, args["data"]) diff --git a/examples/python/gi/show-wifi-networks.py b/examples/python/gi/show-wifi-networks.py index e1ee4c3d5d..b865a85aa4 100755 --- a/examples/python/gi/show-wifi-networks.py +++ b/examples/python/gi/show-wifi-networks.py @@ -7,7 +7,8 @@ import locale import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # @@ -19,40 +20,50 @@ from gi.repository import NM # an error without it: http://www.python.org/dev/peps/pep-0263/ # + def clamp(value, minvalue, maxvalue): return max(minvalue, min(value, maxvalue)) + def ssid_to_utf8(ap): ssid = ap.get_ssid() if not ssid: return "" return NM.utils_ssid_to_utf8(ap.get_ssid().get_data()) + def print_device_info(device): active_ap = dev.get_active_access_point() ssid = None if active_ap is not None: ssid = ssid_to_utf8(active_ap) - info = "Device: %s | Driver: %s | Active AP: %s" % (dev.get_iface(), dev.get_driver(), ssid) + info = "Device: %s | Driver: %s | Active AP: %s" % ( + dev.get_iface(), + dev.get_driver(), + ssid, + ) print(info) - print('=' * len(info)) + print("=" * len(info)) + def mode_to_string(mode): - if mode == getattr(NM, '80211Mode').INFRA: + if mode == getattr(NM, "80211Mode").INFRA: return "INFRA" - if mode == getattr(NM, '80211Mode').ADHOC: + if mode == getattr(NM, "80211Mode").ADHOC: return "ADHOC" - if mode == getattr(NM, '80211Mode').AP: + if mode == getattr(NM, "80211Mode").AP: return "AP" return "UNKNOWN" + def flags_to_string(flags): - if flags & getattr(NM, '80211ApFlags').PRIVACY: + if flags & getattr(NM, "80211ApFlags").PRIVACY: return "PRIVACY" return "NONE" + def security_flags_to_string(flags): - NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags') + NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags") str = "" if flags & NM_AP_FLAGS.PAIR_WEP40: str = str + " PAIR_WEP40" @@ -79,43 +90,50 @@ def security_flags_to_string(flags): else: return "NONE" + def flags_to_security(flags, wpa_flags, rsn_flags): str = "" - if ((flags & getattr(NM, '80211ApFlags').PRIVACY) and - (wpa_flags == 0) and (rsn_flags == 0)): - str = str + " WEP" + if ( + (flags & getattr(NM, "80211ApFlags").PRIVACY) + and (wpa_flags == 0) + and (rsn_flags == 0) + ): + str = str + " WEP" if wpa_flags != 0: str = str + " WPA1" if rsn_flags != 0: str = str + " WPA2" - if ((wpa_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X) or - (rsn_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X)): + if (wpa_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X) or ( + rsn_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X + ): str = str + " 802.1X" return str.lstrip() + def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() flags = ap.get_flags() wpa_flags = ap.get_wpa_flags() rsn_flags = ap.get_rsn_flags() - print("SSID: %s" % (ssid_to_utf8(ap))) - print("BSSID: %s" % (ap.get_bssid())) - print("Frequency: %s" % (frequency)) - print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) - print("Mode: %s" % (mode_to_string(ap.get_mode()))) - print("Flags: %s" % (flags_to_string(flags))) - print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) - print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) - print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags))) + print("SSID: %s" % (ssid_to_utf8(ap))) + print("BSSID: %s" % (ap.get_bssid())) + print("Frequency: %s" % (frequency)) + print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) + print("Mode: %s" % (mode_to_string(ap.get_mode()))) + print("Flags: %s" % (flags_to_string(flags))) + print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) + print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) + print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags))) print("Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength)) print + if __name__ == "__main__": # Python apparently doesn't call setlocale() on its own? We have to call this or else # NM.utils_wifi_strength_bars() will think the locale is ASCII-only, and return the # fallback characters rather than the unicode bars - locale.setlocale(locale.LC_ALL, '') + locale.setlocale(locale.LC_ALL, "") nmc = NM.Client.new(None) devs = nmc.get_devices() @@ -125,4 +143,3 @@ if __name__ == "__main__": print_device_info(dev) for ap in dev.get_access_points(): print_ap_info(ap) - diff --git a/examples/python/gi/update-ip4-method.py b/examples/python/gi/update-ip4-method.py index 9bba619918..6fae260353 100755 --- a/examples/python/gi/update-ip4-method.py +++ b/examples/python/gi/update-ip4-method.py @@ -13,7 +13,8 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys, socket @@ -25,7 +26,9 @@ if __name__ == "__main__": method = sys.argv[2] if (method == "static" or method == "manual") and len(sys.argv) < 5: - print("Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1])) + print( + "Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1]) + ) sys.exit(1) uuid = sys.argv[1] @@ -69,4 +72,3 @@ if __name__ == "__main__": except Exception as e: sys.stderr.write("Error: %s\n" % e) break - diff --git a/examples/python/gi/vpn-import.py b/examples/python/gi/vpn-import.py index 78ae7cb182..a7c2f7f3d3 100755 --- a/examples/python/gi/vpn-import.py +++ b/examples/python/gi/vpn-import.py @@ -9,7 +9,8 @@ # VPN plugin. import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys @@ -35,17 +36,21 @@ for vpn_info in NM.VpnPluginInfo.list_load(): break if connection is None: - print("None of the VPN plugins was able to import \"%s\"" % (filename)) + print('None of the VPN plugins was able to import "%s"' % (filename)) sys.exit(1) connection.normalize() -print("connection imported from \"%s\" using plugin \"%s\" (\"%s\", %s)" % (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid())) +print( + 'connection imported from "%s" using plugin "%s" ("%s", %s)' + % (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid()) +) client = NM.Client.new(None) main_loop = GLib.MainLoop() + def added_cb(client, result, data): try: client.add_connection_finish(result) @@ -54,6 +59,7 @@ def added_cb(client, result, data): print("ERROR: failed to add connection: %s\n" % e) main_loop.quit() + client.add_connection_async(connection, True, None, added_cb, None) main_loop.run() diff --git a/examples/python/gi/wifi-p2p.py b/examples/python/gi/wifi-p2p.py index 804df34c89..526db5ecab 100755 --- a/examples/python/gi/wifi-p2p.py +++ b/examples/python/gi/wifi-p2p.py @@ -9,12 +9,14 @@ import sys import uuid import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM main_loop = None client = None + def create_profile(name, peer_mac): profile = NM.SimpleConnection.new() @@ -32,8 +34,10 @@ def create_profile(name, peer_mac): s_wifi_p2p = NM.SettingWifiP2P.new() s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_PEER, peer_mac) - s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_WFD_IES, - GLib.Bytes.new(b'\x00\x00\x06\x00\x90\x1c\x44\x00\xc8')) + s_wifi_p2p.set_property( + NM.SETTING_WIFI_P2P_WFD_IES, + GLib.Bytes.new(b"\x00\x00\x06\x00\x90\x1c\x44\x00\xc8"), + ) profile.add_setting(s_con) profile.add_setting(s_ip4) @@ -42,6 +46,7 @@ def create_profile(name, peer_mac): return profile + def activated_cb(client, result, data): try: client.add_and_activate_connection2_finish(result) @@ -50,35 +55,37 @@ def activated_cb(client, result, data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() + def scan_timeout_cb(device): peers = device.get_peers() if len(peers) == 0: main_loop.quit() sys.exit("No peer found") - print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs")); + print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs")) for p in peers: if p.get_wfd_ies() is not None: ies = p.get_wfd_ies().get_data().hex() else: ies = "" - print(" {:20} {:30} {:3} {:30}".format(p.get_hw_address(), - p.get_name(), - p.get_strength(), - ies)) + print( + " {:20} {:30} {:3} {:30}".format( + p.get_hw_address(), p.get_name(), p.get_strength(), ies + ) + ) print("") # Connect to first peer - profile = create_profile('P2P-connection', peers[0].get_hw_address()) - client.add_and_activate_connection2(profile, - device, - "/", - GLib.Variant('a{sv}', {}), - None, - activated_cb, - None) - print(" * Connecting to peer {} using profile '{}'".format(peers[0].get_hw_address(), - profile.get_id())) + profile = create_profile("P2P-connection", peers[0].get_hw_address()) + client.add_and_activate_connection2( + profile, device, "/", GLib.Variant("a{sv}", {}), None, activated_cb, None + ) + print( + " * Connecting to peer {} using profile '{}'".format( + peers[0].get_hw_address(), profile.get_id() + ) + ) + def start_find_cb(device, async_result, user_data): try: @@ -87,9 +94,10 @@ def start_find_cb(device, async_result, user_data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() - print(" * Scanning on device {}...".format(device.get_iface())); + print(" * Scanning on device {}...".format(device.get_iface())) GLib.timeout_add(10000, scan_timeout_cb, device) + if __name__ == "__main__": client = NM.Client.new(None) device = None @@ -103,7 +111,7 @@ if __name__ == "__main__": if device is None: sys.exit("No Wi-Fi P2P device found") - device.start_find(GLib.Variant('a{sv}', {}), None, start_find_cb, None) + device.start_find(GLib.Variant("a{sv}", {}), None, start_find_cb, None) main_loop = GLib.MainLoop() main_loop.run() diff --git a/src/tests/test-secret-agent.py b/src/tests/test-secret-agent.py index d8cabc6571..46f82b3485 100755 --- a/src/tests/test-secret-agent.py +++ b/src/tests/test-secret-agent.py @@ -6,11 +6,13 @@ import dbus import dbus.service import dbus.mainloop.glib -IFACE_SECRET_AGENT = 'org.freedesktop.NetworkManager.SecretAgent' -IFACE_AGENT_MANAGER = 'org.freedesktop.NetworkManager.AgentManager' +IFACE_SECRET_AGENT = "org.freedesktop.NetworkManager.SecretAgent" +IFACE_AGENT_MANAGER = "org.freedesktop.NetworkManager.AgentManager" + class NotAuthorizedException(dbus.DBusException): - _dbus_error_name = IFACE_SECRET_AGENT + '.NotAuthorized' + _dbus_error_name = IFACE_SECRET_AGENT + ".NotAuthorized" + class Agent(dbus.service.Object): def __init__(self, bus, object_path): @@ -18,41 +20,58 @@ class Agent(dbus.service.Object): self.bus = bus dbus.service.Object.__init__(self, bus, object_path) - @dbus.service.method(IFACE_SECRET_AGENT, - in_signature='a{sa{sv}}osasb', - out_signature='a{sa{sv}}', - sender_keyword='sender') - def GetSecrets(self, connection_hash, connection_path, setting_name, hints, request_new, sender=None): + @dbus.service.method( + IFACE_SECRET_AGENT, + in_signature="a{sa{sv}}osasb", + out_signature="a{sa{sv}}", + sender_keyword="sender", + ) + def GetSecrets( + self, + connection_hash, + connection_path, + setting_name, + hints, + request_new, + sender=None, + ): if not sender: raise NotAuthorizedException("Internal error: couldn't get sender") uid = self.bus.get_unix_user(sender) if uid != 0: raise NotAuthorizedException("UID %d not authorized" % uid) - print("Secrets requested path '%s' setting '%s' hints '%s' new %d" % (connection_path, setting_name, str(hints), request_new)) + print( + "Secrets requested path '%s' setting '%s' hints '%s' new %d" + % (connection_path, setting_name, str(hints), request_new) + ) # return some random GSM secrets - s_gsm = dbus.Dictionary({'password': 'asdfadfasdfaf'}) - con = dbus.Dictionary({'gsm': s_gsm}) + s_gsm = dbus.Dictionary({"password": "asdfadfasdfaf"}) + con = dbus.Dictionary({"gsm": s_gsm}) return con + def register(proxy): proxy.Register("test.agent.id", dbus_interface=IFACE_AGENT_MANAGER) print("Registered!") return False + def unregister(proxy, loop): proxy.Unregister(dbus_interface=IFACE_AGENT_MANAGER) loop.quit() return False + def main(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() obj = Agent(bus, "/org/freedesktop/NetworkManager/SecretAgent") - proxy = bus.get_object("org.freedesktop.NetworkManager", - "/org/freedesktop/NetworkManager/AgentManager") + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/AgentManager" + ) mainloop = GLib.MainLoop() @@ -65,8 +84,8 @@ def main(): pass print("Unregistering...") - unregister(proxy, mainloop); + unregister(proxy, mainloop) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/tools/debug-helper.py b/tools/debug-helper.py index b841c39cca..708cf73c98 100755 --- a/tools/debug-helper.py +++ b/tools/debug-helper.py @@ -6,56 +6,85 @@ import argparse bus = dbus.SystemBus() -parser = argparse.ArgumentParser(description='Interface to easily control logging levels for NetworkManager, ModemManager, and wpasupplicant.') +parser = argparse.ArgumentParser( + description="Interface to easily control logging levels for NetworkManager, ModemManager, and wpasupplicant." +) # NM options -parser.add_argument('--nm', dest='do_set_nm_logging', action='store', - help='modify log level for NetworkManager (debug, info, etc.)') -parser.add_argument('--domains', dest='log_domains', action='store', - default=[], nargs='+', - help='log "domains" to use with NetworkManager (HW, CORE, etc.)') +parser.add_argument( + "--nm", + dest="do_set_nm_logging", + action="store", + help="modify log level for NetworkManager (debug, info, etc.)", +) +parser.add_argument( + "--domains", + dest="log_domains", + action="store", + default=[], + nargs="+", + help='log "domains" to use with NetworkManager (HW, CORE, etc.)', +) # MM options -parser.add_argument('--mm', dest='do_set_mm_logging', action='store', - help='modify log level for ModemManager (debug, info, etc.)') +parser.add_argument( + "--mm", + dest="do_set_mm_logging", + action="store", + help="modify log level for ModemManager (debug, info, etc.)", +) # wpasupplicant options -parser.add_argument('--wpa', dest='do_set_wpa_logging', action='store', - help='modify log level for wpasupplicant (debug, msgdump, info, etc.)') +parser.add_argument( + "--wpa", + dest="do_set_wpa_logging", + action="store", + help="modify log level for wpasupplicant (debug, msgdump, info, etc.)", +) args = parser.parse_args() if args.do_set_nm_logging: - #print args.log_domains + # print args.log_domains dom_msg = "" if args.log_domains: - dom_msg = " for domains: " + ','.join(args.log_domains) - print("Setting NetworkManager log level to '" + args.do_set_nm_logging + "'" + dom_msg) + dom_msg = " for domains: " + ",".join(args.log_domains) + print( + "Setting NetworkManager log level to '" + args.do_set_nm_logging + "'" + dom_msg + ) - nm_bus = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - nm = dbus.Interface(nm_bus, dbus_interface='org.freedesktop.NetworkManager') - nm.SetLogging(args.do_set_nm_logging, ','.join(args.log_domains)) + nm_bus = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + nm = dbus.Interface(nm_bus, dbus_interface="org.freedesktop.NetworkManager") + nm.SetLogging(args.do_set_nm_logging, ",".join(args.log_domains)) if args.do_set_mm_logging: print("Setting ModemManager log level to '" + args.do_set_mm_logging + "'") - mm_bus = bus.get_object('org.freedesktop.ModemManager', '/org/freedesktop/ModemManager') - mm = dbus.Interface(mm_bus, dbus_interface='org.freedesktop.ModemManager') + mm_bus = bus.get_object( + "org.freedesktop.ModemManager", "/org/freedesktop/ModemManager" + ) + mm = dbus.Interface(mm_bus, dbus_interface="org.freedesktop.ModemManager") mm.SetLogging(args.do_set_mm_logging) if args.do_set_wpa_logging: print("Setting wpa_supplicant log level to '" + args.do_set_wpa_logging + "'") - if 'debug' in args.do_set_wpa_logging or 'msgdump' in args.do_set_wpa_logging: + if "debug" in args.do_set_wpa_logging or "msgdump" in args.do_set_wpa_logging: print("Enabling timestamps for wpasupplicant debugging logs") use_timestamps = dbus.Boolean(True, variant_level=1) else: print("Disabling timestamps for wpasupplicant debugging logs") use_timestamps = dbus.Boolean(False, variant_level=1) - wpa_bus = bus.get_object('fi.w1.wpa_supplicant1', '/fi/w1/wpa_supplicant1') - wpa_properties = dbus.Interface(wpa_bus, dbus_interface='org.freedesktop.DBus.Properties') - wpa_properties.Set('fi.w1.wpa_supplicant1', 'DebugTimestamp', use_timestamps) - wpa_properties.Set('fi.w1.wpa_supplicant1', 'DebugLevel', - dbus.String(args.do_set_wpa_logging, variant_level=1)) - + wpa_bus = bus.get_object("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1") + wpa_properties = dbus.Interface( + wpa_bus, dbus_interface="org.freedesktop.DBus.Properties" + ) + wpa_properties.Set("fi.w1.wpa_supplicant1", "DebugTimestamp", use_timestamps) + wpa_properties.Set( + "fi.w1.wpa_supplicant1", + "DebugLevel", + dbus.String(args.do_set_wpa_logging, variant_level=1), + ) diff --git a/tools/generate-docs-nm-settings-docs-gir.py b/tools/generate-docs-nm-settings-docs-gir.py index f63c48b1ae..0eb0da9785 100755 --- a/tools/generate-docs-nm-settings-docs-gir.py +++ b/tools/generate-docs-nm-settings-docs-gir.py @@ -8,171 +8,196 @@ from __future__ import print_function import os import gi -gi.require_version('GIRepository', '2.0') + +gi.require_version("GIRepository", "2.0") from gi.repository import GIRepository import argparse, re, sys import xml.etree.ElementTree as ET try: - libs = os.environ['LD_LIBRARY_PATH'].split(':') + libs = os.environ["LD_LIBRARY_PATH"].split(":") libs.reverse() for lib in libs: GIRepository.Repository.prepend_library_path(lib) except AttributeError: - # An old GI version, that has no prepend_library_path - # It's alright, it probably interprets LD_LIBRARY_PATH - # correctly. - pass + # An old GI version, that has no prepend_library_path + # It's alright, it probably interprets LD_LIBRARY_PATH + # correctly. + pass except KeyError: - pass + pass -gi.require_version('NM', '1.0') +gi.require_version("NM", "1.0") from gi.repository import NM, GObject dbus_type_name_map = { - 'b': 'boolean', - 's': 'string', - 'i': 'int32', - 'u': 'uint32', - 't': 'uint64', - 'x': 'int64', - 'y': 'byte', - 'as': 'array of string', - 'au': 'array of uint32', - 'ay': 'byte array', - 'a{ss}': 'dict of string to string', - 'a{sv}': 'vardict', - 'aa{sv}': 'array of vardict', - 'aau': 'array of array of uint32', - 'aay': 'array of byte array', - 'a(ayuay)': 'array of legacy IPv6 address struct', - 'a(ayuayu)': 'array of legacy IPv6 route struct', + "b": "boolean", + "s": "string", + "i": "int32", + "u": "uint32", + "t": "uint64", + "x": "int64", + "y": "byte", + "as": "array of string", + "au": "array of uint32", + "ay": "byte array", + "a{ss}": "dict of string to string", + "a{sv}": "vardict", + "aa{sv}": "array of vardict", + "aau": "array of array of uint32", + "aay": "array of byte array", + "a(ayuay)": "array of legacy IPv6 address struct", + "a(ayuayu)": "array of legacy IPv6 route struct", } ns_map = { - 'c': 'http://www.gtk.org/introspection/c/1.0', - 'gi': 'http://www.gtk.org/introspection/core/1.0', - 'glib': 'http://www.gtk.org/introspection/glib/1.0' + "c": "http://www.gtk.org/introspection/c/1.0", + "gi": "http://www.gtk.org/introspection/core/1.0", + "glib": "http://www.gtk.org/introspection/glib/1.0", } -identifier_key = '{%s}identifier' % ns_map['c'] -nick_key = '{%s}nick' % ns_map['glib'] -symbol_prefix_key = '{%s}symbol-prefix' % ns_map['c'] +identifier_key = "{%s}identifier" % ns_map["c"] +nick_key = "{%s}nick" % ns_map["glib"] +symbol_prefix_key = "{%s}symbol-prefix" % ns_map["c"] constants = { - 'TRUE': 'TRUE', - 'FALSE': 'FALSE', - 'G_MAXUINT32': 'G_MAXUINT32', - 'NULL': 'NULL' } + "TRUE": "TRUE", + "FALSE": "FALSE", + "G_MAXUINT32": "G_MAXUINT32", + "NULL": "NULL", +} setting_names = {} + def get_setting_name_define(setting): n = setting.attrib[symbol_prefix_key] if n and n.startswith("setting_"): return n[8:].upper() - raise Exception("Unexpected symbol_prefix_key \"%s\"" % (n)) + raise Exception('Unexpected symbol_prefix_key "%s"' % (n)) + def init_constants(girxml, settings): - for const in girxml.findall('./gi:namespace/gi:constant', ns_map): - cname = const.attrib['{%s}type' % ns_map['c']] - cvalue = const.attrib['value'] + for const in girxml.findall("./gi:namespace/gi:constant", ns_map): + cname = const.attrib["{%s}type" % ns_map["c"]] + cvalue = const.attrib["value"] if const.find('./gi:type[@name="utf8"]', ns_map) is not None: cvalue = '"%s"' % cvalue constants[cname] = cvalue - for enum in girxml.findall('./gi:namespace/gi:enumeration', ns_map): - for enumval in enum.findall('./gi:member', ns_map): + for enum in girxml.findall("./gi:namespace/gi:enumeration", ns_map): + for enumval in enum.findall("./gi:member", ns_map): cname = enumval.attrib[identifier_key] - cvalue = '%s (%s)' % (cname, enumval.attrib['value']) + cvalue = "%s (%s)" % (cname, enumval.attrib["value"]) constants[cname] = cvalue - for enum in girxml.findall('./gi:namespace/gi:bitfield', ns_map): - for enumval in enum.findall('./gi:member', ns_map): + for enum in girxml.findall("./gi:namespace/gi:bitfield", ns_map): + for enumval in enum.findall("./gi:member", ns_map): cname = enumval.attrib[identifier_key] - cvalue = '%s (0x%x)' % (cname, int(enumval.attrib['value'])) + cvalue = "%s (0x%x)" % (cname, int(enumval.attrib["value"])) constants[cname] = cvalue for setting in settings: - setting_type_name = 'NM' + setting.attrib['name']; - setting_name_symbol = 'NM_SETTING_' + get_setting_name_define(setting) + '_SETTING_NAME' + setting_type_name = "NM" + setting.attrib["name"] + setting_name_symbol = ( + "NM_SETTING_" + get_setting_name_define(setting) + "_SETTING_NAME" + ) if setting_name_symbol in constants: setting_name = constants[setting_name_symbol] setting_names[setting_type_name] = setting_name + def get_prop_type(setting, pspec): dbus_type = setting.get_dbus_property_type(pspec.name).dup_string() prop_type = dbus_type_name_map[dbus_type] - if GObject.type_is_a(pspec.value_type, GObject.TYPE_ENUM) or GObject.type_is_a(pspec.value_type, GObject.TYPE_FLAGS): + if GObject.type_is_a(pspec.value_type, GObject.TYPE_ENUM) or GObject.type_is_a( + pspec.value_type, GObject.TYPE_FLAGS + ): prop_type = "%s (%s)" % (pspec.value_type.name, prop_type) return prop_type + def get_docs(propxml): - doc_xml = propxml.find('gi:doc', ns_map) + doc_xml = propxml.find("gi:doc", ns_map) if doc_xml is None: return None doc = doc_xml.text - if 'deprecated' in propxml.attrib: - doc = doc + ' Deprecated: ' + propxml.attrib['deprecated'] + if "deprecated" in propxml.attrib: + doc = doc + " Deprecated: " + propxml.attrib["deprecated"] - doc = re.sub(r'\n\s*', r' ', doc) + doc = re.sub(r"\n\s*", r" ", doc) # Expand constants - doc = re.sub(r'%([^%]\w*)', lambda match: constants[match.group(1)], doc) + doc = re.sub(r"%([^%]\w*)", lambda match: constants[match.group(1)], doc) # #NMSettingWired:mac-address -> "mac-address" - doc = re.sub(r'#[A-Za-z0-9_]*:([A-Za-z0-9_-]*)', r'"\1"', doc) + doc = re.sub(r"#[A-Za-z0-9_]*:([A-Za-z0-9_-]*)", r'"\1"', doc) # #NMSettingWired setting -> "802-3-ethernet" setting - doc = re.sub(r'#([A-Z]\w*) setting', lambda match: setting_names[match.group(1)] + ' setting', doc) + doc = re.sub( + r"#([A-Z]\w*) setting", + lambda match: setting_names[match.group(1)] + " setting", + doc, + ) # remaining gtk-doc cleanup - doc = doc.replace('%%', '%') - doc = doc.replace('<!-- -->', '') - doc = re.sub(r' Element-.ype:.*', '', doc) - doc = re.sub(r'#([A-Z]\w*)', r'\1', doc) + doc = doc.replace("%%", "%") + doc = doc.replace("<!-- -->", "") + doc = re.sub(r" Element-.ype:.*", "", doc) + doc = re.sub(r"#([A-Z]\w*)", r"\1", doc) # Remove sentences that refer to functions - doc = re.sub(r'\.\s+[^.]*\w\(\)[^.]*\.', r'.', doc) + doc = re.sub(r"\.\s+[^.]*\w\(\)[^.]*\.", r".", doc) return doc + def get_default_value(setting, pspec, propxml): - default_value = setting.get_property(pspec.name.replace('-', '_')) + default_value = setting.get_property(pspec.name.replace("-", "_")) if default_value is None: return default_value value_type = get_prop_type(setting, pspec) - if value_type == 'string' and default_value != '' and pspec.name != 'name': + if value_type == "string" and default_value != "" and pspec.name != "name": default_value = '"%s"' % default_value - elif value_type == 'boolean': + elif value_type == "boolean": default_value = str(default_value).upper() - elif value_type == 'byte array': - default_value = '[]' - elif str(default_value).startswith('<'): + elif value_type == "byte array": + default_value = "[]" + elif str(default_value).startswith("<"): default_value = None - elif str(default_value).startswith('['): + elif str(default_value).startswith("["): default_value = None return default_value + def settings_sort_key(x): - x_prefix = x.attrib['{%s}symbol-prefix' % ns_map['c']] + x_prefix = x.attrib["{%s}symbol-prefix" % ns_map["c"]] # always sort NMSettingConnection first - return (x_prefix != "setting_connection", x_prefix); + return (x_prefix != "setting_connection", x_prefix) + def escape(val): - return str(val).replace('"', '"') + return str(val).replace('"', """) + def usage(): print("Usage: %s --gir FILE --output FILE" % sys.argv[0]) exit() + parser = argparse.ArgumentParser() -parser.add_argument('-l', '--lib-path', metavar='PATH', action='append', help='path to scan for shared libraries') -parser.add_argument('-g', '--gir', metavar='FILE', help='NM-1.0.gir file') -parser.add_argument('-o', '--output', metavar='FILE', help='output file') +parser.add_argument( + "-l", + "--lib-path", + metavar="PATH", + action="append", + help="path to scan for shared libraries", +) +parser.add_argument("-g", "--gir", metavar="FILE", help="NM-1.0.gir file") +parser.add_argument("-o", "--output", metavar="FILE", help="output file") args = parser.parse_args() if args.gir is None or args.output is None: @@ -183,37 +208,50 @@ if args.lib_path: GIRepository.Repository.prepend_library_path(lib) girxml = ET.parse(args.gir).getroot() -outfile = open(args.output, mode='w') +outfile = open(args.output, mode="w") basexml = girxml.find('./gi:namespace/gi:class[@name="Setting"]', ns_map) settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map) # Hack. Need a better way to do this ipxml = girxml.find('./gi:namespace/gi:class[@name="SettingIPConfig"]', ns_map) -settings.extend(girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map)) +settings.extend( + girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map) +) settings = sorted(settings, key=settings_sort_key) init_constants(girxml, settings) -outfile.write("""<?xml version=\"1.0\"?> +outfile.write( + """<?xml version=\"1.0\"?> <!DOCTYPE nm-setting-docs [ <!ENTITY quot """> ]> <nm-setting-docs> -""") +""" +) for settingxml in settings: - if 'abstract' in settingxml.attrib: + if "abstract" in settingxml.attrib: continue - new_func = NM.__getattr__(settingxml.attrib['name']) + new_func = NM.__getattr__(settingxml.attrib["name"]) setting = new_func() class_desc = get_docs(settingxml) if class_desc is None: - raise Exception("%s needs a gtk-doc block with one-line description" % setting.props.name) - outfile.write(" <setting name=\"%s\" description=\"%s\" name_upper=\"%s\" >\n" % (setting.props.name, class_desc, get_setting_name_define (settingxml))) - - setting_properties = { prop.name: prop for prop in GObject.list_properties(setting) if prop.name != 'name' } + raise Exception( + "%s needs a gtk-doc block with one-line description" % setting.props.name + ) + outfile.write( + ' <setting name="%s" description="%s" name_upper="%s" >\n' + % (setting.props.name, class_desc, get_setting_name_define(settingxml)) + ) + + setting_properties = { + prop.name: prop + for prop in GObject.list_properties(setting) + if prop.name != "name" + } for prop in sorted(setting_properties): pspec = setting_properties[prop] @@ -228,17 +266,21 @@ for settingxml in settings: value_desc = get_docs(propxml) default_value = get_default_value(setting, pspec, propxml) - prop_upper = prop.upper().replace('-', '_') + prop_upper = prop.upper().replace("-", "_") if value_desc is None: - raise Exception("%s.%s needs a documentation description" % (setting.props.name, prop)) + raise Exception( + "%s.%s needs a documentation description" % (setting.props.name, prop) + ) - default_value_as_xml = '' + default_value_as_xml = "" if default_value is not None: - default_value_as_xml = (' default=\"%s\"' % (escape(default_value))) + default_value_as_xml = ' default="%s"' % (escape(default_value)) - outfile.write(" <property name=\"%s\" name_upper=\"%s\" type=\"%s\"%s description=\"%s\" />\n" % - (prop, prop_upper, value_type, default_value_as_xml, escape(value_desc))) + outfile.write( + ' <property name="%s" name_upper="%s" type="%s"%s description="%s" />\n' + % (prop, prop_upper, value_type, default_value_as_xml, escape(value_desc)) + ) outfile.write(" </setting>\n") diff --git a/tools/generate-docs-nm-settings-docs-merge.py b/tools/generate-docs-nm-settings-docs-merge.py index bf58669819..0da3a0bbaf 100755 --- a/tools/generate-docs-nm-settings-docs-merge.py +++ b/tools/generate-docs-nm-settings-docs-merge.py @@ -61,28 +61,33 @@ _setting_name_order = [ "wpan", ] + def _setting_name_order_idx(name): try: return _setting_name_order.index(name) except ValueError: return len(_setting_name_order) + def key_fcn_setting_name(n1): return (_setting_name_order_idx(n1), n1) -def iter_keys_of_dicts(dicts, key = None): + +def iter_keys_of_dicts(dicts, key=None): keys = set([k for d in dicts for k in d.keys()]) - return sorted(keys, key = key) + return sorted(keys, key=key) + def node_to_dict(node, tag, key_attr): dictionary = collections.OrderedDict() if node is not None: for n in node.iter(tag): k = n.get(key_attr) - assert(k is not None) + assert k is not None dictionary[k] = n return dictionary + def node_get_attr(nodes, name): for n in nodes: if n is None: @@ -92,18 +97,20 @@ def node_get_attr(nodes, name): return x return None + def node_set_attr(dst_node, name, nodes): x = node_get_attr(nodes, name) if x: dst_node.set(name, x) + ############################################################################### gl_only_from_first = False argv = list(sys.argv[1:]) while True: - if argv[0] == '--only-from-first': + if argv[0] == "--only-from-first": gl_only_from_first = True del argv[0] continue @@ -119,54 +126,51 @@ gl_input_files = list(argv[1:]) xml_roots = list([ET.parse(f).getroot() for f in gl_input_files]) -assert(all([root.tag == 'nm-setting-docs' for root in xml_roots])) +assert all([root.tag == "nm-setting-docs" for root in xml_roots]) -settings_roots = list([node_to_dict(root, 'setting', 'name') for root in xml_roots]) +settings_roots = list([node_to_dict(root, "setting", "name") for root in xml_roots]) -root_node = ET.Element('nm-setting-docs') +root_node = ET.Element("nm-setting-docs") for setting_name in iter_keys_of_dicts(settings_roots, key_fcn_setting_name): settings = list([d.get(setting_name) for d in settings_roots]) - if gl_only_from_first \ - and settings[0] is None: + if gl_only_from_first and settings[0] is None: continue - properties = list([node_to_dict(s, 'property', 'name') for s in settings]) + properties = list([node_to_dict(s, "property", "name") for s in settings]) - if gl_only_from_first \ - and not properties[0]: + if gl_only_from_first and not properties[0]: continue - setting_node = ET.SubElement(root_node, 'setting') + setting_node = ET.SubElement(root_node, "setting") - setting_node.set('name', setting_name) + setting_node.set("name", setting_name) - node_set_attr(setting_node, 'description', settings) - node_set_attr(setting_node, 'name_upper', settings) - node_set_attr(setting_node, 'alias', settings) + node_set_attr(setting_node, "description", settings) + node_set_attr(setting_node, "name_upper", settings) + node_set_attr(setting_node, "alias", settings) for property_name in iter_keys_of_dicts(properties): properties_attrs = list([p.get(property_name) for p in properties]) - if gl_only_from_first \ - and properties_attrs[0] is None: + if gl_only_from_first and properties_attrs[0] is None: continue - property_node = ET.SubElement(setting_node, 'property') - property_node.set('name', property_name) - property_node.set('name_upper', property_name.upper().replace('-', '_')) + property_node = ET.SubElement(setting_node, "property") + property_node.set("name", property_name) + property_node.set("name_upper", property_name.upper().replace("-", "_")) - x = node_get_attr(properties_attrs, 'format') + x = node_get_attr(properties_attrs, "format") if x: - property_node.set('type', x) + property_node.set("type", x) else: - node_set_attr(property_node, 'type', properties_attrs) + node_set_attr(property_node, "type", properties_attrs) - node_set_attr(property_node, 'default', properties_attrs) - node_set_attr(property_node, 'description', properties_attrs) - node_set_attr(property_node, 'alias', properties_attrs) + node_set_attr(property_node, "default", properties_attrs) + node_set_attr(property_node, "description", properties_attrs) + node_set_attr(property_node, "alias", properties_attrs) ET.ElementTree(root_node).write(gl_output_xml_file) diff --git a/tools/test-networkmanager-service.py b/tools/test-networkmanager-service.py index 56a53a4517..359c5e5ded 100755 --- a/tools/test-networkmanager-service.py +++ b/tools/test-networkmanager-service.py @@ -8,7 +8,7 @@ import gi from gi.repository import GLib try: - gi.require_version('NM', '1.0') + gi.require_version("NM", "1.0") from gi.repository import NM except Exception as e: print("Cannot load gi.NM: %s" % (str(e))) @@ -30,23 +30,28 @@ _DEFAULT_ARG = object() ############################################################################### + class Global: pass + gl = None ############################################################################### + class TestError(AssertionError): - def __init__(self, message = 'Unspecified error', errors = None): + def __init__(self, message="Unspecified error", errors=None): AssertionError.__init__(self, message) self.errors = errors + ############################################################################### + class Util: - PY3 = (sys.version_info[0] == 3) + PY3 = sys.version_info[0] == 3 @staticmethod def g_source_remove(source_id): @@ -54,14 +59,14 @@ class Util: GLib.source_remove(source_id) @staticmethod - def addr_family_check(family, allow_af_unspec = False): + def addr_family_check(family, allow_af_unspec=False): if family == socket.AF_INET: return if family == socket.AF_INET6: return if allow_af_unspec and family == socket.AF_UNSPEC: return - raise TestError('invalid address family %s' % (family)) + raise TestError("invalid address family %s" % (family)) @staticmethod def ip_addr_pton(addr, family=None): @@ -86,11 +91,11 @@ class Util: return (a, family) @staticmethod - def ip_addr_ntop(addr, family = None): + def ip_addr_ntop(addr, family=None): if Util.PY3: a = bytes(addr) else: - a = ''.join([chr(c) for c in addr]) + a = "".join([chr(c) for c in addr]) if len(a) == 4: f = socket.AF_INET elif len(a) == 16: @@ -98,11 +103,14 @@ class Util: else: raise TestError("Invalid binary IP address '%s'" % (repr(addr))) if family is not None and f != family: - raise TestError("Unexpected address family. Expected %s but ip address was %s" % (family, repr(addr))) + raise TestError( + "Unexpected address family. Expected %s but ip address was %s" + % (family, repr(addr)) + ) return socket.inet_ntop(f, a) @staticmethod - def ip_addr_norm(addr, family = None): + def ip_addr_norm(addr, family=None): a, family = Util.ip_addr_pton(addr, family) return (Util.ip_addr_ntop(a, family), family) @@ -121,10 +129,12 @@ class Util: return Util.ip_addr_pton(addr, socket.AF_INET6)[0] @staticmethod - def ip_net_parse(net, family = None): - parts = net.split('/') + def ip_net_parse(net, family=None): + parts = net.split("/") if len(parts) != 2: - raise TestError("Invalid IP network '%s' has not '/' for the prefix length" % (net)) + raise TestError( + "Invalid IP network '%s' has not '/' for the prefix length" % (net) + ) prefix = int(parts[1]) addr, family = Util.ip_addr_norm(parts[0], family) if family == socket.AF_INET: @@ -135,14 +145,16 @@ class Util: raise TestError("Invalid prefix length for IPv4 address '%s'" % (net)) return (addr, prefix, family) - class RandomSeed(): + class RandomSeed: def __init__(self, seed): self.cnt = 0 self.seed = str(seed) + def _next(self): c = self.cnt self.cnt += 1 - return self.seed + '-' + str(c) + return self.seed + "-" + str(c) + @staticmethod def wrap(seed): if seed is None: @@ -150,8 +162,9 @@ class Util: if isinstance(seed, Util.RandomSeed): return seed return Util.RandomSeed(seed) + @staticmethod - def get(seed, extra_seed = None): + def get(seed, extra_seed=None): if seed is None: return None if isinstance(seed, Util.RandomSeed): @@ -162,12 +175,14 @@ class Util: try: extra_seed = Util.RandomSeed._extra_seed except: - extra_seed = os.environ.get('NM_TEST_NETWORKMANAGER_SERVICE_SEED', '') + extra_seed = os.environ.get( + "NM_TEST_NETWORKMANAGER_SERVICE_SEED", "" + ) Util.RandomSeed._extra_seed = extra_seed return extra_seed + seed @staticmethod - def random_stream(seed, length = None): + def random_stream(seed, length=None): seed = Util.RandomSeed.wrap(seed) # generates a stream of integers, in the range [0..255] if seed is None: @@ -181,7 +196,7 @@ class Util: while length is None or length > 0: if not v: s = Util.RandomSeed.get(seed) - s = s.encode('utf8') + s = s.encode("utf8") v = hashlib.sha256(s).hexdigest() yield int(v[0:2], 16) v = v[2:] @@ -189,7 +204,7 @@ class Util: length -= 1 @staticmethod - def random_int(seed, v_start = _DEFAULT_ARG, v_end = _DEFAULT_ARG): + def random_int(seed, v_start=_DEFAULT_ARG, v_end=_DEFAULT_ARG): # - if neither start not end is give, return a number in the range # u32 range [0, 0xFFFFFFFF] # - if only start is given (the first argument), interpret it as @@ -231,7 +246,9 @@ class Util: all_set = list(all_set) result = [] seed = Util.RandomSeed.wrap(seed) - for i in list(range(Util.random_int(Util.RandomSeed.get(seed), len(all_set) + 1))): + for i in list( + range(Util.random_int(Util.RandomSeed.get(seed), len(all_set) + 1)) + ): idx = Util.random_int(Util.RandomSeed.get(seed), len(all_set)) result.append(all_set[idx]) del all_set[idx] @@ -239,10 +256,10 @@ class Util: @staticmethod def random_mac(seed): - return '%02X:%02X:%02X:%02X:%02X:%02X' % tuple(Util.random_stream(seed, 6)) + return "%02X:%02X:%02X:%02X:%02X:%02X" % tuple(Util.random_stream(seed, 6)) @staticmethod - def random_ip(seed, net = None, family = None): + def random_ip(seed, net=None, family=None): if net is not None: mask, prefix, family = Util.ip_net_parse(net, family) a_mask, unused = Util.ip_addr_pton(mask, family) @@ -277,120 +294,156 @@ class Util: @staticmethod def variant_from_dbus(val): if isinstance(val, (dbus.String, str)): - return GLib.Variant('s', str(val)) + return GLib.Variant("s", str(val)) if isinstance(val, dbus.UInt32): - return GLib.Variant('u', int(val)) + return GLib.Variant("u", int(val)) if isinstance(val, dbus.UInt64): - return GLib.Variant('t', int(val)) + return GLib.Variant("t", int(val)) if isinstance(val, dbus.Boolean): - return GLib.Variant('b', bool(val)) + return GLib.Variant("b", bool(val)) if isinstance(val, dbus.Byte): - return GLib.Variant('y', int(val)) + return GLib.Variant("y", int(val)) if isinstance(val, dbus.Array): try: - if val.signature == 's': - return GLib.Variant('as', [Util.variant_from_dbus(x) for x in val]) - if val.signature == 'b': - return GLib.Variant('ab', [Util.variant_from_dbus(x) for x in val]) - if val.signature == 'y': - return GLib.Variant('ay', [int(x) for x in val]) - if val.signature == 'u': - return GLib.Variant('au', [int(x) for x in val]) - if val.signature == 'ay': - return GLib.Variant('aay', [Util.variant_from_dbus(x) for x in val]) - if val.signature == 'au': - return GLib.Variant('aau', [Util.variant_from_dbus(x) for x in val]) - if val.signature == 'a{sv}': - return GLib.Variant('aa{sv}', [collections.OrderedDict([(str(k), Util.variant_from_dbus(v)) for k, v in addr.items()]) for addr in val]) - if val.signature == '(ayuay)': - return GLib.Variant('a(ayuay)', [Util.variant_from_dbus(x) for x in val]) - if val.signature == '(ayuayu)': - return GLib.Variant('a(ayuayu)', [Util.variant_from_dbus(x) for x in val]) + if val.signature == "s": + return GLib.Variant("as", [Util.variant_from_dbus(x) for x in val]) + if val.signature == "b": + return GLib.Variant("ab", [Util.variant_from_dbus(x) for x in val]) + if val.signature == "y": + return GLib.Variant("ay", [int(x) for x in val]) + if val.signature == "u": + return GLib.Variant("au", [int(x) for x in val]) + if val.signature == "ay": + return GLib.Variant("aay", [Util.variant_from_dbus(x) for x in val]) + if val.signature == "au": + return GLib.Variant("aau", [Util.variant_from_dbus(x) for x in val]) + if val.signature == "a{sv}": + return GLib.Variant( + "aa{sv}", + [ + collections.OrderedDict( + [ + (str(k), Util.variant_from_dbus(v)) + for k, v in addr.items() + ] + ) + for addr in val + ], + ) + if val.signature == "(ayuay)": + return GLib.Variant( + "a(ayuay)", [Util.variant_from_dbus(x) for x in val] + ) + if val.signature == "(ayuayu)": + return GLib.Variant( + "a(ayuayu)", [Util.variant_from_dbus(x) for x in val] + ) except Exception as e: - raise Exception("Cannot convert array element to type '%s': %s" % (val.signature, e.message)) + raise Exception( + "Cannot convert array element to type '%s': %s" + % (val.signature, e.message) + ) if isinstance(val, dbus.Dictionary): - if val.signature == 'ss': - return GLib.Variant('a{ss}', collections.OrderedDict([(str(k), str(v)) for k, v in val.items()])) - if val.signature == 'sv': - return GLib.Variant('a{sv}', collections.OrderedDict([(str(k), Util.variant_from_dbus(v)) for k, v in val.items()])) - if val.signature == 'sa{sv}': - c = collections.OrderedDict([ - (str(key1), - collections.OrderedDict([(str(key2), Util.variant_from_dbus(arr2)) for key2, arr2 in arr1.items()]) - ) for key1, arr1 in val.items() - ]) - return GLib.Variant('a{sa{sv}}', c) + if val.signature == "ss": + return GLib.Variant( + "a{ss}", + collections.OrderedDict([(str(k), str(v)) for k, v in val.items()]), + ) + if val.signature == "sv": + return GLib.Variant( + "a{sv}", + collections.OrderedDict( + [(str(k), Util.variant_from_dbus(v)) for k, v in val.items()] + ), + ) + if val.signature == "sa{sv}": + c = collections.OrderedDict( + [ + ( + str(key1), + collections.OrderedDict( + [ + (str(key2), Util.variant_from_dbus(arr2)) + for key2, arr2 in arr1.items() + ] + ), + ) + for key1, arr1 in val.items() + ] + ) + return GLib.Variant("a{sa{sv}}", c) raise Exception("Unsupported type for value '%s'" % (repr(val))) + ############################################################################### -IFACE_DBUS = 'org.freedesktop.DBus' -IFACE_OBJECT_MANAGER = 'org.freedesktop.DBus.ObjectManager' -IFACE_CONNECTION = 'org.freedesktop.NetworkManager.Settings.Connection' -IFACE_DEVICE = 'org.freedesktop.NetworkManager.Device' -IFACE_WIFI = 'org.freedesktop.NetworkManager.Device.Wireless' -IFACE_TEST = 'org.freedesktop.NetworkManager.LibnmGlibTest' -IFACE_NM = 'org.freedesktop.NetworkManager' -IFACE_SETTINGS = 'org.freedesktop.NetworkManager.Settings' -IFACE_AGENT_MANAGER = 'org.freedesktop.NetworkManager.AgentManager' -IFACE_AGENT = 'org.freedesktop.NetworkManager.SecretAgent' -IFACE_WIRED = 'org.freedesktop.NetworkManager.Device.Wired' -IFACE_VLAN = 'org.freedesktop.NetworkManager.Device.Vlan' -IFACE_WIFI_AP = 'org.freedesktop.NetworkManager.AccessPoint' -IFACE_ACTIVE_CONNECTION = 'org.freedesktop.NetworkManager.Connection.Active' -IFACE_VPN_CONNECTION = 'org.freedesktop.NetworkManager.VPN.Connection' -IFACE_DNS_MANAGER = 'org.freedesktop.NetworkManager.DnsManager' -IFACE_IP4_CONFIG = 'org.freedesktop.NetworkManager.IP4Config' -IFACE_IP6_CONFIG = 'org.freedesktop.NetworkManager.IP6Config' -IFACE_DHCP4_CONFIG = 'org.freedesktop.NetworkManager.DHCP4Config' -IFACE_DHCP6_CONFIG = 'org.freedesktop.NetworkManager.DHCP6Config' +IFACE_DBUS = "org.freedesktop.DBus" +IFACE_OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager" +IFACE_CONNECTION = "org.freedesktop.NetworkManager.Settings.Connection" +IFACE_DEVICE = "org.freedesktop.NetworkManager.Device" +IFACE_WIFI = "org.freedesktop.NetworkManager.Device.Wireless" +IFACE_TEST = "org.freedesktop.NetworkManager.LibnmGlibTest" +IFACE_NM = "org.freedesktop.NetworkManager" +IFACE_SETTINGS = "org.freedesktop.NetworkManager.Settings" +IFACE_AGENT_MANAGER = "org.freedesktop.NetworkManager.AgentManager" +IFACE_AGENT = "org.freedesktop.NetworkManager.SecretAgent" +IFACE_WIRED = "org.freedesktop.NetworkManager.Device.Wired" +IFACE_VLAN = "org.freedesktop.NetworkManager.Device.Vlan" +IFACE_WIFI_AP = "org.freedesktop.NetworkManager.AccessPoint" +IFACE_ACTIVE_CONNECTION = "org.freedesktop.NetworkManager.Connection.Active" +IFACE_VPN_CONNECTION = "org.freedesktop.NetworkManager.VPN.Connection" +IFACE_DNS_MANAGER = "org.freedesktop.NetworkManager.DnsManager" +IFACE_IP4_CONFIG = "org.freedesktop.NetworkManager.IP4Config" +IFACE_IP6_CONFIG = "org.freedesktop.NetworkManager.IP6Config" +IFACE_DHCP4_CONFIG = "org.freedesktop.NetworkManager.DHCP4Config" +IFACE_DHCP6_CONFIG = "org.freedesktop.NetworkManager.DHCP6Config" ############################################################################### -class BusErr: +class BusErr: class UnknownInterfaceException(dbus.DBusException): - _dbus_error_name = IFACE_DBUS + '.UnknownInterface' + _dbus_error_name = IFACE_DBUS + ".UnknownInterface" class UnknownPropertyException(dbus.DBusException): - _dbus_error_name = IFACE_DBUS + '.UnknownProperty' + _dbus_error_name = IFACE_DBUS + ".UnknownProperty" class InvalidPropertyException(dbus.DBusException): - _dbus_error_name = IFACE_CONNECTION + '.InvalidProperty' + _dbus_error_name = IFACE_CONNECTION + ".InvalidProperty" class MissingPropertyException(dbus.DBusException): - _dbus_error_name = IFACE_CONNECTION + '.MissingProperty' + _dbus_error_name = IFACE_CONNECTION + ".MissingProperty" class InvalidSettingException(dbus.DBusException): - _dbus_error_name = IFACE_CONNECTION + '.InvalidSetting' + _dbus_error_name = IFACE_CONNECTION + ".InvalidSetting" class MissingSettingException(dbus.DBusException): - _dbus_error_name = IFACE_CONNECTION + '.MissingSetting' + _dbus_error_name = IFACE_CONNECTION + ".MissingSetting" class NotSoftwareException(dbus.DBusException): - _dbus_error_name = IFACE_DEVICE + '.NotSoftware' + _dbus_error_name = IFACE_DEVICE + ".NotSoftware" class ApNotFoundException(dbus.DBusException): - _dbus_error_name = IFACE_WIFI + '.AccessPointNotFound' + _dbus_error_name = IFACE_WIFI + ".AccessPointNotFound" class PermissionDeniedException(dbus.DBusException): - _dbus_error_name = IFACE_NM + '.PermissionDenied' + _dbus_error_name = IFACE_NM + ".PermissionDenied" class UnknownDeviceException(dbus.DBusException): - _dbus_error_name = IFACE_NM + '.UnknownDevice' + _dbus_error_name = IFACE_NM + ".UnknownDevice" class UnknownConnectionException(dbus.DBusException): - _dbus_error_name = IFACE_NM + '.UnknownConnection' + _dbus_error_name = IFACE_NM + ".UnknownConnection" class InvalidHostnameException(dbus.DBusException): - _dbus_error_name = IFACE_SETTINGS + '.InvalidHostname' + _dbus_error_name = IFACE_SETTINGS + ".InvalidHostname" class NoSecretsException(dbus.DBusException): - _dbus_error_name = IFACE_AGENT_MANAGER + '.NoSecrets' + _dbus_error_name = IFACE_AGENT_MANAGER + ".NoSecrets" class UserCanceledException(dbus.DBusException): - _dbus_error_name = IFACE_AGENT_MANAGER + '.UserCanceled' + _dbus_error_name = IFACE_AGENT_MANAGER + ".UserCanceled" @staticmethod def from_nmerror(e): @@ -412,34 +465,43 @@ class BusErr: raise e2 raise e + ############################################################################### -class NmUtil: +class NmUtil: @staticmethod - def con_hash_to_connection(con_hash, do_verify = False, do_normalize = False): + def con_hash_to_connection(con_hash, do_verify=False, do_normalize=False): x_con = [] for v_setting_name, v_setting in list(con_hash.items()): if isinstance(v_setting_name, (dbus.String, str)): v_setting_name = str(v_setting_name) else: - raise Exception("Expected string dict, but got '%s' key" % (v_setting_name)) + raise Exception( + "Expected string dict, but got '%s' key" % (v_setting_name) + ) x_setting = [] for v_property_name, v_value in list(v_setting.items()): if isinstance(v_property_name, (dbus.String, str)): v_property_name = str(v_property_name) else: - raise Exception("Expected string dict, but got '%s' subkey under %s (%s)" % (v_property_name, v_setting_name, repr(con_hash))) + raise Exception( + "Expected string dict, but got '%s' subkey under %s (%s)" + % (v_property_name, v_setting_name, repr(con_hash)) + ) try: v = Util.variant_from_dbus(v_value) except Exception as e: - raise Exception("Unsupported value %s.%s = %s (%s)" % (v_setting_name, v_property_name, v_value, str(e))) + raise Exception( + "Unsupported value %s.%s = %s (%s)" + % (v_setting_name, v_property_name, v_value, str(e)) + ) x_setting.append((v_property_name, v)) x_con.append((v_setting_name, collections.OrderedDict(x_setting))) - x_con = GLib.Variant('a{sa{sv}}', collections.OrderedDict(x_con)) + x_con = GLib.Variant("a{sa{sv}}", collections.OrderedDict(x_con)) assert GLib.Variant.equal(x_con, Util.variant_from_dbus(con_hash)) @@ -463,30 +525,40 @@ class NmUtil: return con @staticmethod - def con_hash_verify(con_hash, do_verify_strict = True): + def con_hash_verify(con_hash, do_verify_strict=True): if NM.SETTING_CONNECTION_SETTING_NAME not in con_hash: - raise BusErr.MissingSettingException('connection: setting is required') + raise BusErr.MissingSettingException("connection: setting is required") s_con = con_hash[NM.SETTING_CONNECTION_SETTING_NAME] if NM.SETTING_CONNECTION_TYPE not in s_con: - raise BusErr.MissingPropertyException('connection.type: property is required') + raise BusErr.MissingPropertyException( + "connection.type: property is required" + ) if NM.SETTING_CONNECTION_UUID not in s_con: - raise BusErr.MissingPropertyException('connection.uuid: property is required') + raise BusErr.MissingPropertyException( + "connection.uuid: property is required" + ) if NM.SETTING_CONNECTION_ID not in s_con: - raise BusErr.MissingPropertyException('connection.id: property is required') + raise BusErr.MissingPropertyException("connection.id: property is required") if not do_verify_strict: - return; + return t = s_con[NM.SETTING_CONNECTION_TYPE] - if t not in [ NM.SETTING_GSM_SETTING_NAME, - NM.SETTING_VLAN_SETTING_NAME, - NM.SETTING_VPN_SETTING_NAME, - NM.SETTING_WIMAX_SETTING_NAME, - NM.SETTING_WIRED_SETTING_NAME, - NM.SETTING_WIRELESS_SETTING_NAME ]: - raise BusErr.InvalidPropertyException('connection.type: unsupported connection type "%s"' % (t)) + if t not in [ + NM.SETTING_GSM_SETTING_NAME, + NM.SETTING_VLAN_SETTING_NAME, + NM.SETTING_VPN_SETTING_NAME, + NM.SETTING_WIMAX_SETTING_NAME, + NM.SETTING_WIRED_SETTING_NAME, + NM.SETTING_WIRELESS_SETTING_NAME, + ]: + raise BusErr.InvalidPropertyException( + 'connection.type: unsupported connection type "%s"' % (t) + ) try: - con_nm = NmUtil.con_hash_to_connection(con_hash, do_verify = True, do_normalize = True) + con_nm = NmUtil.con_hash_to_connection( + con_hash, do_verify=True, do_normalize=True + ) except Exception as e: BusErr.raise_nmerror(e) @@ -514,14 +586,18 @@ class NmUtil: return s_con[NM.SETTING_CONNECTION_TYPE] return None + ############################################################################### + class ExportedObj(dbus.service.Object): - DBusInterface = collections.namedtuple('DBusInterface', ['dbus_iface', 'props', 'legacy_prop_changed_func']) + DBusInterface = collections.namedtuple( + "DBusInterface", ["dbus_iface", "props", "legacy_prop_changed_func"] + ) @staticmethod - def create_path(klass, path_prefix = None): + def create_path(klass, path_prefix=None): if path_prefix is None: path_prefix = klass.path_prefix path = path_prefix + str(klass.path_counter_next) @@ -530,8 +606,10 @@ class ExportedObj(dbus.service.Object): @staticmethod def to_path_array(src): - return dbus.Array([ExportedObj.to_path(o) for o in src] if src else [], - signature=dbus.Signature('o')) + return dbus.Array( + [ExportedObj.to_path(o) for o in src] if src else [], + signature=dbus.Signature("o"), + ) @staticmethod def to_path(src): @@ -539,7 +617,7 @@ class ExportedObj(dbus.service.Object): return dbus.ObjectPath(src.path) return dbus.ObjectPath("/") - def __init__(self, object_path, ident = None): + def __init__(self, object_path, ident=None): dbus.service.Object.__init__(self) self._dbus_ifaces = {} @@ -564,15 +642,17 @@ class ExportedObj(dbus.service.Object): gl.object_manager.remove_object(self) self.remove_from_connection() - def dbus_interface_add(self, dbus_iface, props, legacy_prop_changed_func = None): - self._dbus_ifaces[dbus_iface] = ExportedObj.DBusInterface(dbus_iface, props, legacy_prop_changed_func) + def dbus_interface_add(self, dbus_iface, props, legacy_prop_changed_func=None): + self._dbus_ifaces[dbus_iface] = ExportedObj.DBusInterface( + dbus_iface, props, legacy_prop_changed_func + ) def _dbus_interface_get(self, dbus_iface): if dbus_iface not in self._dbus_ifaces: raise BusErr.UnknownInterfaceException() return self._dbus_ifaces[dbus_iface] - def _dbus_interface_get_property(self, dbus_interface, propname = None): + def _dbus_interface_get_property(self, dbus_interface, propname=None): props = dbus_interface.props if propname is None: return props @@ -580,33 +660,53 @@ class ExportedObj(dbus.service.Object): raise BusErr.UnknownPropertyException() return props[propname] - def _dbus_property_get(self, dbus_iface, propname = None): - return self._dbus_interface_get_property(self._dbus_interface_get(dbus_iface), - propname) - - def _dbus_property_set(self, dbus_iface, propname, value, allow_detect_dbus_iface = False, dry_run = False, force_update = False): + def _dbus_property_get(self, dbus_iface, propname=None): + return self._dbus_interface_get_property( + self._dbus_interface_get(dbus_iface), propname + ) + + def _dbus_property_set( + self, + dbus_iface, + propname, + value, + allow_detect_dbus_iface=False, + dry_run=False, + force_update=False, + ): if allow_detect_dbus_iface and not dbus_iface: props = None for p, dbus_interface in self._dbus_ifaces.items(): if propname in dbus_interface.props: if props is not None: - raise TestError("Cannot uniquely find the property '%s' on object '%s'" % (propname, self.path)) + raise TestError( + "Cannot uniquely find the property '%s' on object '%s'" + % (propname, self.path) + ) props = dbus_interface.props dbus_iface = p if props is None: - raise TestError("Cannot find the property '%s' on object '%s'" % (propname, self.path)) + raise TestError( + "Cannot find the property '%s' on object '%s'" + % (propname, self.path) + ) else: try: dbus_interface = self._dbus_interface_get(dbus_iface) props = self._dbus_interface_get_property(dbus_interface) except: if dry_run: - raise TestError("No interface '%s' on '%s'" % (dbus_iface, self.path)) + raise TestError( + "No interface '%s' on '%s'" % (dbus_iface, self.path) + ) raise if dry_run: if propname not in props: - raise TestError("No property '%s' on '%s' on '%s'" % (propname, dbus_iface, self.path)) + raise TestError( + "No property '%s' on '%s' on '%s'" + % (propname, dbus_iface, self.path) + ) permission_granted = False @@ -619,7 +719,10 @@ class ExportedObj(dbus.service.Object): permission_granted = True if not permission_granted: - raise TestError("Cannot set property '%s' on '%s' on '%s' via D-Bus" % (propname, dbus_iface, self.path)) + raise TestError( + "Cannot set property '%s' on '%s' on '%s' via D-Bus" + % (propname, dbus_iface, self.path) + ) return @@ -636,7 +739,7 @@ class ExportedObj(dbus.service.Object): dbus_interface = self._dbus_interface_get(dbus_iface) prop = self._dbus_interface_get_property(dbus_interface, propname) if propname is not None: - prop = { propname: prop } + prop = {propname: prop} ExportedObj.PropertiesChanged(self, dbus_iface, prop, []) # the legacy_prop_changed_func signal is a legacy signal that got obsoleted by the standard @@ -648,15 +751,19 @@ class ExportedObj(dbus.service.Object): if dbus_interface.legacy_prop_changed_func is not None: dbus_interface.legacy_prop_changed_func(self, prop) - @dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as') + @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as") def PropertiesChanged(self, iface, changed, invalidated): pass - @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}') + @dbus.service.method( + dbus_interface=dbus.PROPERTIES_IFACE, in_signature="s", out_signature="a{sv}" + ) def GetAll(self, dbus_iface): return self._dbus_property_get(dbus_iface) - @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v') + @dbus.service.method( + dbus_interface=dbus.PROPERTIES_IFACE, in_signature="ss", out_signature="v" + ) def Get(self, dbus_iface, name): return self._dbus_property_get(dbus_iface, name) @@ -666,31 +773,33 @@ class ExportedObj(dbus.service.Object): my_ifaces[iface] = self._dbus_ifaces[iface].props return my_ifaces + ############################################################################### -PRP_DEVICE_UDI = "Udi" -PRP_DEVICE_IFACE = "Interface" -PRP_DEVICE_DRIVER = "Driver" -PRP_DEVICE_STATE = "State" -PRP_DEVICE_STATE_REASON = "StateReason" -PRP_DEVICE_ACTIVE_CONNECTION = "ActiveConnection" -PRP_DEVICE_IP4_CONFIG = "Ip4Config" -PRP_DEVICE_IP6_CONFIG = "Ip6Config" -PRP_DEVICE_DHCP4_CONFIG = "Dhcp4Config" -PRP_DEVICE_DHCP6_CONFIG = "Dhcp6Config" -PRP_DEVICE_MANAGED = "Managed" -PRP_DEVICE_AUTOCONNECT = "Autoconnect" -PRP_DEVICE_DEVICE_TYPE = "DeviceType" +PRP_DEVICE_UDI = "Udi" +PRP_DEVICE_IFACE = "Interface" +PRP_DEVICE_DRIVER = "Driver" +PRP_DEVICE_STATE = "State" +PRP_DEVICE_STATE_REASON = "StateReason" +PRP_DEVICE_ACTIVE_CONNECTION = "ActiveConnection" +PRP_DEVICE_IP4_CONFIG = "Ip4Config" +PRP_DEVICE_IP6_CONFIG = "Ip6Config" +PRP_DEVICE_DHCP4_CONFIG = "Dhcp4Config" +PRP_DEVICE_DHCP6_CONFIG = "Dhcp6Config" +PRP_DEVICE_MANAGED = "Managed" +PRP_DEVICE_AUTOCONNECT = "Autoconnect" +PRP_DEVICE_DEVICE_TYPE = "DeviceType" PRP_DEVICE_AVAILABLE_CONNECTIONS = "AvailableConnections" -PRP_DEVICE_LLDP_NEIGHBORS = "LldpNeighbors" -PRP_DEVICE_INTERFACE_FLAGS = "InterfaceFlags" +PRP_DEVICE_LLDP_NEIGHBORS = "LldpNeighbors" +PRP_DEVICE_INTERFACE_FLAGS = "InterfaceFlags" + class Device(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/Devices/" - def __init__(self, iface, devtype, ident = None): + def __init__(self, iface, devtype, ident=None): if ident is None: ident = iface @@ -705,145 +814,211 @@ class Device(ExportedObj): self.prp_state = NM.DeviceState.UNAVAILABLE props = { - PRP_DEVICE_UDI: "/sys/devices/virtual/%s" % (iface), - PRP_DEVICE_IFACE: iface, - PRP_DEVICE_DRIVER: "virtual", - PRP_DEVICE_STATE: dbus.UInt32(self.prp_state), - PRP_DEVICE_STATE_REASON: dbus.Struct((dbus.UInt32(self.prp_state), dbus.UInt32(NM.DeviceStateReason.NONE))), - PRP_DEVICE_ACTIVE_CONNECTION: ExportedObj.to_path(None), - PRP_DEVICE_IP4_CONFIG: ExportedObj.to_path(self.ip4_config), - PRP_DEVICE_IP6_CONFIG: ExportedObj.to_path(self.ip6_config), - PRP_DEVICE_DHCP4_CONFIG: ExportedObj.to_path(self.dhcp4_config), - PRP_DEVICE_DHCP6_CONFIG: ExportedObj.to_path(self.dhcp6_config), - PRP_DEVICE_MANAGED: True, - PRP_DEVICE_AUTOCONNECT: True, - PRP_DEVICE_DEVICE_TYPE: dbus.UInt32(devtype), + PRP_DEVICE_UDI: "/sys/devices/virtual/%s" % (iface), + PRP_DEVICE_IFACE: iface, + PRP_DEVICE_DRIVER: "virtual", + PRP_DEVICE_STATE: dbus.UInt32(self.prp_state), + PRP_DEVICE_STATE_REASON: dbus.Struct( + (dbus.UInt32(self.prp_state), dbus.UInt32(NM.DeviceStateReason.NONE)) + ), + PRP_DEVICE_ACTIVE_CONNECTION: ExportedObj.to_path(None), + PRP_DEVICE_IP4_CONFIG: ExportedObj.to_path(self.ip4_config), + PRP_DEVICE_IP6_CONFIG: ExportedObj.to_path(self.ip6_config), + PRP_DEVICE_DHCP4_CONFIG: ExportedObj.to_path(self.dhcp4_config), + PRP_DEVICE_DHCP6_CONFIG: ExportedObj.to_path(self.dhcp6_config), + PRP_DEVICE_MANAGED: True, + PRP_DEVICE_AUTOCONNECT: True, + PRP_DEVICE_DEVICE_TYPE: dbus.UInt32(devtype), PRP_DEVICE_AVAILABLE_CONNECTIONS: ExportedObj.to_path_array([]), - PRP_DEVICE_INTERFACE_FLAGS: dbus.UInt32(3), # up,lower-up - PRP_DEVICE_LLDP_NEIGHBORS: dbus.Array([ - dbus.Dictionary({ - 'chassis-id-type': dbus.UInt32(6), - 'chassis-id': dbus.String('00:11:22:33:44:00'), - 'port-id-type': dbus.UInt32(7), - 'port-id': dbus.String('Uplink port'), - 'port-description': dbus.String('GigabitEthernet #1'), - 'system-name': dbus.String('test1.example.com'), - 'system-description': dbus.String('Test system #1'), - 'system-capabilities': dbus.UInt32(20), - 'destination': dbus.String('nearest-bridge'), - }), - dbus.Dictionary({ - 'chassis-id-type': dbus.UInt32(2), - 'chassis-id': dbus.String('chassis1'), - 'port-id-type': dbus.UInt32(3), - 'port-id': dbus.String('44:44:44:44:44:44'), - 'port-description': dbus.String('GigabitEthernet #2'), - 'system-name': dbus.String('test2.example.com'), - 'system-description': dbus.String('Test system #2'), - 'system-capabilities': dbus.UInt32(2047), - 'destination': dbus.String('nearest-non-tpmr-bridge'), - 'ieee-802-1-vlans': dbus.Array([ - dbus.Dictionary({ - 'vid': dbus.UInt32(80), - 'name': dbus.String('vlan80'), - }, signature = 'sv'), - dbus.Dictionary({ - 'vid': dbus.UInt32(4000), - 'name': dbus.String('My VLAN'), - }, signature = 'sv'), - ]), - 'ieee-802-1-ppvids': dbus.Array([ - dbus.Dictionary({ - 'ppvid': dbus.UInt32(4), - 'flags': dbus.UInt32(0x12), - }, signature = 'sv'), - dbus.Dictionary({ - 'ppvid': dbus.UInt32(10), - 'flags': dbus.UInt32(0x31), - }, signature = 'sv'), - ]), - - }), - dbus.Dictionary({ - 'chassis-id-type': dbus.UInt32(6), - 'chassis-id': dbus.String('00:11:22:33:44:22'), - 'port-id-type': dbus.UInt32(1), - 'port-id': dbus.String('port1'), - 'port-description': dbus.String('GigabitEthernet #3'), - 'system-name': dbus.String('test3.example.com'), - 'system-description': dbus.String('Test system #3'), - 'system-capabilities': dbus.UInt32(40), - 'destination': dbus.String('nearest-customer-bridge'), - 'management-addresses': dbus.Array([ - dbus.Dictionary({ - 'address-subtype': dbus.UInt32(1), - 'address': dbus.ByteArray(b'\xc0\xa8\x01\x01'), - 'interface-number': dbus.UInt32(4), - 'interface-number-subtype': dbus.UInt32(3), - 'object-id': dbus.ByteArray(b'\x01\x02\x03\x04') - }, signature = 'sv'), - dbus.Dictionary({ - 'address-subtype': dbus.UInt32(2), - 'address': dbus.ByteArray(b'\xfd\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12\x34\x56\x78'), - 'interface-number': dbus.UInt32(1), - 'interface-number-subtype': dbus.UInt32(2), - }, signature = 'sv'), - ]), - 'ieee-802-3-mac-phy-conf': dbus.Dictionary({ - 'autoneg': dbus.UInt32(3), - 'pmd-autoneg-cap': dbus.UInt32(0xfe), - 'operational-mau-type': dbus.UInt32(5), - }, signature = 'sv'), - 'ieee-802-3-power-via-mdi': dbus.Dictionary({ - 'mdi-power-support': dbus.UInt32(7), - 'pse-power-pair': dbus.UInt32(6), - 'power-class': dbus.UInt32(1), - }, signature = 'sv'), - }) - ], 'a{sv}') + PRP_DEVICE_INTERFACE_FLAGS: dbus.UInt32(3), # up,lower-up + PRP_DEVICE_LLDP_NEIGHBORS: dbus.Array( + [ + dbus.Dictionary( + { + "chassis-id-type": dbus.UInt32(6), + "chassis-id": dbus.String("00:11:22:33:44:00"), + "port-id-type": dbus.UInt32(7), + "port-id": dbus.String("Uplink port"), + "port-description": dbus.String("GigabitEthernet #1"), + "system-name": dbus.String("test1.example.com"), + "system-description": dbus.String("Test system #1"), + "system-capabilities": dbus.UInt32(20), + "destination": dbus.String("nearest-bridge"), + } + ), + dbus.Dictionary( + { + "chassis-id-type": dbus.UInt32(2), + "chassis-id": dbus.String("chassis1"), + "port-id-type": dbus.UInt32(3), + "port-id": dbus.String("44:44:44:44:44:44"), + "port-description": dbus.String("GigabitEthernet #2"), + "system-name": dbus.String("test2.example.com"), + "system-description": dbus.String("Test system #2"), + "system-capabilities": dbus.UInt32(2047), + "destination": dbus.String("nearest-non-tpmr-bridge"), + "ieee-802-1-vlans": dbus.Array( + [ + dbus.Dictionary( + { + "vid": dbus.UInt32(80), + "name": dbus.String("vlan80"), + }, + signature="sv", + ), + dbus.Dictionary( + { + "vid": dbus.UInt32(4000), + "name": dbus.String("My VLAN"), + }, + signature="sv", + ), + ] + ), + "ieee-802-1-ppvids": dbus.Array( + [ + dbus.Dictionary( + { + "ppvid": dbus.UInt32(4), + "flags": dbus.UInt32(0x12), + }, + signature="sv", + ), + dbus.Dictionary( + { + "ppvid": dbus.UInt32(10), + "flags": dbus.UInt32(0x31), + }, + signature="sv", + ), + ] + ), + } + ), + dbus.Dictionary( + { + "chassis-id-type": dbus.UInt32(6), + "chassis-id": dbus.String("00:11:22:33:44:22"), + "port-id-type": dbus.UInt32(1), + "port-id": dbus.String("port1"), + "port-description": dbus.String("GigabitEthernet #3"), + "system-name": dbus.String("test3.example.com"), + "system-description": dbus.String("Test system #3"), + "system-capabilities": dbus.UInt32(40), + "destination": dbus.String("nearest-customer-bridge"), + "management-addresses": dbus.Array( + [ + dbus.Dictionary( + { + "address-subtype": dbus.UInt32(1), + "address": dbus.ByteArray( + b"\xc0\xa8\x01\x01" + ), + "interface-number": dbus.UInt32(4), + "interface-number-subtype": dbus.UInt32(3), + "object-id": dbus.ByteArray( + b"\x01\x02\x03\x04" + ), + }, + signature="sv", + ), + dbus.Dictionary( + { + "address-subtype": dbus.UInt32(2), + "address": dbus.ByteArray( + b"\xfd\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12\x34\x56\x78" + ), + "interface-number": dbus.UInt32(1), + "interface-number-subtype": dbus.UInt32(2), + }, + signature="sv", + ), + ] + ), + "ieee-802-3-mac-phy-conf": dbus.Dictionary( + { + "autoneg": dbus.UInt32(3), + "pmd-autoneg-cap": dbus.UInt32(0xFE), + "operational-mau-type": dbus.UInt32(5), + }, + signature="sv", + ), + "ieee-802-3-power-via-mdi": dbus.Dictionary( + { + "mdi-power-support": dbus.UInt32(7), + "pse-power-pair": dbus.UInt32(6), + "power-class": dbus.UInt32(1), + }, + signature="sv", + ), + } + ), + ], + "a{sv}", + ), } self.dbus_interface_add(IFACE_DEVICE, props, Device.PropertiesChanged) def start(self): self.ip4_config = IP4Config() - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_IP4_CONFIG, ExportedObj.to_path(self.ip4_config)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_IP4_CONFIG, ExportedObj.to_path(self.ip4_config) + ) self.ip6_config = IP6Config() - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_IP6_CONFIG, ExportedObj.to_path(self.ip6_config)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_IP6_CONFIG, ExportedObj.to_path(self.ip6_config) + ) self.dhcp4_config = Dhcp4Config() - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_DHCP4_CONFIG, ExportedObj.to_path(self.dhcp4_config)) + self._dbus_property_set( + IFACE_DEVICE, + PRP_DEVICE_DHCP4_CONFIG, + ExportedObj.to_path(self.dhcp4_config), + ) self.dhcp6_config = Dhcp6Config() - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_DHCP6_CONFIG, ExportedObj.to_path(self.dhcp6_config)) + self._dbus_property_set( + IFACE_DEVICE, + PRP_DEVICE_DHCP6_CONFIG, + ExportedObj.to_path(self.dhcp6_config), + ) def stop(self): - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_IP4_CONFIG, ExportedObj.to_path(None)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_IP4_CONFIG, ExportedObj.to_path(None) + ) if self.ip4_config is not None: self.ip4_config.unexport() self.ip4_config = None - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_IP6_CONFIG, ExportedObj.to_path(None)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_IP6_CONFIG, ExportedObj.to_path(None) + ) if self.ip6_config is not None: self.ip6_config.unexport() self.ip6_config = None - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_DHCP4_CONFIG, ExportedObj.to_path(None)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_DHCP4_CONFIG, ExportedObj.to_path(None) + ) if self.dhcp4_config is not None: self.dhcp4_config.unexport() self.dhcp4_config = None - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_DHCP6_CONFIG, ExportedObj.to_path(None)) + self._dbus_property_set( + IFACE_DEVICE, PRP_DEVICE_DHCP6_CONFIG, ExportedObj.to_path(None) + ) if self.dhcp6_config is not None: self.dhcp6_config.unexport() self.dhcp6_config = None - @dbus.service.method(dbus_interface=IFACE_DEVICE, in_signature='', out_signature='') + @dbus.service.method(dbus_interface=IFACE_DEVICE, in_signature="", out_signature="") def Disconnect(self): pass - @dbus.service.method(dbus_interface=IFACE_DEVICE, in_signature='', out_signature='') + @dbus.service.method(dbus_interface=IFACE_DEVICE, in_signature="", out_signature="") def Delete(self): # We don't currently support any software device types, so... raise BusErr.NotSoftwareException() pass - @dbus.service.signal(IFACE_DEVICE, signature='a{sv}') + @dbus.service.signal(IFACE_DEVICE, signature="a{sv}") def PropertiesChanged(self, changed): pass @@ -862,88 +1037,109 @@ class Device(ExportedObj): return False def available_connections_get(self): - return [c for c in gl.settings.get_connections() if self.connection_is_available(c)] + return [ + c for c in gl.settings.get_connections() if self.connection_is_available(c) + ] def available_connections_update(self): - self._dbus_property_set(IFACE_DEVICE, PRP_DEVICE_AVAILABLE_CONNECTIONS, - ExportedObj.to_path_array(self.available_connections_get())) + self._dbus_property_set( + IFACE_DEVICE, + PRP_DEVICE_AVAILABLE_CONNECTIONS, + ExportedObj.to_path_array(self.available_connections_get()), + ) + ############################################################################### -PRP_WIRED_HW_ADDRESS = "HwAddress" -PRP_WIRED_PERM_HW_ADDRESS = "PermHwAddress" -PRP_WIRED_SPEED = "Speed" -PRP_WIRED_CARRIER = "Carrier" +PRP_WIRED_HW_ADDRESS = "HwAddress" +PRP_WIRED_PERM_HW_ADDRESS = "PermHwAddress" +PRP_WIRED_SPEED = "Speed" +PRP_WIRED_CARRIER = "Carrier" PRP_WIRED_S390_SUBCHANNELS = "S390Subchannels" + class WiredDevice(Device): - def __init__(self, iface, mac = None, subchannels = None, ident = None): + def __init__(self, iface, mac=None, subchannels=None, ident=None): Device.__init__(self, iface, NM.DeviceType.ETHERNET, ident) if mac is None: mac = Util.random_mac(self.ident) if subchannels is None: - subchannels = dbus.Array(signature = 's') + subchannels = dbus.Array(signature="s") props = { - PRP_WIRED_HW_ADDRESS: mac, - PRP_WIRED_PERM_HW_ADDRESS: mac, - PRP_WIRED_SPEED: dbus.UInt32(100), - PRP_WIRED_CARRIER: False, + PRP_WIRED_HW_ADDRESS: mac, + PRP_WIRED_PERM_HW_ADDRESS: mac, + PRP_WIRED_SPEED: dbus.UInt32(100), + PRP_WIRED_CARRIER: False, PRP_WIRED_S390_SUBCHANNELS: subchannels, } self.dbus_interface_add(IFACE_WIRED, props, WiredDevice.PropertiesChanged) - @dbus.service.signal(IFACE_WIRED, signature='a{sv}') + @dbus.service.signal(IFACE_WIRED, signature="a{sv}") def PropertiesChanged(self, changed): pass + ############################################################################### PRP_VLAN_HW_ADDRESS = "HwAddress" -PRP_VLAN_CARRIER = "Carrier" -PRP_VLAN_VLAN_ID = "VlanId" +PRP_VLAN_CARRIER = "Carrier" +PRP_VLAN_VLAN_ID = "VlanId" + class VlanDevice(Device): - def __init__(self, iface, ident = None): + def __init__(self, iface, ident=None): Device.__init__(self, iface, NM.DeviceType.VLAN, ident) props = { PRP_VLAN_HW_ADDRESS: Util.random_mac(self.ident), - PRP_VLAN_CARRIER: False, - PRP_VLAN_VLAN_ID: dbus.UInt32(1), + PRP_VLAN_CARRIER: False, + PRP_VLAN_VLAN_ID: dbus.UInt32(1), } self.dbus_interface_add(IFACE_VLAN, props, VlanDevice.PropertiesChanged) - @dbus.service.signal(IFACE_VLAN, signature='a{sv}') + @dbus.service.signal(IFACE_VLAN, signature="a{sv}") def PropertiesChanged(self, changed): pass + ############################################################################### -PRP_WIFI_AP_FLAGS = "Flags" -PRP_WIFI_AP_WPA_FLAGS = "WpaFlags" -PRP_WIFI_AP_RSN_FLAGS = "RsnFlags" -PRP_WIFI_AP_SSID = "Ssid" -PRP_WIFI_AP_FREQUENCY = "Frequency" -PRP_WIFI_AP_HW_ADDRESS = "HwAddress" -PRP_WIFI_AP_MODE = "Mode" +PRP_WIFI_AP_FLAGS = "Flags" +PRP_WIFI_AP_WPA_FLAGS = "WpaFlags" +PRP_WIFI_AP_RSN_FLAGS = "RsnFlags" +PRP_WIFI_AP_SSID = "Ssid" +PRP_WIFI_AP_FREQUENCY = "Frequency" +PRP_WIFI_AP_HW_ADDRESS = "HwAddress" +PRP_WIFI_AP_MODE = "Mode" PRP_WIFI_AP_MAX_BITRATE = "MaxBitrate" -PRP_WIFI_AP_STRENGTH = "Strength" -PRP_WIFI_AP_LAST_SEEN = "LastSeen" +PRP_WIFI_AP_STRENGTH = "Strength" +PRP_WIFI_AP_LAST_SEEN = "LastSeen" + class WifiAp(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/AccessPoint/" - def __init__(self, ssid, bssid = None, flags = None, wpaf = None, rsnf = None, freq = None, strength = None, ident = None): + def __init__( + self, + ssid, + bssid=None, + flags=None, + wpaf=None, + rsnf=None, + freq=None, + strength=None, + ident=None, + ): ExportedObj.__init__(self, ExportedObj.create_path(WifiAp), ident) - NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags') + NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags") if flags is None: flags = 0x1 if wpaf is None: @@ -970,24 +1166,25 @@ class WifiAp(ExportedObj): self.ssid = ssid props = { - PRP_WIFI_AP_FLAGS: dbus.UInt32(flags), - PRP_WIFI_AP_WPA_FLAGS: dbus.UInt32(wpaf), - PRP_WIFI_AP_RSN_FLAGS: dbus.UInt32(rsnf), - PRP_WIFI_AP_SSID: dbus.ByteArray(self.ssid.encode('utf-8')), - PRP_WIFI_AP_FREQUENCY: dbus.UInt32(freq), - PRP_WIFI_AP_HW_ADDRESS: bssid, - PRP_WIFI_AP_MODE: dbus.UInt32(getattr(NM,'80211Mode').INFRA), + PRP_WIFI_AP_FLAGS: dbus.UInt32(flags), + PRP_WIFI_AP_WPA_FLAGS: dbus.UInt32(wpaf), + PRP_WIFI_AP_RSN_FLAGS: dbus.UInt32(rsnf), + PRP_WIFI_AP_SSID: dbus.ByteArray(self.ssid.encode("utf-8")), + PRP_WIFI_AP_FREQUENCY: dbus.UInt32(freq), + PRP_WIFI_AP_HW_ADDRESS: bssid, + PRP_WIFI_AP_MODE: dbus.UInt32(getattr(NM, "80211Mode").INFRA), PRP_WIFI_AP_MAX_BITRATE: dbus.UInt32(54000), - PRP_WIFI_AP_STRENGTH: dbus.Byte(strength), - PRP_WIFI_AP_LAST_SEEN: dbus.Int32(NM.utils_get_timestamp_msec() / 1000), + PRP_WIFI_AP_STRENGTH: dbus.Byte(strength), + PRP_WIFI_AP_LAST_SEEN: dbus.Int32(NM.utils_get_timestamp_msec() / 1000), } self.dbus_interface_add(IFACE_WIFI_AP, props, WifiAp.PropertiesChanged) - @dbus.service.signal(IFACE_WIFI_AP, signature='a{sv}') + @dbus.service.signal(IFACE_WIFI_AP, signature="a{sv}") def PropertiesChanged(self, changed): pass + ############################################################################### PRP_WIFI_HW_ADDRESS = "HwAddress" @@ -999,8 +1196,9 @@ PRP_WIFI_ACTIVE_ACCESS_POINT = "ActiveAccessPoint" PRP_WIFI_WIRELESS_CAPABILITIES = "WirelessCapabilities" PRP_WIFI_LAST_SCAN = "LastScan" + class WifiDevice(Device): - def __init__(self, iface, mac = None, ident = None): + def __init__(self, iface, mac=None, ident=None): Device.__init__(self, iface, NM.DeviceType.WIFI, ident) if mac is None: @@ -1010,58 +1208,70 @@ class WifiDevice(Device): self.scan_cb_id = None # Use a randomly older timestamp to trigger RequestScan() from the client - ts = max(0, NM.utils_get_timestamp_msec() - Util.random_int(self.path, 20000, 40000)) + ts = max( + 0, NM.utils_get_timestamp_msec() - Util.random_int(self.path, 20000, 40000) + ) props = { - PRP_WIFI_HW_ADDRESS: mac, - PRP_WIFI_PERM_HW_ADDRESS: mac, - PRP_WIFI_MODE: dbus.UInt32(getattr(NM,'80211Mode').INFRA), - PRP_WIFI_BITRATE: dbus.UInt32(21000), + PRP_WIFI_HW_ADDRESS: mac, + PRP_WIFI_PERM_HW_ADDRESS: mac, + PRP_WIFI_MODE: dbus.UInt32(getattr(NM, "80211Mode").INFRA), + PRP_WIFI_BITRATE: dbus.UInt32(21000), PRP_WIFI_WIRELESS_CAPABILITIES: dbus.UInt32(0xFF), - PRP_WIFI_ACCESS_POINTS: ExportedObj.to_path_array(self.aps), - PRP_WIFI_ACTIVE_ACCESS_POINT: ExportedObj.to_path(None), - PRP_WIFI_LAST_SCAN: dbus.Int64(ts), + PRP_WIFI_ACCESS_POINTS: ExportedObj.to_path_array(self.aps), + PRP_WIFI_ACTIVE_ACCESS_POINT: ExportedObj.to_path(None), + PRP_WIFI_LAST_SCAN: dbus.Int64(ts), } self.dbus_interface_add(IFACE_WIFI, props, WifiDevice.PropertiesChanged) - @dbus.service.method(dbus_interface=IFACE_WIFI, in_signature='', out_signature='ao') + @dbus.service.method(dbus_interface=IFACE_WIFI, in_signature="", out_signature="ao") def GetAccessPoints(self): # only include non-hidden APs return ExportedObj.to_path_array([a for a in self.aps if a.ssid]) - @dbus.service.method(dbus_interface=IFACE_WIFI, in_signature='', out_signature='ao') + @dbus.service.method(dbus_interface=IFACE_WIFI, in_signature="", out_signature="ao") def GetAllAccessPoints(self): # include all APs including hidden ones return ExportedObj.to_path_array(self.aps) - @dbus.service.method(dbus_interface=IFACE_WIFI, in_signature='a{sv}', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_WIFI, in_signature="a{sv}", out_signature="" + ) def RequestScan(self, props): self.scan_cb_id = Util.g_source_remove(self.scan_cb_id) + def cb(): ts = NM.utils_get_timestamp_msec() for ap in self.aps: - ap._dbus_property_set(IFACE_WIFI_AP, PRP_WIFI_AP_LAST_SEEN, dbus.Int32(ts / 1000)) + ap._dbus_property_set( + IFACE_WIFI_AP, PRP_WIFI_AP_LAST_SEEN, dbus.Int32(ts / 1000) + ) self._dbus_property_set(IFACE_WIFI, PRP_WIFI_LAST_SCAN, dbus.Int64(ts)) self.scan_cb_id = None return False + self.scan_cb_id = GLib.idle_add(cb) pass - @dbus.service.signal(IFACE_WIFI, signature='o') + @dbus.service.signal(IFACE_WIFI, signature="o") def AccessPointAdded(self, ap_path): pass def add_ap(self, ap): ap.export() self.aps.append(ap) - self._dbus_property_set(IFACE_WIFI, PRP_WIFI_ACCESS_POINTS, ExportedObj.to_path_array(self.aps)) + self._dbus_property_set( + IFACE_WIFI, PRP_WIFI_ACCESS_POINTS, ExportedObj.to_path_array(self.aps) + ) self.AccessPointAdded(ExportedObj.to_path(ap)) return ap def remove_ap(self, ap): self.aps.remove(ap) - self._dbus_property_set(IFACE_WIFI, PRP_WIFI_ACCESS_POINTS, ExportedObj.to_path_array(self.aps)) + self._dbus_property_set( + IFACE_WIFI, PRP_WIFI_ACCESS_POINTS, ExportedObj.to_path_array(self.aps) + ) self.AccessPointRemoved(ExportedObj.to_path(ap)) ap.unexport() @@ -1069,11 +1279,11 @@ class WifiDevice(Device): self.scan_cb_id = Util.g_source_remove(self.scan_cb_id) super(WifiDevice, self).stop() - @dbus.service.signal(IFACE_WIFI, signature='o') + @dbus.service.signal(IFACE_WIFI, signature="o") def AccessPointRemoved(self, ap_path): pass - @dbus.service.signal(IFACE_WIFI, signature='a{sv}') + @dbus.service.signal(IFACE_WIFI, signature="a{sv}") def PropertiesChanged(self, changed): pass @@ -1103,8 +1313,9 @@ PRP_ACTIVE_CONNECTION_DHCP6CONFIG = "Dhcp6Config" PRP_ACTIVE_CONNECTION_VPN = "Vpn" PRP_ACTIVE_CONNECTION_MASTER = "Master" -PRP_VPN_CONNECTION_VPN_STATE = 'VpnState' -PRP_VPN_CONNECTION_BANNER = 'Banner' +PRP_VPN_CONNECTION_VPN_STATE = "VpnState" +PRP_VPN_CONNECTION_BANNER = "Banner" + class ActiveConnection(ExportedObj): @@ -1124,37 +1335,45 @@ class ActiveConnection(ExportedObj): s_con = con_inst.con_hash[NM.SETTING_CONNECTION_SETTING_NAME] props = { - PRP_ACTIVE_CONNECTION_CONNECTION: ExportedObj.to_path(con_inst), + PRP_ACTIVE_CONNECTION_CONNECTION: ExportedObj.to_path(con_inst), PRP_ACTIVE_CONNECTION_SPECIFIC_OBJECT: ExportedObj.to_path(specific_object), - PRP_ACTIVE_CONNECTION_ID: s_con[NM.SETTING_CONNECTION_ID], - PRP_ACTIVE_CONNECTION_UUID: s_con[NM.SETTING_CONNECTION_UUID], - PRP_ACTIVE_CONNECTION_TYPE: s_con[NM.SETTING_CONNECTION_TYPE], - PRP_ACTIVE_CONNECTION_DEVICES: ExportedObj.to_path_array([self.device]), - PRP_ACTIVE_CONNECTION_STATE: dbus.UInt32(NM.ActiveConnectionState.UNKNOWN), - PRP_ACTIVE_CONNECTION_DEFAULT: False, - PRP_ACTIVE_CONNECTION_IP4CONFIG: ExportedObj.to_path(None), - PRP_ACTIVE_CONNECTION_DHCP4CONFIG: ExportedObj.to_path(None), - PRP_ACTIVE_CONNECTION_DEFAULT6: False, - PRP_ACTIVE_CONNECTION_IP6CONFIG: ExportedObj.to_path(None), - PRP_ACTIVE_CONNECTION_DHCP6CONFIG: ExportedObj.to_path(None), - PRP_ACTIVE_CONNECTION_VPN: self.is_vpn, - PRP_ACTIVE_CONNECTION_MASTER: ExportedObj.to_path(None), + PRP_ACTIVE_CONNECTION_ID: s_con[NM.SETTING_CONNECTION_ID], + PRP_ACTIVE_CONNECTION_UUID: s_con[NM.SETTING_CONNECTION_UUID], + PRP_ACTIVE_CONNECTION_TYPE: s_con[NM.SETTING_CONNECTION_TYPE], + PRP_ACTIVE_CONNECTION_DEVICES: ExportedObj.to_path_array([self.device]), + PRP_ACTIVE_CONNECTION_STATE: dbus.UInt32(NM.ActiveConnectionState.UNKNOWN), + PRP_ACTIVE_CONNECTION_DEFAULT: False, + PRP_ACTIVE_CONNECTION_IP4CONFIG: ExportedObj.to_path(None), + PRP_ACTIVE_CONNECTION_DHCP4CONFIG: ExportedObj.to_path(None), + PRP_ACTIVE_CONNECTION_DEFAULT6: False, + PRP_ACTIVE_CONNECTION_IP6CONFIG: ExportedObj.to_path(None), + PRP_ACTIVE_CONNECTION_DHCP6CONFIG: ExportedObj.to_path(None), + PRP_ACTIVE_CONNECTION_VPN: self.is_vpn, + PRP_ACTIVE_CONNECTION_MASTER: ExportedObj.to_path(None), } - self.dbus_interface_add(IFACE_ACTIVE_CONNECTION, props, ActiveConnection.PropertiesChanged) + self.dbus_interface_add( + IFACE_ACTIVE_CONNECTION, props, ActiveConnection.PropertiesChanged + ) if self.is_vpn: props = { - PRP_VPN_CONNECTION_VPN_STATE: dbus.UInt32(NM.VpnConnectionState.UNKNOWN), - PRP_VPN_CONNECTION_BANNER: '*** VPN connection %s ***' % (con_inst.get_id()), + PRP_VPN_CONNECTION_VPN_STATE: dbus.UInt32( + NM.VpnConnectionState.UNKNOWN + ), + PRP_VPN_CONNECTION_BANNER: "*** VPN connection %s ***" + % (con_inst.get_id()), } - self.dbus_interface_add(IFACE_VPN_CONNECTION, props, ActiveConnection.VpnPropertiesChanged) - + self.dbus_interface_add( + IFACE_VPN_CONNECTION, props, ActiveConnection.VpnPropertiesChanged + ) def _set_state(self, state, reason): state = dbus.UInt32(state) - self._dbus_property_set(IFACE_ACTIVE_CONNECTION, PRP_ACTIVE_CONNECTION_STATE, state) + self._dbus_property_set( + IFACE_ACTIVE_CONNECTION, PRP_ACTIVE_CONNECTION_STATE, state + ) self.StateChanged(state, dbus.UInt32(reason)) def activation_cancel(self): @@ -1163,55 +1382,62 @@ class ActiveConnection(ExportedObj): def _activation_step2(self): assert self._activation_id is not None self._activation_id = None - self._set_state(NM.ActiveConnectionState.ACTIVATED, NM.ActiveConnectionStateReason.UNKNOWN) + self._set_state( + NM.ActiveConnectionState.ACTIVATED, NM.ActiveConnectionStateReason.UNKNOWN + ) return False def _activation_step1(self): assert self._activation_id is not None self._activation_id = GLib.timeout_add(50, self._activation_step2) self.device.set_active_connection(self) - self._set_state(NM.ActiveConnectionState.ACTIVATING, NM.ActiveConnectionStateReason.UNKNOWN) + self._set_state( + NM.ActiveConnectionState.ACTIVATING, NM.ActiveConnectionStateReason.UNKNOWN + ) return False def start_activation(self): assert self._activation_id is None self._activation_id = GLib.timeout_add(50, self._activation_step1) - @dbus.service.signal(IFACE_VPN_CONNECTION, signature='a{sv}') + @dbus.service.signal(IFACE_VPN_CONNECTION, signature="a{sv}") def PropertiesChanged(self, changed): pass + VpnPropertiesChanged = PropertiesChanged - @dbus.service.signal(IFACE_ACTIVE_CONNECTION, signature='a{sv}') + @dbus.service.signal(IFACE_ACTIVE_CONNECTION, signature="a{sv}") def PropertiesChanged(self, changed): pass - @dbus.service.signal(IFACE_ACTIVE_CONNECTION, signature='uu') + @dbus.service.signal(IFACE_ACTIVE_CONNECTION, signature="uu") def StateChanged(self, state, reason): pass - @dbus.service.signal(IFACE_VPN_CONNECTION, signature='uu') + @dbus.service.signal(IFACE_VPN_CONNECTION, signature="uu") def VpnStateChanged(self, state, reason): pass + ############################################################################### -PRP_NM_DEVICES = 'Devices' -PRP_NM_ALL_DEVICES = 'AllDevices' -PRP_NM_NETWORKING_ENABLED = 'NetworkingEnabled' -PRP_NM_WWAN_ENABLED = 'WwanEnabled' -PRP_NM_WWAN_HARDWARE_ENABLED = 'WwanHardwareEnabled' -PRP_NM_WIRELESS_ENABLED = 'WirelessEnabled' -PRP_NM_WIRELESS_HARDWARE_ENABLED = 'WirelessHardwareEnabled' -PRP_NM_WIMAX_ENABLED = 'WimaxEnabled' -PRP_NM_WIMAX_HARDWARE_ENABLED = 'WimaxHardwareEnabled' -PRP_NM_ACTIVE_CONNECTIONS = 'ActiveConnections' -PRP_NM_PRIMARY_CONNECTION = 'PrimaryConnection' -PRP_NM_ACTIVATING_CONNECTION = 'ActivatingConnection' -PRP_NM_STARTUP = 'Startup' -PRP_NM_STATE = 'State' -PRP_NM_VERSION = 'Version' -PRP_NM_CONNECTIVITY = 'Connectivity' +PRP_NM_DEVICES = "Devices" +PRP_NM_ALL_DEVICES = "AllDevices" +PRP_NM_NETWORKING_ENABLED = "NetworkingEnabled" +PRP_NM_WWAN_ENABLED = "WwanEnabled" +PRP_NM_WWAN_HARDWARE_ENABLED = "WwanHardwareEnabled" +PRP_NM_WIRELESS_ENABLED = "WirelessEnabled" +PRP_NM_WIRELESS_HARDWARE_ENABLED = "WirelessHardwareEnabled" +PRP_NM_WIMAX_ENABLED = "WimaxEnabled" +PRP_NM_WIMAX_HARDWARE_ENABLED = "WimaxHardwareEnabled" +PRP_NM_ACTIVE_CONNECTIONS = "ActiveConnections" +PRP_NM_PRIMARY_CONNECTION = "PrimaryConnection" +PRP_NM_ACTIVATING_CONNECTION = "ActivatingConnection" +PRP_NM_STARTUP = "Startup" +PRP_NM_STATE = "State" +PRP_NM_VERSION = "Version" +PRP_NM_CONNECTIVITY = "Connectivity" + class NetworkManager(ExportedObj): def __init__(self): @@ -1220,28 +1446,30 @@ class NetworkManager(ExportedObj): self.active_connections = [] props = { - PRP_NM_DEVICES: ExportedObj.to_path_array(self.devices), - PRP_NM_ALL_DEVICES: ExportedObj.to_path_array(self.devices), - PRP_NM_NETWORKING_ENABLED: True, - PRP_NM_WWAN_ENABLED: True, - PRP_NM_WWAN_HARDWARE_ENABLED: True, - PRP_NM_WIRELESS_ENABLED: True, + PRP_NM_DEVICES: ExportedObj.to_path_array(self.devices), + PRP_NM_ALL_DEVICES: ExportedObj.to_path_array(self.devices), + PRP_NM_NETWORKING_ENABLED: True, + PRP_NM_WWAN_ENABLED: True, + PRP_NM_WWAN_HARDWARE_ENABLED: True, + PRP_NM_WIRELESS_ENABLED: True, PRP_NM_WIRELESS_HARDWARE_ENABLED: True, - PRP_NM_WIMAX_ENABLED: True, - PRP_NM_WIMAX_HARDWARE_ENABLED: True, - PRP_NM_ACTIVE_CONNECTIONS: ExportedObj.to_path_array(self.active_connections), - PRP_NM_PRIMARY_CONNECTION: ExportedObj.to_path(None), - PRP_NM_ACTIVATING_CONNECTION: ExportedObj.to_path(None), - PRP_NM_STARTUP: False, - PRP_NM_STATE: dbus.UInt32(NM.State.DISCONNECTED), - PRP_NM_VERSION: "0.9.9.0", - PRP_NM_CONNECTIVITY: dbus.UInt32(NM.ConnectivityState.NONE), + PRP_NM_WIMAX_ENABLED: True, + PRP_NM_WIMAX_HARDWARE_ENABLED: True, + PRP_NM_ACTIVE_CONNECTIONS: ExportedObj.to_path_array( + self.active_connections + ), + PRP_NM_PRIMARY_CONNECTION: ExportedObj.to_path(None), + PRP_NM_ACTIVATING_CONNECTION: ExportedObj.to_path(None), + PRP_NM_STARTUP: False, + PRP_NM_STATE: dbus.UInt32(NM.State.DISCONNECTED), + PRP_NM_VERSION: "0.9.9.0", + PRP_NM_CONNECTIVITY: dbus.UInt32(NM.ConnectivityState.NONE), } self.dbus_interface_add(IFACE_NM, props, NetworkManager.PropertiesChanged) self.export() - @dbus.service.signal(IFACE_NM, signature='u') + @dbus.service.signal(IFACE_NM, signature="u") def StateChanged(self, new_state): pass @@ -1249,20 +1477,22 @@ class NetworkManager(ExportedObj): self._dbus_property_set(IFACE_NM, PRP_NM_STATE, state) self.StateChanged(dbus.UInt32(self.state)) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='', out_signature='ao') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="", out_signature="ao") def GetDevices(self): return ExportedObj.to_path_array(self.devices) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='', out_signature='ao') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="", out_signature="ao") def GetAllDevices(self): return ExportedObj.to_path_array(self.devices) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='s', out_signature='o') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="s", out_signature="o") def GetDeviceByIpIface(self, ip_iface): - d = self.find_device_first(ip_iface = ip_iface, require = BusErr.UnknownDeviceException) + d = self.find_device_first( + ip_iface=ip_iface, require=BusErr.UnknownDeviceException + ) return ExportedObj.to_path(d) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='ooo', out_signature='o') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="ooo", out_signature="o") def ActivateConnection(self, conpath, devpath, specific_object): try: con_inst = gl.settings.get_connection(conpath) @@ -1272,14 +1502,14 @@ class NetworkManager(ExportedObj): con_hash = con_inst.con_hash con_type = NmUtil.con_hash_get_type(con_hash) - device = self.find_device_first(path = devpath) + device = self.find_device_first(path=devpath) if not device: if con_type == NM.SETTING_WIRED_SETTING_NAME: - device = self.find_device_first(dev_type = WiredDevice) + device = self.find_device_first(dev_type=WiredDevice) elif con_type == NM.SETTING_WIRELESS_SETTING_NAME: - device = self.find_device_first(dev_type = WifiDevice) + device = self.find_device_first(dev_type=WifiDevice) elif con_type == NM.SETTING_VLAN_SETTING_NAME: - ifname = con_hash[NM.SETTING_CONNECTION_SETTING_NAME]['interface-name'] + ifname = con_hash[NM.SETTING_CONNECTION_SETTING_NAME]["interface-name"] device = VlanDevice(ifname) self.add_device(device) elif con_type == NM.SETTING_VPN_SETTING_NAME: @@ -1291,19 +1521,23 @@ class NetworkManager(ExportedObj): break if not device: - raise BusErr.UnknownDeviceException("No device found for the requested iface.") + raise BusErr.UnknownDeviceException( + "No device found for the requested iface." + ) # See if we need secrets. For the moment, we only support WPA - if '802-11-wireless-security' in con_hash: - s_wsec = con_hash['802-11-wireless-security'] - if (s_wsec['key-mgmt'] == 'wpa-psk' and 'psk' not in s_wsec): - secrets = gl.agent_manager.get_secrets(con_hash, conpath, '802-11-wireless-security') + if "802-11-wireless-security" in con_hash: + s_wsec = con_hash["802-11-wireless-security"] + if s_wsec["key-mgmt"] == "wpa-psk" and "psk" not in s_wsec: + secrets = gl.agent_manager.get_secrets( + con_hash, conpath, "802-11-wireless-security" + ) if secrets is None: raise BusErr.NoSecretsException("No secret agent available") - if '802-11-wireless-security' not in secrets: + if "802-11-wireless-security" not in secrets: raise BusErr.NoSecretsException("No secrets provided") - s_wsec = secrets['802-11-wireless-security'] - if 'psk' not in s_wsec: + s_wsec = secrets["802-11-wireless-security"] + if "psk" not in s_wsec: raise BusErr.NoSecretsException("No secrets provided") ac = ActiveConnection(device, con_inst, None) @@ -1313,31 +1547,49 @@ class NetworkManager(ExportedObj): def active_connection_add(self, ac): ac.export() self.active_connections.append(ac) - self._dbus_property_set(IFACE_NM, PRP_NM_ACTIVE_CONNECTIONS, ExportedObj.to_path_array(self.active_connections)) + self._dbus_property_set( + IFACE_NM, + PRP_NM_ACTIVE_CONNECTIONS, + ExportedObj.to_path_array(self.active_connections), + ) ac.start_activation() def active_connection_remove(self, ac): ac.activation_cancel() self.active_connections.remove(ac) - self._dbus_property_set(IFACE_NM, PRP_NM_ACTIVE_CONNECTIONS, ExportedObj.to_path_array(self.active_connections)) + self._dbus_property_set( + IFACE_NM, + PRP_NM_ACTIVE_CONNECTIONS, + ExportedObj.to_path_array(self.active_connections), + ) ac.unexport() - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='a{sa{sv}}oo', out_signature='oo') + @dbus.service.method( + dbus_interface=IFACE_NM, in_signature="a{sa{sv}}oo", out_signature="oo" + ) def AddAndActivateConnection(self, con_hash, devpath, specific_object): - conpath, acpath, result = self.AddAndActivateConnection2(con_hash, devpath, specific_object, dict()) + conpath, acpath, result = self.AddAndActivateConnection2( + con_hash, devpath, specific_object, dict() + ) return (conpath, acpath) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='a{sa{sv}}ooa{sv}', out_signature='ooa{sv}') + @dbus.service.method( + dbus_interface=IFACE_NM, + in_signature="a{sa{sv}}ooa{sv}", + out_signature="ooa{sv}", + ) def AddAndActivateConnection2(self, con_hash, devpath, specific_object, options): - device = self.find_device_first(path = devpath, require = BusErr.UnknownDeviceException) + device = self.find_device_first( + path=devpath, require=BusErr.UnknownDeviceException + ) conpath = gl.settings.AddConnection(con_hash) return (conpath, self.ActivateConnection(conpath, devpath, specific_object), []) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='o', out_signature='') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="o", out_signature="") def DeactivateConnection(self, active_connection): pass - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='b', out_signature='') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="b", out_signature="") def Sleep(self, do_sleep): if do_sleep: state = NM.State.ASLEEP @@ -1345,44 +1597,54 @@ class NetworkManager(ExportedObj): state = NM.State.DISCONNECTED self.set_state(state) - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='b', out_signature='') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="b", out_signature="") def Enable(self, do_enable): pass - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='', out_signature='a{ss}') + @dbus.service.method( + dbus_interface=IFACE_NM, in_signature="", out_signature="a{ss}" + ) def GetPermissions(self): - return { "org.freedesktop.NetworkManager.enable-disable-network": "yes", - "org.freedesktop.NetworkManager.sleep-wake": "no", - "org.freedesktop.NetworkManager.enable-disable-wifi": "yes", - "org.freedesktop.NetworkManager.enable-disable-wwan": "yes", - "org.freedesktop.NetworkManager.enable-disable-wimax": "yes", - "org.freedesktop.NetworkManager.network-control": "yes", - "org.freedesktop.NetworkManager.wifi.share.protected": "yes", - "org.freedesktop.NetworkManager.wifi.share.open": "yes", - "org.freedesktop.NetworkManager.settings.modify.own": "yes", - "org.freedesktop.NetworkManager.settings.modify.system": "yes", - "org.freedesktop.NetworkManager.settings.modify.hostname": "yes", - "org.freedesktop.NetworkManager.settings.modify.global-dns": "no", - "org.freedesktop.NetworkManager.reload": "no", - } - - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='ss', out_signature='') + return { + "org.freedesktop.NetworkManager.enable-disable-network": "yes", + "org.freedesktop.NetworkManager.sleep-wake": "no", + "org.freedesktop.NetworkManager.enable-disable-wifi": "yes", + "org.freedesktop.NetworkManager.enable-disable-wwan": "yes", + "org.freedesktop.NetworkManager.enable-disable-wimax": "yes", + "org.freedesktop.NetworkManager.network-control": "yes", + "org.freedesktop.NetworkManager.wifi.share.protected": "yes", + "org.freedesktop.NetworkManager.wifi.share.open": "yes", + "org.freedesktop.NetworkManager.settings.modify.own": "yes", + "org.freedesktop.NetworkManager.settings.modify.system": "yes", + "org.freedesktop.NetworkManager.settings.modify.hostname": "yes", + "org.freedesktop.NetworkManager.settings.modify.global-dns": "no", + "org.freedesktop.NetworkManager.reload": "no", + } + + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="ss", out_signature="") def SetLogging(self, level, domains): pass - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='', out_signature='ss') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="", out_signature="ss") def GetLogging(self): return ("info", "HW,RFKILL,CORE,DEVICE,WIFI,ETHER") - @dbus.service.method(dbus_interface=IFACE_NM, in_signature='', out_signature='u') + @dbus.service.method(dbus_interface=IFACE_NM, in_signature="", out_signature="u") def CheckConnectivity(self): raise BusErr.PermissionDeniedException("You fail") - @dbus.service.signal(IFACE_NM, signature='o') + @dbus.service.signal(IFACE_NM, signature="o") def DeviceAdded(self, devpath): pass - def find_devices(self, ident = _DEFAULT_ARG, path = _DEFAULT_ARG, iface = _DEFAULT_ARG, ip_iface = _DEFAULT_ARG, dev_type = _DEFAULT_ARG): + def find_devices( + self, + ident=_DEFAULT_ARG, + path=_DEFAULT_ARG, + iface=_DEFAULT_ARG, + ip_iface=_DEFAULT_ARG, + dev_type=_DEFAULT_ARG, + ): r = None for d in self.devices: if ident is not _DEFAULT_ARG: @@ -1403,24 +1665,40 @@ class NetworkManager(ExportedObj): continue yield d - def find_device_first(self, ident = _DEFAULT_ARG, path = _DEFAULT_ARG, iface = _DEFAULT_ARG, ip_iface = _DEFAULT_ARG, dev_type = _DEFAULT_ARG, require = None): + def find_device_first( + self, + ident=_DEFAULT_ARG, + path=_DEFAULT_ARG, + iface=_DEFAULT_ARG, + ip_iface=_DEFAULT_ARG, + dev_type=_DEFAULT_ARG, + require=None, + ): r = None - for d in self.find_devices(ident = ident, path = path, iface = iface, ip_iface = ip_iface, dev_type = dev_type): + for d in self.find_devices( + ident=ident, path=path, iface=iface, ip_iface=ip_iface, dev_type=dev_type + ): r = d break if r is None and require: if require is TestError: - raise TestError('Device not found') - raise BusErr.UnknownDeviceException('Device not found') + raise TestError("Device not found") + raise BusErr.UnknownDeviceException("Device not found") return r def add_device(self, device): - if self.find_device_first(ident = device.ident, path = device.path) is not None: - raise TestError("Duplicate device ident=%s / path=%s" % (device.ident, device.path)) + if self.find_device_first(ident=device.ident, path=device.path) is not None: + raise TestError( + "Duplicate device ident=%s / path=%s" % (device.ident, device.path) + ) device.export() self.devices.append(device) - self._dbus_property_set(IFACE_NM, PRP_NM_DEVICES, ExportedObj.to_path_array(self.devices)) - self._dbus_property_set(IFACE_NM, PRP_NM_ALL_DEVICES, ExportedObj.to_path_array(self.devices)) + self._dbus_property_set( + IFACE_NM, PRP_NM_DEVICES, ExportedObj.to_path_array(self.devices) + ) + self._dbus_property_set( + IFACE_NM, PRP_NM_ALL_DEVICES, ExportedObj.to_path_array(self.devices) + ) self.DeviceAdded(ExportedObj.to_path(device)) device.start() return device @@ -1428,8 +1706,12 @@ class NetworkManager(ExportedObj): def remove_device(self, device): device.stop() self.devices.remove(device) - self._dbus_property_set(IFACE_NM, PRP_NM_DEVICES, ExportedObj.to_path_array(self.devices)) - self._dbus_property_set(IFACE_NM, PRP_NM_ALL_DEVICES, ExportedObj.to_path_array(self.devices)) + self._dbus_property_set( + IFACE_NM, PRP_NM_DEVICES, ExportedObj.to_path_array(self.devices) + ) + self._dbus_property_set( + IFACE_NM, PRP_NM_ALL_DEVICES, ExportedObj.to_path_array(self.devices) + ) self.DeviceRemoved(ExportedObj.to_path(device)) device.unexport() @@ -1437,23 +1719,26 @@ class NetworkManager(ExportedObj): for d in self.devices: d.available_connections_update() - @dbus.service.signal(IFACE_NM, signature='o') + @dbus.service.signal(IFACE_NM, signature="o") def DeviceRemoved(self, devpath): pass - @dbus.service.signal(IFACE_NM, signature='a{sv}') + @dbus.service.signal(IFACE_NM, signature="a{sv}") def PropertiesChanged(self, changed): pass - @dbus.service.method(IFACE_TEST, in_signature='', out_signature='') + @dbus.service.method(IFACE_TEST, in_signature="", out_signature="") def Quit(self): gl.mainloop.quit() - @dbus.service.method(IFACE_TEST, in_signature='a{ss}', out_signature='a(sss)') + @dbus.service.method(IFACE_TEST, in_signature="a{ss}", out_signature="a(sss)") def FindConnections(self, selector_args): - return [(c.path, c.get_uuid(), c.get_id()) for c in gl.settings.find_connections(**selector_args)] + return [ + (c.path, c.get_uuid(), c.get_id()) + for c in gl.settings.find_connections(**selector_args) + ] - @dbus.service.method(IFACE_TEST, in_signature='a(oa(sa(sv)))', out_signature='') + @dbus.service.method(IFACE_TEST, in_signature="a(oa(sa(sv)))", out_signature="") def SetProperties(self, all_args): for i in [0, 1]: for path, iface_args in all_args: @@ -1462,73 +1747,82 @@ class NetworkManager(ExportedObj): raise TestError("Object %s does not exist" % (path)) for iface_name, args in iface_args: for propname, value in args: - o._dbus_property_set(iface_name, propname, value, - allow_detect_dbus_iface = True, - dry_run = (i == 0)) - - - @dbus.service.method(IFACE_TEST, in_signature='sa{sv}', out_signature='o') + o._dbus_property_set( + iface_name, + propname, + value, + allow_detect_dbus_iface=True, + dry_run=(i == 0), + ) + + @dbus.service.method(IFACE_TEST, in_signature="sa{sv}", out_signature="o") def AddObj(self, class_name, args): - if class_name in ['WiredDevice', 'WifiDevice']: + if class_name in ["WiredDevice", "WifiDevice"]: py_class = globals()[class_name] d = py_class(**args) return ExportedObj.to_path(self.add_device(d)) - elif class_name in ['WifiAp']: - if 'device' not in args: + elif class_name in ["WifiAp"]: + if "device" not in args: raise TestError('missing "device" paramter') - d = self.find_device_first(ident = args['device'], require = TestError) - del args['device'] - if 'ssid' not in args: - args['ssid'] = d.ident + '-ap-' + str(WifiAp.path_counter_next) + d = self.find_device_first(ident=args["device"], require=TestError) + del args["device"] + if "ssid" not in args: + args["ssid"] = d.ident + "-ap-" + str(WifiAp.path_counter_next) ap = WifiAp(**args) return ExportedObj.to_path(d.add_ap(ap)) - raise TestError("Invalid python type \"%s\"" % (class_name)) + raise TestError('Invalid python type "%s"' % (class_name)) - @dbus.service.method(IFACE_TEST, in_signature='ssas', out_signature='o') + @dbus.service.method(IFACE_TEST, in_signature="ssas", out_signature="o") def AddWiredDevice(self, ifname, mac, subchannels): dev = WiredDevice(ifname, mac, subchannels) return ExportedObj.to_path(self.add_device(dev)) - @dbus.service.method(IFACE_TEST, in_signature='s', out_signature='o') + @dbus.service.method(IFACE_TEST, in_signature="s", out_signature="o") def AddWifiDevice(self, ifname): dev = WifiDevice(ifname) return ExportedObj.to_path(self.add_device(dev)) - @dbus.service.method(IFACE_TEST, in_signature='o', out_signature='') + @dbus.service.method(IFACE_TEST, in_signature="o", out_signature="") def RemoveDevice(self, path): - d = self.find_device_first(path = path, require = TestError) + d = self.find_device_first(path=path, require=TestError) self.remove_device(d) - @dbus.service.method(IFACE_TEST, in_signature='sss', out_signature='o') + @dbus.service.method(IFACE_TEST, in_signature="sss", out_signature="o") def AddWifiAp(self, ident, ssid, bssid): - d = self.find_device_first(ident = ident, require = TestError) + d = self.find_device_first(ident=ident, require=TestError) ap = WifiAp(ssid, bssid) return ExportedObj.to_path(d.add_ap(ap)) - @dbus.service.method(IFACE_TEST, in_signature='so', out_signature='') + @dbus.service.method(IFACE_TEST, in_signature="so", out_signature="") def RemoveWifiAp(self, ident, ap_path): - d = self.find_device_first(ident = ident, require = TestError) + d = self.find_device_first(ident=ident, require=TestError) d.remove_ap_by_path(ap_path) - @dbus.service.method(IFACE_TEST, in_signature='', out_signature='') + @dbus.service.method(IFACE_TEST, in_signature="", out_signature="") def AutoRemoveNextConnection(self): gl.settings.auto_remove_next_connection() - @dbus.service.method(dbus_interface=IFACE_TEST, in_signature='a{sa{sv}}b', out_signature='o') + @dbus.service.method( + dbus_interface=IFACE_TEST, in_signature="a{sa{sv}}b", out_signature="o" + ) def AddConnection(self, con_hash, do_verify_strict): return gl.settings.add_connection(con_hash, do_verify_strict) - @dbus.service.method(dbus_interface=IFACE_TEST, in_signature='sa{sa{sv}}b', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_TEST, in_signature="sa{sa{sv}}b", out_signature="" + ) def UpdateConnection(self, path, con_hash, do_verify_strict): return gl.settings.update_connection(con_hash, path, do_verify_strict) - @dbus.service.method(dbus_interface=IFACE_TEST, in_signature='ba{ss}', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_TEST, in_signature="ba{ss}", out_signature="" + ) def ConnectionSetVisible(self, vis, selector_args): cons = list(gl.settings.find_connections(**selector_args)) - assert(len(cons) == 1) + assert len(cons) == 1 cons[0].SetVisible(vis) - @dbus.service.method(dbus_interface=IFACE_TEST, in_signature='', out_signature='') + @dbus.service.method(dbus_interface=IFACE_TEST, in_signature="", out_signature="") def Restart(self): gl.bus.release_name("org.freedesktop.NetworkManager") gl.bus.request_name("org.freedesktop.NetworkManager") @@ -1536,8 +1830,9 @@ class NetworkManager(ExportedObj): ############################################################################### -PRP_CONNECTION_UNSAVED = 'Unsaved' -PRP_CONNECTION_FILENAME = 'Filename' +PRP_CONNECTION_UNSAVED = "Unsaved" +PRP_CONNECTION_FILENAME = "Filename" + class Connection(ExportedObj): def __init__(self, path_counter, con_hash, do_verify_strict=True): @@ -1551,9 +1846,11 @@ class Connection(ExportedObj): s_con = {} con_hash[NM.SETTING_CONNECTION_SETTING_NAME] = s_con if NmUtil.con_hash_get_id(con_hash) is None: - s_con[NM.SETTING_CONNECTION_ID] = 'connection-%s' % (path_counter) + s_con[NM.SETTING_CONNECTION_ID] = "connection-%s" % (path_counter) if NmUtil.con_hash_get_uuid(con_hash) is None: - s_con[NM.SETTING_CONNECTION_UUID] = str(uuid.uuid3(uuid.NAMESPACE_URL, path)) + s_con[NM.SETTING_CONNECTION_UUID] = str( + uuid.uuid3(uuid.NAMESPACE_URL, path) + ) NmUtil.con_hash_verify(con_hash, do_verify_strict=do_verify_strict) @@ -1563,7 +1860,8 @@ class Connection(ExportedObj): props = { PRP_CONNECTION_UNSAVED: False, - PRP_CONNECTION_FILENAME: "/etc/NetworkManager/system-connections/" + self.get_id(), + PRP_CONNECTION_FILENAME: "/etc/NetworkManager/system-connections/" + + self.get_id(), } self.dbus_interface_add(IFACE_CONNECTION, props) @@ -1582,56 +1880,73 @@ class Connection(ExportedObj): def update_connection(self, con_hash, do_verify_strict): - NmUtil.con_hash_verify(con_hash, do_verify_strict = do_verify_strict) + NmUtil.con_hash_verify(con_hash, do_verify_strict=do_verify_strict) old_uuid = self.get_uuid() new_uuid = NmUtil.con_hash_get_uuid(con_hash) if old_uuid != new_uuid: - raise BusErr.InvalidPropertyException('connection.uuid: cannot change the uuid from %s to %s' % (old_uuid, new_uuid)) + raise BusErr.InvalidPropertyException( + "connection.uuid: cannot change the uuid from %s to %s" + % (old_uuid, new_uuid) + ) - self.con_hash = con_hash; + self.con_hash = con_hash self.Updated() - @dbus.service.method(dbus_interface=IFACE_CONNECTION, in_signature='', out_signature='a{sa{sv}}') + @dbus.service.method( + dbus_interface=IFACE_CONNECTION, in_signature="", out_signature="a{sa{sv}}" + ) def GetSettings(self): - if hasattr(self, '_remove_next_connection_cb'): + if hasattr(self, "_remove_next_connection_cb"): self._remove_next_connection_cb() raise BusErr.UnknownConnectionException("Connection not found") if not self.visible: raise BusErr.PermissionDeniedException() return self.con_hash - @dbus.service.method(dbus_interface=IFACE_CONNECTION, in_signature='b', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_CONNECTION, in_signature="b", out_signature="" + ) def SetVisible(self, vis): self.visible = vis self.Updated() - @dbus.service.method(dbus_interface=IFACE_CONNECTION, in_signature='', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_CONNECTION, in_signature="", out_signature="" + ) def Delete(self): gl.settings.delete_connection(self) - @dbus.service.method(dbus_interface=IFACE_CONNECTION, in_signature='a{sa{sv}}', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_CONNECTION, in_signature="a{sa{sv}}", out_signature="" + ) def Update(self, con_hash): self.update_connection(con_hash, True) - @dbus.service.method(dbus_interface=IFACE_CONNECTION, in_signature='a{sa{sv}}ua{sv}', out_signature='a{sv}') + @dbus.service.method( + dbus_interface=IFACE_CONNECTION, + in_signature="a{sa{sv}}ua{sv}", + out_signature="a{sv}", + ) def Update2(self, con_hash, flags, args): self.update_connection(con_hash, True) return [] - @dbus.service.signal(IFACE_CONNECTION, signature='') + @dbus.service.signal(IFACE_CONNECTION, signature="") def Removed(self): pass - @dbus.service.signal(IFACE_CONNECTION, signature='') + @dbus.service.signal(IFACE_CONNECTION, signature="") def Updated(self): pass + ############################################################################### -PRP_SETTINGS_HOSTNAME = 'Hostname' -PRP_SETTINGS_CAN_MODIFY = 'CanModify' -PRP_SETTINGS_CONNECTIONS = 'Connections' +PRP_SETTINGS_HOSTNAME = "Hostname" +PRP_SETTINGS_CAN_MODIFY = "CanModify" +PRP_SETTINGS_CONNECTIONS = "Connections" + class Settings(ExportedObj): def __init__(self): @@ -1642,30 +1957,32 @@ class Settings(ExportedObj): self.remove_next_connection = False props = { - PRP_SETTINGS_HOSTNAME: "foobar.baz", - PRP_SETTINGS_CAN_MODIFY: True, - PRP_SETTINGS_CONNECTIONS: dbus.Array([], 'o'), + PRP_SETTINGS_HOSTNAME: "foobar.baz", + PRP_SETTINGS_CAN_MODIFY: True, + PRP_SETTINGS_CONNECTIONS: dbus.Array([], "o"), } self.dbus_interface_add(IFACE_SETTINGS, props, Settings.PropertiesChanged) self.export() def auto_remove_next_connection(self): - self.remove_next_connection = True; + self.remove_next_connection = True def get_connection(self, path): return self.connections[path] - def get_connections(self, stable_order = True): + def get_connections(self, stable_order=True): cons = list(self.connections.values()) if stable_order: - cons.sort(key = lambda c: (Util.random_int(c.get_id()), Util.random_int(c.path))) + cons.sort( + key=lambda c: (Util.random_int(c.get_id()), Util.random_int(c.path)) + ) return cons - def get_connection_paths(self, stable_order = True): - return [c.path for c in self.get_connections(stable_order = stable_order)] + def get_connection_paths(self, stable_order=True): + return [c.path for c in self.get_connections(stable_order=stable_order)] - def find_connections(self, path = None, con_id = None, con_uuid = None): + def find_connections(self, path=None, con_id=None, con_uuid=None): for c in self.get_connections(): if path is not None: if c.path != path: @@ -1678,11 +1995,15 @@ class Settings(ExportedObj): continue yield c - @dbus.service.method(dbus_interface=IFACE_SETTINGS, in_signature='', out_signature='ao') + @dbus.service.method( + dbus_interface=IFACE_SETTINGS, in_signature="", out_signature="ao" + ) def ListConnections(self): return self.get_connection_paths() - @dbus.service.method(dbus_interface=IFACE_SETTINGS, in_signature='a{sa{sv}}', out_signature='o') + @dbus.service.method( + dbus_interface=IFACE_SETTINGS, in_signature="a{sa{sv}}", out_signature="o" + ) def AddConnection(self, con_hash): return self.add_connection(con_hash) @@ -1691,23 +2012,31 @@ class Settings(ExportedObj): con_inst = Connection(self.c_counter, con_hash, do_verify_strict) uuid = con_inst.get_uuid() - if uuid in [c.get_uuid() for c in self.get_connections(stable_order = False)]: - raise BusErr.InvalidSettingException('cannot add duplicate connection with uuid %s' % (uuid)) + if uuid in [c.get_uuid() for c in self.get_connections(stable_order=False)]: + raise BusErr.InvalidSettingException( + "cannot add duplicate connection with uuid %s" % (uuid) + ) con_inst.export() self.connections[con_inst.path] = con_inst self.NewConnection(con_inst.path) - self._dbus_property_set(IFACE_SETTINGS, PRP_SETTINGS_CONNECTIONS, dbus.Array(self.get_connection_paths(), 'o')) + self._dbus_property_set( + IFACE_SETTINGS, + PRP_SETTINGS_CONNECTIONS, + dbus.Array(self.get_connection_paths(), "o"), + ) gl.manager.devices_available_connections_update() if self.remove_next_connection: self.remove_next_connection = False + def cb(): - if hasattr(con_inst, '_remove_next_connection_cb'): + if hasattr(con_inst, "_remove_next_connection_cb"): del con_inst._remove_next_connection_cb self.delete_connection(con_inst) return False + # We will delete the connection right away on an idle handler. However, # the test races with initializing the connection (calling GetSettings()). # To avoid the race, we will check in GetSettings() whether the profile @@ -1719,56 +2048,64 @@ class Settings(ExportedObj): def update_connection(self, con_hash, path=None, do_verify_strict=True): if path not in self.connections: - raise BusErr.UnknownConnectionException('Connection not found') + raise BusErr.UnknownConnectionException("Connection not found") self.connections[path].update_connection(con_hash, do_verify_strict) def delete_connection(self, con_inst): del self.connections[con_inst.path] - self._dbus_property_set(IFACE_SETTINGS, PRP_SETTINGS_CONNECTIONS, dbus.Array(self.get_connection_paths(), 'o')) + self._dbus_property_set( + IFACE_SETTINGS, + PRP_SETTINGS_CONNECTIONS, + dbus.Array(self.get_connection_paths(), "o"), + ) con_inst.Removed() con_inst.unexport() gl.manager.devices_available_connections_update() - @dbus.service.method(dbus_interface=IFACE_SETTINGS, in_signature='s', out_signature='') + @dbus.service.method( + dbus_interface=IFACE_SETTINGS, in_signature="s", out_signature="" + ) def SaveHostname(self, hostname): # Arbitrary requirement to test error handling - if hostname.find('.') == -1: + if hostname.find(".") == -1: raise BusErr.InvalidHostnameException() self._dbus_property_set(IFACE_SETTINGS, PRP_SETTINGS_HOSTNAME, hostname) - @dbus.service.signal(IFACE_SETTINGS, signature='o') + @dbus.service.signal(IFACE_SETTINGS, signature="o") def NewConnection(self, path): pass - @dbus.service.signal(IFACE_SETTINGS, signature='a{sv}') + @dbus.service.signal(IFACE_SETTINGS, signature="a{sv}") def PropertiesChanged(self, path): pass - @dbus.service.method(IFACE_SETTINGS, in_signature='', out_signature='') + @dbus.service.method(IFACE_SETTINGS, in_signature="", out_signature="") def Quit(self): gl.mainloop.quit() + ############################################################################### -PRP_IP4_CONFIG_ADDRESSES = 'Addresses' -PRP_IP4_CONFIG_ADDRESSDATA = 'AddressData' -PRP_IP4_CONFIG_GATEWAY = 'Gateway' -PRP_IP4_CONFIG_ROUTES = 'Routes' -PRP_IP4_CONFIG_ROUTEDATA = 'RouteData' -PRP_IP4_CONFIG_NAMESERVERS = 'Nameservers' -PRP_IP4_CONFIG_DOMAINS = 'Domains' -PRP_IP4_CONFIG_SEARCHES = 'Searches' -PRP_IP4_CONFIG_DNSOPTIONS = 'DnsOptions' -PRP_IP4_CONFIG_DNSPRIORITY = 'DnsPriority' -PRP_IP4_CONFIG_WINSSERVERS = 'WinsServers' +PRP_IP4_CONFIG_ADDRESSES = "Addresses" +PRP_IP4_CONFIG_ADDRESSDATA = "AddressData" +PRP_IP4_CONFIG_GATEWAY = "Gateway" +PRP_IP4_CONFIG_ROUTES = "Routes" +PRP_IP4_CONFIG_ROUTEDATA = "RouteData" +PRP_IP4_CONFIG_NAMESERVERS = "Nameservers" +PRP_IP4_CONFIG_DOMAINS = "Domains" +PRP_IP4_CONFIG_SEARCHES = "Searches" +PRP_IP4_CONFIG_DNSOPTIONS = "DnsOptions" +PRP_IP4_CONFIG_DNSPRIORITY = "DnsPriority" +PRP_IP4_CONFIG_WINSSERVERS = "WinsServers" + class IP4Config(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/IP4Config/" - def __init__(self, generate_seed = _DEFAULT_ARG): + def __init__(self, generate_seed=_DEFAULT_ARG): ExportedObj.__init__(self, ExportedObj.create_path(IP4Config)) if generate_seed == _DEFAULT_ARG: @@ -1784,15 +2121,15 @@ class IP4Config(ExportedObj): gateway = None if seed: if Util.random_bool(seed): - gateway = Util.random_ip(seed, net = '192.168.0.0/16')[0] + gateway = Util.random_ip(seed, net="192.168.0.0/16")[0] addrs = [] if seed: for n in range(0, Util.random_int(seed, 4)): a = { - 'addr': Util.random_ip(seed, net = '192.168.0.0/16')[0], - 'prefix': Util.random_int(seed, 17, 32), - 'gateway': gateway if n == 0 else None, + "addr": Util.random_ip(seed, net="192.168.0.0/16")[0], + "prefix": Util.random_int(seed, 17, 32), + "gateway": gateway if n == 0 else None, } addrs.append(a) @@ -1800,30 +2137,48 @@ class IP4Config(ExportedObj): if seed: for n in range(0, Util.random_int(seed, 4)): a = { - 'dest': Util.random_ip(seed, net = '192.168.0.0/16')[0], - 'prefix': Util.random_int(seed, 17, 32), - 'next-hop': None if (Util.random_int(seed) % 3 == 0) else Util.random_ip(seed, net = '192.168.0.0/16')[0], - 'metric': -1 if (Util.random_int(seed) % 3 == 0) else Util.random_int(seed, 0, 0xFFFFFFFF), + "dest": Util.random_ip(seed, net="192.168.0.0/16")[0], + "prefix": Util.random_int(seed, 17, 32), + "next-hop": None + if (Util.random_int(seed) % 3 == 0) + else Util.random_ip(seed, net="192.168.0.0/16")[0], + "metric": -1 + if (Util.random_int(seed) % 3 == 0) + else Util.random_int(seed, 0, 0xFFFFFFFF), } routes.append(a) nameservers = [] if seed: - nameservers = list([Util.random_ip(seed, net = '192.168.0.0/16')[0] for x in range(Util.random_int(seed, 4))]) - - names_selection = ['foo1.bar', 'foo2.bar', 'foo3.bar', 'foo4.bar', 'fo.o.bar', 'fo.x.y']; + nameservers = list( + [ + Util.random_ip(seed, net="192.168.0.0/16")[0] + for x in range(Util.random_int(seed, 4)) + ] + ) + + names_selection = [ + "foo1.bar", + "foo2.bar", + "foo3.bar", + "foo4.bar", + "fo.o.bar", + "fo.x.y", + ] domains = [] if seed: - domains = Util.random_subset(seed, ['dom4.' + s for s in names_selection]) + domains = Util.random_subset(seed, ["dom4." + s for s in names_selection]) searches = [] if seed: - domains = Util.random_subset(seed, ['sear4.' + s for s in names_selection]) + domains = Util.random_subset(seed, ["sear4." + s for s in names_selection]) dnsoptions = [] if seed: - dnsoptions = Util.random_subset(seed, ['dns4-opt1', 'dns4-opt2', 'dns4-opt3', 'dns4-opt4']) + dnsoptions = Util.random_subset( + seed, ["dns4-opt1", "dns4-opt2", "dns4-opt3", "dns4-opt4"] + ) dnspriority = 0 if seed: @@ -1831,78 +2186,125 @@ class IP4Config(ExportedObj): winsservers = [] if seed: - winsservers = list([Util.random_ip(seed, net = '192.168.0.0/16')[0] for x in range(Util.random_int(seed, 4))]) + winsservers = list( + [ + Util.random_ip(seed, net="192.168.0.0/16")[0] + for x in range(Util.random_int(seed, 4)) + ] + ) return { - PRP_IP4_CONFIG_ADDRESSES: dbus.Array([ - [ Util.ip4_addr_be32(a['addr']), - a['prefix'], - Util.ip4_addr_be32(a['gateway']) if a['gateway'] else 0 - ] for a in addrs - ], - 'au'), - PRP_IP4_CONFIG_ADDRESSDATA: dbus.Array([ - dbus.Dictionary(collections.OrderedDict( [ ('address', dbus.String(a['addr'])), - ('prefix', dbus.UInt32(a['prefix']))] + \ - ([ ('gateway', dbus.String(a['gateway'])) ] if a['gateway'] else [])), - 'sv') - for a in addrs - ], - 'a{sv}'), - PRP_IP4_CONFIG_GATEWAY: dbus.String(gateway) if gateway else "", - PRP_IP4_CONFIG_ROUTES: dbus.Array([ - [ Util.ip4_addr_be32(a['dest']), - a['prefix'], - Util.ip4_addr_be32(a['next-hop'] or '0.0.0.0'), - max(a['metric'], 0) - ] for a in routes - ], - 'au'), - PRP_IP4_CONFIG_ROUTEDATA: dbus.Array([ - dbus.Dictionary(collections.OrderedDict( [ ('dest', dbus.String(a['dest'])), - ('prefix', dbus.UInt32(a['prefix']))] + \ - ([ ('next-hop', dbus.String(a['next-hop'])) ] if a['next-hop'] else []) + \ - ([ ('metric', dbus.UInt32(a['metric'])) ] if a['metric'] != -1 else [])), - 'sv') - for a in routes - ], - 'a{sv}'), - PRP_IP4_CONFIG_NAMESERVERS: dbus.Array([dbus.UInt32(Util.ip4_addr_be32(n)) for n in nameservers], 'u'), - PRP_IP4_CONFIG_DOMAINS: dbus.Array(domains, 's'), - PRP_IP4_CONFIG_SEARCHES: dbus.Array(searches, 's'), - PRP_IP4_CONFIG_DNSOPTIONS: dbus.Array(dnsoptions, 's'), + PRP_IP4_CONFIG_ADDRESSES: dbus.Array( + [ + [ + Util.ip4_addr_be32(a["addr"]), + a["prefix"], + Util.ip4_addr_be32(a["gateway"]) if a["gateway"] else 0, + ] + for a in addrs + ], + "au", + ), + PRP_IP4_CONFIG_ADDRESSDATA: dbus.Array( + [ + dbus.Dictionary( + collections.OrderedDict( + [ + ("address", dbus.String(a["addr"])), + ("prefix", dbus.UInt32(a["prefix"])), + ] + + ( + [("gateway", dbus.String(a["gateway"]))] + if a["gateway"] + else [] + ) + ), + "sv", + ) + for a in addrs + ], + "a{sv}", + ), + PRP_IP4_CONFIG_GATEWAY: dbus.String(gateway) if gateway else "", + PRP_IP4_CONFIG_ROUTES: dbus.Array( + [ + [ + Util.ip4_addr_be32(a["dest"]), + a["prefix"], + Util.ip4_addr_be32(a["next-hop"] or "0.0.0.0"), + max(a["metric"], 0), + ] + for a in routes + ], + "au", + ), + PRP_IP4_CONFIG_ROUTEDATA: dbus.Array( + [ + dbus.Dictionary( + collections.OrderedDict( + [ + ("dest", dbus.String(a["dest"])), + ("prefix", dbus.UInt32(a["prefix"])), + ] + + ( + [("next-hop", dbus.String(a["next-hop"]))] + if a["next-hop"] + else [] + ) + + ( + [("metric", dbus.UInt32(a["metric"]))] + if a["metric"] != -1 + else [] + ) + ), + "sv", + ) + for a in routes + ], + "a{sv}", + ), + PRP_IP4_CONFIG_NAMESERVERS: dbus.Array( + [dbus.UInt32(Util.ip4_addr_be32(n)) for n in nameservers], "u" + ), + PRP_IP4_CONFIG_DOMAINS: dbus.Array(domains, "s"), + PRP_IP4_CONFIG_SEARCHES: dbus.Array(searches, "s"), + PRP_IP4_CONFIG_DNSOPTIONS: dbus.Array(dnsoptions, "s"), PRP_IP4_CONFIG_DNSPRIORITY: dbus.Int32(dnspriority), - PRP_IP4_CONFIG_WINSSERVERS: dbus.Array([dbus.UInt32(Util.ip4_addr_be32(n)) for n in winsservers], 'u'), + PRP_IP4_CONFIG_WINSSERVERS: dbus.Array( + [dbus.UInt32(Util.ip4_addr_be32(n)) for n in winsservers], "u" + ), } def props_regenerate(self, generate_seed): props = self.generate_props(generate_seed) - for k,v in props.items(): + for k, v in props.items(): self._dbus_property_set(IFACE_IP4_CONFIG, k, v) - @dbus.service.signal(IFACE_IP4_CONFIG, signature='a{sv}') + @dbus.service.signal(IFACE_IP4_CONFIG, signature="a{sv}") def PropertiesChanged(self, path): pass + ############################################################################### -PRP_IP6_CONFIG_ADDRESSES = "Addresses" +PRP_IP6_CONFIG_ADDRESSES = "Addresses" PRP_IP6_CONFIG_ADDRESSDATA = "AddressData" -PRP_IP6_CONFIG_GATEWAY = "Gateway" -PRP_IP6_CONFIG_ROUTES = "Routes" -PRP_IP6_CONFIG_ROUTEDATA = "RouteData" +PRP_IP6_CONFIG_GATEWAY = "Gateway" +PRP_IP6_CONFIG_ROUTES = "Routes" +PRP_IP6_CONFIG_ROUTEDATA = "RouteData" PRP_IP6_CONFIG_NAMESERVERS = "Nameservers" -PRP_IP6_CONFIG_DOMAINS = "Domains" -PRP_IP6_CONFIG_SEARCHES = "Searches" -PRP_IP6_CONFIG_DNSOPTIONS = "DnsOptions" +PRP_IP6_CONFIG_DOMAINS = "Domains" +PRP_IP6_CONFIG_SEARCHES = "Searches" +PRP_IP6_CONFIG_DNSOPTIONS = "DnsOptions" PRP_IP6_CONFIG_DNSPRIORITY = "DnsPriority" + class IP6Config(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/IP6Config/" - def __init__(self, generate_seed = _DEFAULT_ARG): + def __init__(self, generate_seed=_DEFAULT_ARG): ExportedObj.__init__(self, ExportedObj.create_path(IP6Config)) if generate_seed == _DEFAULT_ARG: @@ -1918,15 +2320,15 @@ class IP6Config(ExportedObj): gateway = None if seed: if Util.random_bool(seed): - gateway = Util.random_ip(seed, net = '2001:a::/64')[0] + gateway = Util.random_ip(seed, net="2001:a::/64")[0] addrs = [] if seed: for n in range(0, Util.random_int(seed, 4)): a = { - 'addr': Util.random_ip(seed, net = '2001:a::/64')[0], - 'prefix': Util.random_int(seed, 65, 128), - 'gateway': gateway if n == 0 else None, + "addr": Util.random_ip(seed, net="2001:a::/64")[0], + "prefix": Util.random_int(seed, 65, 128), + "gateway": gateway if n == 0 else None, } addrs.append(a) @@ -1934,102 +2336,162 @@ class IP6Config(ExportedObj): if seed: for n in range(0, Util.random_int(seed, 4)): a = { - 'dest': Util.random_ip(seed, net = '2001:a::/64')[0], - 'prefix': Util.random_int(seed, 65, 128), - 'next-hop': None if (Util.random_int(seed) % 3 == 0) else Util.random_ip(seed, net = '2001:a::/64')[0], - 'metric': -1 if (Util.random_int(seed) % 3 == 0) else Util.random_int(seed, 0, 0xFFFFFFFF), + "dest": Util.random_ip(seed, net="2001:a::/64")[0], + "prefix": Util.random_int(seed, 65, 128), + "next-hop": None + if (Util.random_int(seed) % 3 == 0) + else Util.random_ip(seed, net="2001:a::/64")[0], + "metric": -1 + if (Util.random_int(seed) % 3 == 0) + else Util.random_int(seed, 0, 0xFFFFFFFF), } routes.append(a) nameservers = [] if seed: - nameservers = list([Util.random_ip(seed, net = '2001:a::/64')[0] for x in range(Util.random_int(seed, 4))]) - - names_selection = ['foo1.bar', 'foo2.bar', 'foo3.bar', 'foo4.bar', 'fo.o.bar', 'fo.x.y']; + nameservers = list( + [ + Util.random_ip(seed, net="2001:a::/64")[0] + for x in range(Util.random_int(seed, 4)) + ] + ) + + names_selection = [ + "foo1.bar", + "foo2.bar", + "foo3.bar", + "foo4.bar", + "fo.o.bar", + "fo.x.y", + ] domains = [] if seed: - domains = Util.random_subset(seed, ['dom6.' + s for s in names_selection]) + domains = Util.random_subset(seed, ["dom6." + s for s in names_selection]) searches = [] if seed: - domains = Util.random_subset(seed, ['sear6.' + s for s in names_selection]) + domains = Util.random_subset(seed, ["sear6." + s for s in names_selection]) dnsoptions = [] if seed: - dnsoptions = Util.random_subset(seed, ['dns6-opt1', 'dns6-opt2', 'dns6-opt3', 'dns6-opt4']) + dnsoptions = Util.random_subset( + seed, ["dns6-opt1", "dns6-opt2", "dns6-opt3", "dns6-opt4"] + ) dnspriority = 0 if seed: dnspriority = Util.random_int(seed, -10000, 10000) return { - PRP_IP6_CONFIG_ADDRESSES: dbus.Array([ - [ Util.ip6_addr_ay(a['addr']), - a['prefix'], - Util.ip6_addr_ay(a['gateway'] or '::') - ] for a in addrs - ], - '(ayuay)'), - PRP_IP6_CONFIG_ADDRESSDATA: dbus.Array([ - dbus.Dictionary(collections.OrderedDict( [ ('address', dbus.String(a['addr'])), - ('prefix', dbus.UInt32(a['prefix']))] + \ - ([ ('gateway', dbus.String(a['gateway'])) ] if a['gateway'] else [])), - 'sv') - for a in addrs - ], - 'a{sv}'), - PRP_IP6_CONFIG_GATEWAY: dbus.String(gateway) if gateway else "", - PRP_IP6_CONFIG_ROUTES: dbus.Array([ - [ Util.ip6_addr_ay(a['dest']), - a['prefix'], - Util.ip6_addr_ay(a['next-hop'] or '::'), - max(a['metric'], 0) - ] for a in routes - ], - '(ayuayu)'), - PRP_IP6_CONFIG_ROUTEDATA: dbus.Array([ - dbus.Dictionary(collections.OrderedDict( [ ('dest', dbus.String(a['dest'])), - ('prefix', dbus.UInt32(a['prefix']))] + \ - ([ ('next-hop', dbus.String(a['next-hop'])) ] if a['next-hop'] else []) + \ - ([ ('metric', dbus.UInt32(a['metric'])) ] if a['metric'] != -1 else [])), - 'sv') - for a in routes - ], - 'a{sv}'), - PRP_IP6_CONFIG_NAMESERVERS: dbus.Array([Util.ip6_addr_ay(n) for n in nameservers], 'ay'), - PRP_IP6_CONFIG_DOMAINS: dbus.Array(domains, 's'), - PRP_IP6_CONFIG_SEARCHES: dbus.Array(searches, 's'), - PRP_IP6_CONFIG_DNSOPTIONS: dbus.Array(dnsoptions, 's'), + PRP_IP6_CONFIG_ADDRESSES: dbus.Array( + [ + [ + Util.ip6_addr_ay(a["addr"]), + a["prefix"], + Util.ip6_addr_ay(a["gateway"] or "::"), + ] + for a in addrs + ], + "(ayuay)", + ), + PRP_IP6_CONFIG_ADDRESSDATA: dbus.Array( + [ + dbus.Dictionary( + collections.OrderedDict( + [ + ("address", dbus.String(a["addr"])), + ("prefix", dbus.UInt32(a["prefix"])), + ] + + ( + [("gateway", dbus.String(a["gateway"]))] + if a["gateway"] + else [] + ) + ), + "sv", + ) + for a in addrs + ], + "a{sv}", + ), + PRP_IP6_CONFIG_GATEWAY: dbus.String(gateway) if gateway else "", + PRP_IP6_CONFIG_ROUTES: dbus.Array( + [ + [ + Util.ip6_addr_ay(a["dest"]), + a["prefix"], + Util.ip6_addr_ay(a["next-hop"] or "::"), + max(a["metric"], 0), + ] + for a in routes + ], + "(ayuayu)", + ), + PRP_IP6_CONFIG_ROUTEDATA: dbus.Array( + [ + dbus.Dictionary( + collections.OrderedDict( + [ + ("dest", dbus.String(a["dest"])), + ("prefix", dbus.UInt32(a["prefix"])), + ] + + ( + [("next-hop", dbus.String(a["next-hop"]))] + if a["next-hop"] + else [] + ) + + ( + [("metric", dbus.UInt32(a["metric"]))] + if a["metric"] != -1 + else [] + ) + ), + "sv", + ) + for a in routes + ], + "a{sv}", + ), + PRP_IP6_CONFIG_NAMESERVERS: dbus.Array( + [Util.ip6_addr_ay(n) for n in nameservers], "ay" + ), + PRP_IP6_CONFIG_DOMAINS: dbus.Array(domains, "s"), + PRP_IP6_CONFIG_SEARCHES: dbus.Array(searches, "s"), + PRP_IP6_CONFIG_DNSOPTIONS: dbus.Array(dnsoptions, "s"), PRP_IP6_CONFIG_DNSPRIORITY: dbus.Int32(dnspriority), } def props_regenerate(self, generate_seed): props = self.generate_props(generate_seed) - for k,v in props.items(): + for k, v in props.items(): self._dbus_property_set(IFACE_IP6_CONFIG, k, v) - @dbus.service.signal(IFACE_IP6_CONFIG, signature='a{sv}') + @dbus.service.signal(IFACE_IP6_CONFIG, signature="a{sv}") def PropertiesChanged(self, path): pass + ############################################################################### -PRP_DHCP4_CONFIG_OPTIONS = 'Options' +PRP_DHCP4_CONFIG_OPTIONS = "Options" + class Dhcp4Config(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/DHCP4Config/" - def __init__(self, generate_seed = _DEFAULT_ARG): + def __init__(self, generate_seed=_DEFAULT_ARG): ExportedObj.__init__(self, ExportedObj.create_path(Dhcp4Config)) if generate_seed == _DEFAULT_ARG: generate_seed = self.path props = self._props_generate(generate_seed) - self.dbus_interface_add(IFACE_DHCP4_CONFIG, props, Dhcp4Config.PropertiesChanged) + self.dbus_interface_add( + IFACE_DHCP4_CONFIG, props, Dhcp4Config.PropertiesChanged + ) self.export() def _props_generate(self, generate_seed): @@ -2037,39 +2499,46 @@ class Dhcp4Config(ExportedObj): options = [] if seed: - options = Util.random_subset(seed, [('dhcp-4-opt-' + str(i), 'val-' + str(i)) for i in range(10)]) + options = Util.random_subset( + seed, [("dhcp-4-opt-" + str(i), "val-" + str(i)) for i in range(10)] + ) return { - PRP_DHCP4_CONFIG_OPTIONS: dbus.Dictionary(collections.OrderedDict(options), - 'sv') + PRP_DHCP4_CONFIG_OPTIONS: dbus.Dictionary( + collections.OrderedDict(options), "sv" + ) } def props_regenerate(self, generate_seed): props = self.generate_props(generate_seed) - for k,v in props.items(): + for k, v in props.items(): self._dbus_property_set(IFACE_DHCP4_CONFIG, k, v) - @dbus.service.signal(IFACE_DHCP4_CONFIG, signature='a{sv}') + @dbus.service.signal(IFACE_DHCP4_CONFIG, signature="a{sv}") def PropertiesChanged(self, path): pass + ############################################################################### -PRP_DHCP6_CONFIG_OPTIONS = 'Options' +PRP_DHCP6_CONFIG_OPTIONS = "Options" + class Dhcp6Config(ExportedObj): path_counter_next = 1 path_prefix = "/org/freedesktop/NetworkManager/DHCP6Config/" - def __init__(self, generate_seed = _DEFAULT_ARG): + def __init__(self, generate_seed=_DEFAULT_ARG): ExportedObj.__init__(self, ExportedObj.create_path(Dhcp6Config)) if generate_seed == _DEFAULT_ARG: generate_seed = self.path props = self._props_generate(generate_seed) - self.dbus_interface_add(IFACE_DHCP6_CONFIG, props, Dhcp6Config.PropertiesChanged) + self.dbus_interface_add( + IFACE_DHCP6_CONFIG, props, Dhcp6Config.PropertiesChanged + ) self.export() def _props_generate(self, generate_seed): @@ -2077,78 +2546,98 @@ class Dhcp6Config(ExportedObj): options = [] if seed: - options = Util.random_subset(seed, [('dhcp-6-opt-' + str(i), 'val-' + str(i)) for i in range(10)]) + options = Util.random_subset( + seed, [("dhcp-6-opt-" + str(i), "val-" + str(i)) for i in range(10)] + ) return { - PRP_DHCP4_CONFIG_OPTIONS: dbus.Dictionary(collections.OrderedDict(options), - 'sv') + PRP_DHCP4_CONFIG_OPTIONS: dbus.Dictionary( + collections.OrderedDict(options), "sv" + ) } def props_regenerate(self, generate_seed): props = self.generate_props(generate_seed) - for k,v in props.items(): + for k, v in props.items(): self._dbus_property_set(IFACE_DHCP6_CONFIG, k, v) - @dbus.service.signal(IFACE_DHCP6_CONFIG, signature='a{sv}') + @dbus.service.signal(IFACE_DHCP6_CONFIG, signature="a{sv}") def PropertiesChanged(self, path): pass + ############################################################################### -PRP_DNS_MANAGER_MODE = 'Mode' -PRP_DNS_MANAGER_RC_MANAGER = 'RcManager' -PRP_DNS_MANAGER_CONFIGURATION = 'Configuration' +PRP_DNS_MANAGER_MODE = "Mode" +PRP_DNS_MANAGER_RC_MANAGER = "RcManager" +PRP_DNS_MANAGER_CONFIGURATION = "Configuration" + class DnsManager(ExportedObj): def __init__(self): ExportedObj.__init__(self, "/org/freedesktop/NetworkManager/DnsManager") props = { - PRP_DNS_MANAGER_MODE: "dnsmasq", - PRP_DNS_MANAGER_RC_MANAGER: "symlink", + PRP_DNS_MANAGER_MODE: "dnsmasq", + PRP_DNS_MANAGER_RC_MANAGER: "symlink", PRP_DNS_MANAGER_CONFIGURATION: dbus.Array( [ dbus.Dictionary( { - 'nameservers' : dbus.Array(['1.2.3.4', '5.6.7.8'], 's'), - 'priority' : dbus.Int32(100), + "nameservers": dbus.Array(["1.2.3.4", "5.6.7.8"], "s"), + "priority": dbus.Int32(100), }, - 'sv') + "sv", + ) ], - 'a{sv}'), + "a{sv}", + ), } self.dbus_interface_add(IFACE_DNS_MANAGER, props) self.export() + ############################################################################### -PATH_SECRET_AGENT = '/org/freedesktop/NetworkManager/SecretAgent' +PATH_SECRET_AGENT = "/org/freedesktop/NetworkManager/SecretAgent" FLAG_ALLOW_INTERACTION = 0x1 FLAG_REQUEST_NEW = 0x2 FLAG_USER_REQUESTED = 0x4 + class AgentManager(dbus.service.Object): def __init__(self): - dbus.service.Object.__init__(self, gl.bus, "/org/freedesktop/NetworkManager/AgentManager") + dbus.service.Object.__init__( + self, gl.bus, "/org/freedesktop/NetworkManager/AgentManager" + ) self.agents = {} - @dbus.service.method(dbus_interface=IFACE_AGENT_MANAGER, - in_signature='s', out_signature='', - sender_keyword='sender') + @dbus.service.method( + dbus_interface=IFACE_AGENT_MANAGER, + in_signature="s", + out_signature="", + sender_keyword="sender", + ) def Register(self, name, sender=None): self.RegisterWithCapabilities(name, 0, sender) - @dbus.service.method(dbus_interface=IFACE_AGENT_MANAGER, - in_signature='su', out_signature='', - sender_keyword='sender') + @dbus.service.method( + dbus_interface=IFACE_AGENT_MANAGER, + in_signature="su", + out_signature="", + sender_keyword="sender", + ) def RegisterWithCapabilities(self, name, caps, sender=None): self.agents[sender] = gl.bus.get_object(sender, PATH_SECRET_AGENT) - @dbus.service.method(dbus_interface=IFACE_AGENT_MANAGER, - in_signature='', out_signature='', - sender_keyword='sender') + @dbus.service.method( + dbus_interface=IFACE_AGENT_MANAGER, + in_signature="", + out_signature="", + sender_keyword="sender", + ) def Unregister(self, sender=None): del self.agents[sender] @@ -2160,19 +2649,25 @@ class AgentManager(dbus.service.Object): for sender in self.agents: agent = self.agents[sender] try: - secrets = agent.GetSecrets(con_hash, path, setting_name, - dbus.Array([], 's'), - FLAG_ALLOW_INTERACTION | FLAG_USER_REQUESTED, - dbus_interface=IFACE_AGENT) + secrets = agent.GetSecrets( + con_hash, + path, + setting_name, + dbus.Array([], "s"), + FLAG_ALLOW_INTERACTION | FLAG_USER_REQUESTED, + dbus_interface=IFACE_AGENT, + ) break except dbus.DBusException as e: - if e.get_dbus_name() == IFACE_AGENT + '.UserCanceled': - raise BusErr.UserCanceledException('User canceled') + if e.get_dbus_name() == IFACE_AGENT + ".UserCanceled": + raise BusErr.UserCanceledException("User canceled") continue return secrets + ############################################################################### + class ObjectManager(dbus.service.Object): def __init__(self, object_path): dbus.service.Object.__init__(self, gl.bus, object_path) @@ -2192,25 +2687,30 @@ class ObjectManager(dbus.service.Object): self.objs.remove(obj) self.InterfacesRemoved(obj.path, obj.get_managed_ifaces().keys()) - @dbus.service.signal(IFACE_OBJECT_MANAGER, signature='oa{sa{sv}}') + @dbus.service.signal(IFACE_OBJECT_MANAGER, signature="oa{sa{sv}}") def InterfacesAdded(self, name, ifaces): pass - @dbus.service.signal(IFACE_OBJECT_MANAGER, signature='oas') + @dbus.service.signal(IFACE_OBJECT_MANAGER, signature="oas") def InterfacesRemoved(self, name, ifaces): pass - @dbus.service.method(dbus_interface=IFACE_OBJECT_MANAGER, - in_signature='', out_signature='a{oa{sa{sv}}}', - sender_keyword='sender') + @dbus.service.method( + dbus_interface=IFACE_OBJECT_MANAGER, + in_signature="", + out_signature="a{oa{sa{sv}}}", + sender_keyword="sender", + ) def GetManagedObjects(self, sender=None): managed_objects = {} for obj in self.objs: managed_objects[obj.path] = obj.get_managed_ifaces() return managed_objects + ############################################################################### + def main(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) @@ -2222,20 +2722,24 @@ def main(): gl.mainloop = GLib.MainLoop() gl.bus = dbus.SessionBus() - gl.object_manager = ObjectManager('/org/freedesktop') + gl.object_manager = ObjectManager("/org/freedesktop") gl.manager = NetworkManager() gl.settings = Settings() gl.dns_manager = DnsManager() gl.agent_manager = AgentManager() if not gl.bus.request_name("org.freedesktop.NetworkManager"): - raise AssertionError("Failure to request D-Bus name org.freedesktop.NetworkManager") + raise AssertionError( + "Failure to request D-Bus name org.freedesktop.NetworkManager" + ) # Watch stdin; if it closes, assume our parent has crashed, and exit - id1 = GLib.io_add_watch(GLib.IOChannel.unix_new(0), - GLib.PRIORITY_DEFAULT, - GLib.IO_HUP, - lambda io, condition: gl.mainloop.quit() or True) + id1 = GLib.io_add_watch( + GLib.IOChannel.unix_new(0), + GLib.PRIORITY_DEFAULT, + GLib.IO_HUP, + lambda io, condition: gl.mainloop.quit() or True, + ) gl.mainloop.run() @@ -2249,5 +2753,6 @@ def main(): sys.exit(0) -if __name__ == '__main__': + +if __name__ == "__main__": main() |