From ed2e629449313304c71a7f3de9fe56ace6a3e194 Mon Sep 17 00:00:00 2001
From: Nicolas KAROLAK <nicolas@karolak.fr>
Date: Wed, 16 Oct 2019 09:26:56 +0000
Subject: [PATCH] switch to pydbus

dns[1] value come from AF_INET and AF_INET6 values https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/socket.h
---
 pkgs_envsetup.py          | 18 +++++++++++-------
 tests/test_dns_records.py | 26 ++++++++++++++------------
 utils.py                  | 27 +++++++++++++++++++++++++++
 3 files changed, 52 insertions(+), 19 deletions(-)

diff --git a/pkgs_envsetup.py b/pkgs_envsetup.py
index edc7230c..a861c815 100755
--- a/pkgs_envsetup.py
+++ b/pkgs_envsetup.py
@@ -7,6 +7,7 @@ PACKAGES = [
     "python3-defusedxml",
     "python3-openssl",
     "python3-psutil",
+    "python3-pydbus",
     "python3-requests",
     "python3-spf",
 ]
@@ -14,13 +15,16 @@ PACKAGES = [
 
 def main():
     for pkg in PACKAGES:
-        if run(
-            ["/usr/bin/dpkg", "-s", pkg],
-            shell=False,
-            stdout=DEVNULL,
-            stderr=DEVNULL,
-            stdin=PIPE,
-        ).returncode != 0:
+        if (
+            run(
+                ["/usr/bin/dpkg", "-s", pkg],
+                shell=False,
+                stdout=DEVNULL,
+                stderr=DEVNULL,
+                stdin=PIPE,
+            ).returncode
+            != 0
+        ):
             result = run(
                 ["/usr/bin/apt", "install", "-y", pkg],
                 shell=False,
diff --git a/tests/test_dns_records.py b/tests/test_dns_records.py
index 5a417247..8625078a 100755
--- a/tests/test_dns_records.py
+++ b/tests/test_dns_records.py
@@ -5,8 +5,8 @@ Criticality: Normal
 Checks that DNS records are provided by the customer servers are correctly set
 """
 
-import dbus
 from pathlib import Path
+import pydbus
 import re
 import subprocess
 import sys
@@ -23,20 +23,19 @@ def get_dns_servers() -> set:
 
     # dbus method
     try:
-        bus = dbus.SystemBus()
-        proxy = bus.get_object(
-            bus_name="org.freedesktop.resolve1", object_path="/org/freedesktop/resolve1"
-        )
-        iface = dbus.Interface(
-            object=proxy, dbus_interface="org.freedesktop.DBus.Properties"
-        )
-        data = iface.Get("org.freedesktop.resolve1.Manager", "DNS")
-        for dns in iface.Get("org.freedesktop.resolve1.Manager", "DNS"):
-            delimiter = ":" if len(dns[2]) == 16 else "."  # if IPv6 else IPv4
-            servers.append(delimiter.join([str(int(o)) for o in dns[2]]))
+        bus = pydbus.SystemBus()
+        bus_client = bus.get("org.freedesktop.resolve1", "/org/freedesktop/resolve1")
+        servers.extend(
+            [".".join(map(str, dns[2])) for dns in bus_client.DNS if dns[1] == 2]
+        )  # IPv4
+        servers.extend(
+            [":".join(map(str, dns[2])) for dns in bus_client.DNS if dns[1] == 10]
+        )  # IPv6
     except Exception as dbus_err:
         u.info("DBus method failed: {}".format(dbus_err))
 
+    # TODO: remove fallback methods below when the dbus one is confirmed to work everwhere
+
     # network-manager method
     if not len(servers) and subprocess.getstatusoutput("command -v nmcli")[0] == 0:
         _, output = subprocess.getstatusoutput(
@@ -122,6 +121,9 @@ def check_resolver(conf: dict, resolvers: set, ip: str) -> tuple:
 
 def main():
     print("Check DNS settings:")
+    if not u.supported_platform():
+        u.info("Platform not supported")
+        exit(2)
 
     warnings = 0
     errors = 0
diff --git a/utils.py b/utils.py
index cd844015..8413191b 100644
--- a/utils.py
+++ b/utils.py
@@ -3,6 +3,7 @@
 """EnvSetup utilities."""
 
 from collections import OrderedDict
+from configparser import ConfigParser
 from pathlib import Path
 import re
 import socket
@@ -22,6 +23,32 @@ CONF_PATH = "conf.sh"
 
 _conf_cache = None
 
+SUPPORTED_PLATFORMS = (("debian", "10"), ("ubuntu", "18.04"))
+
+
+def dist() -> tuple:
+    """Return distribution name and version).
+
+    :return: Distribution name and version
+    :rtype: tuple
+    """
+
+    parser = ConfigParser()
+    with open("/etc/os-release") as os_release:
+        parser.read_string("[os]\n{}".format(os_release.read()))
+
+    return (parser["os"]["ID"], parser["os"]["VERSION_ID"].strip('"'))
+
+
+def supported_platform() -> bool:
+    """Let you know if the current platform is supported.
+
+    :return: Wether the platform is supported or not
+    :rtype: bool
+    """
+
+    return dist() in SUPPORTED_PLATFORMS
+
 
 def log(text: str, error: bool = False):
     """Output log message to stout or stderr.
-- 
GitLab