Exemplo n.º 1
0
    def test_take_ownership(self):
        if not self._can_create:
            self.skipTest('Cannot create %s filesystem' % self._fs_name)

        if not self._can_mount:
            self.skipTest('Cannot mount %s filesystem' % self._fs_name)

        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create filesystem
        disk.Format(self._fs_name,
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')
        self.addCleanup(self._clean_format, self.vdevs[0])

        # create user for our test
        self.addCleanup(self._remove_user, self.username)
        uid, gid = self._add_user(self.username)

        # mount the device
        mnt_path = disk.Mount(self.no_options,
                              dbus_interface=self.iface_prefix + '.Filesystem')
        self.addCleanup(self._unmount, self.vdevs[0])

        # change owner of the mountpoint to our user
        os.chown(mnt_path, int(uid), int(gid))

        # now take ownership of the filesystem -- owner should now be root
        disk.TakeOwnership(self.no_options,
                           dbus_interface=self.iface_prefix + '.Filesystem')

        sys_stat = os.stat(mnt_path)
        self.assertEqual(sys_stat.st_uid, 0)
        self.assertEqual(sys_stat.st_gid, 0)

        # change the owner back and create some files and directories there
        os.chown(mnt_path, int(uid), int(gid))

        dirname = 'udisks_test_dir'
        fname = 'file.txt'

        os.mknod(os.path.join(mnt_path, fname))
        os.mkdir(os.path.join(mnt_path, dirname))
        os.mknod(os.path.join(mnt_path, dirname, fname))

        # now take ownership of the filesystem with recursive option -- owner
        # of everything should now be root
        d = dbus.Dictionary(signature='sv')
        d['recursive'] = True
        disk.TakeOwnership(d, dbus_interface=self.iface_prefix + '.Filesystem')

        sys_stat = os.stat(mnt_path)
        self.assertEqual(sys_stat.st_uid, 0)
        self.assertEqual(sys_stat.st_gid, 0)

        sys_stat = os.stat(os.path.join(mnt_path, dirname))
        self.assertEqual(sys_stat.st_uid, 0)
        self.assertEqual(sys_stat.st_gid, 0)

        sys_stat = os.stat(os.path.join(mnt_path, dirname, fname))
        self.assertEqual(sys_stat.st_uid, 0)
        self.assertEqual(sys_stat.st_gid, 0)
Exemplo n.º 2
0
    def test_configuration_crypttab(self):

        # this test will change /etc/crypttab, we might want to revert the changes when it finishes
        crypttab = self.read_file('/etc/crypttab')
        self.addCleanup(self.write_file, '/etc/crypttab', crypttab)

        # format the disk
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        disk.Format('xfs', {'encrypt.passphrase': 'test'},
                    dbus_interface=self.iface_prefix + '.Block')

        # cleanup -- close the luks and remove format
        self.addCleanup(self._clean_format, disk)
        self.addCleanup(self._close_luks, disk)

        # configuration items as arrays of dbus.Byte
        opts = self.str_to_ay('verify')
        passwd = self.str_to_ay('test')

        # set the new configuration
        conf = dbus.Dictionary({
            'passphrase-contents': passwd,
            'options': opts
        },
                               signature=dbus.Signature('sv'))
        disk.AddConfigurationItem(('crypttab', conf),
                                  self.no_options,
                                  dbus_interface=self.iface_prefix + '.Block')

        # get the configuration
        old_conf = self.get_property(disk, '.Block', 'Configuration')
        old_conf.assertTrue()
        self.assertEqual(old_conf.value[0][1]['options'], opts)

        # get the secret configuration (passphrase)
        sec_conf = disk.GetSecretConfiguration(
            self.no_options, dbus_interface=self.iface_prefix + '.Block')
        self.assertIsNotNone(sec_conf)
        self.assertEqual(sec_conf[0][1]['passphrase-contents'], passwd)

        # update the configuration
        new_opts = self.str_to_ay('verify,discard')
        new_conf = copy.deepcopy(sec_conf)
        new_conf[0][1]['options'] = new_opts

        disk.UpdateConfigurationItem(
            (sec_conf[0][0], sec_conf[0][1]), (new_conf[0][0], new_conf[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')
        time.sleep(5)

        # get the configuration after the update
        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertTrue()
        self.assertEqual(upd_conf.value[0][1]['options'], new_opts)

        # remove the configuration
        disk.RemoveConfigurationItem(
            (upd_conf.value[0][0], upd_conf.value[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertFalse()
Exemplo n.º 3
0
 def getResourcesProducedHistory(self, node_id: str) -> Dict:
     history = self._node_engine.getNodeHistoryById(node_id)
     if history:
         return dbus.Dictionary(history.getResourcesProducedHistory(),
                                signature='sv')
     return {}
Exemplo n.º 4
0
 def add_manufacturer_data(self, manuf_code, data):
     if not self.manufacturer_data:
         self.manufacturer_data = dbus.Dictionary({}, signature="qv")
     self.manufacturer_data[manuf_code] = dbus.Array(data, signature="y")
Exemplo n.º 5
0
 def _clean_format(self, disk):
     d = dbus.Dictionary(signature='sv')
     d['erase'] = True
     disk.Format('empty', d, dbus_interface=self.iface_prefix + '.Block')
Exemplo n.º 6
0
def modify_connection(params, nm=NetworkManager()):
    types = {
        'wired': '802-3-ethernet',
        'wireless': '802-11-wireless',
        'cdma': 'cdma',
    }
    type2desc = {1: '802-3-ethernet', 2: '802-11-wireless'}
    #uuid = params['nm.uuid']
    #conn = None
    #if uuid != "":
    #    conn = nm.get_connection(uuid)
    #if conn == None:
    conn_list = []
    for conn in nm.connections:
        for interface in nm.devices:
            if str(conn.settings.mac_address) == str(interface.hwaddress):
                dev_state = interface.proxy.Get(NM_DEVICE, "State")
                dev_type_int = interface.proxy.Get(NM_DEVICE, "DeviceType")
                dev_type = type2desc.get(dev_type_int, None)
                conn_list.append((conn, dev_type, int(dev_state)))
                break
    try:
        xbmc.log("conn_list: " + str(conn_list))
    except:
        syslog.syslog("conn_list: " + str(conn_list))
    active_conn_list = []
    for a in conn_list:
        if a[2] >= 20:  # http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE
            # any states other than NM_DEVICE_STATE_UNKNOWN
            # NM_DEVICE_STATE_UNMANAGED
            active_conn_list.append(a)
    #for b in active_conn_list:
    #    conn = b[0]
    #    if b[1] == type2desc[1]: # Wired Network
    #        break
    #if conn == None:
    #    for c in conn_list:
    #        conn = c[0]
    #        if c[1] == type2desc[1]: # Wired Networ
    #            break
    RETURN_CODE = -11
    if len(active_conn_list) > 0:
        for a in active_conn_list:
            conn = a[0]
            settings = conn.settings
            old_settings = str(settings._settings)
            if a[1] == type2desc[1]:  # Wired Network
                if params['nm.dhcp'] == "false":
                    address = params['nm.address']
                    netmask = params['nm.netmask']
                    gateway = params['nm.gateway']
                    dns = params['nm.dns']
                    dns_search = params['nm.search']
            if a[1] == type2desc[2]:  # Wireless Network
                if params['nm.wifi.dhcp'] == "false":
                    address = params['nm.wifi.address']
                    netmask = params['nm.wifi.netmask']
                    gateway = params['nm.wifi.gateway']
                    dns = params['nm.wifi.dns']
                    dns_search = params['nm.wifi.search']
                # 802-11-wireless
                if params["nm.wifi.5GOnly"] == "true":
                    # 5GHz 802.11a
                    band = "a"
                else:
                    # 2.4GHz 802.11
                    band = "bg"
                ## WiFi network mode
                if params["nm.wifi.adhoc"] == "true":
                    mode = "adhoc"
                else:
                    mode = "infrastructure"
                security = "802-11-wireless-security"
                key_mgmt = "none"
                # None
                if params["nm.wifi.security"] == "0":
                    security = ""
                # WEP (Open Key)
                if params["nm.wifi.security"] == "1":
                    key_mgmt = "none"
                    auth_alg = "open"
                # WEP (Shared Key)
                if params["nm.wifi.security"] == "2":
                    key_mgmt = "none"
                    auth_alg = "shared"
                # Dynamic WEP
                if params["nm.wifi.security"] == "3":
                    key_mgmt = "ieee8021x"
                # WPA/WPA2
                if params["nm.wifi.security"] == "4":
                    if mode == "adhoc":
                        key_mgmt = "wpa-none"
                    else:
                        key_mgmt = "wpa-psk"

                if "802-11-wireless" in settings._settings:
                    try:
                        xbmc.log(a[1] + " 802-11-wireless old: " +
                                 str(settings._settings['802-11-wireless']))
                    except:
                        syslog.syslog(
                            a[1] + " 802-11-wireless old: " +
                            str(settings._settings['802-11-wireless']))
                else:
                    settings._settings['802-11-wireless'] = dbus.Dictionary(
                        signature='sv')

                # clear 802-11-wireless settings
                # settings._settings['802-11-wireless'] = dbus.Dictionary(signature='sv')

                settings._settings['802-11-wireless'][
                    'security'] = dbus.String(security)
                settings._settings['802-11-wireless']['mode'] = dbus.String(
                    mode)
                settings._settings['802-11-wireless']['band'] = dbus.String(
                    band)
                SSID = []
                for c in params["nm.wifi.ssid"]:
                    SSID.append(dbus.Byte(int(ord(c))))
                settings._settings['802-11-wireless']['ssid'] = dbus.Array(
                    SSID, signature='y')

                if "802-11-wireless-security" in settings._settings:
                    try:
                        xbmc.log(a[1] + " 802-11-wireless-security old: " +
                                 str(settings.
                                     _settings['802-11-wireless-security']))
                    except:
                        syslog.syslog(
                            a[1] + " 802-11-wireless-security old: " +
                            str(settings._settings['802-11-wireless-security'])
                        )
                else:
                    if key_mgmt != "":
                        settings._settings[
                            '802-11-wireless-security'] = dbus.Dictionary(
                                signature='sv')

                # clear 802-11-wireless-security settings
                # settings._settings['802-11-wireless-security'] = dbus.Dictionary(signature='sv')
                if key_mgmt == "" and "802-11-wireless-security" in settings._settings:
                    del (settings._settings['802-11-wireless-security'])
                    CONFIG_DIFFERENCE = True

                if key_mgmt != "":
                    settings._settings['802-11-wireless-security'][
                        'security'] = dbus.String(security)
                settings._settings['802-11-wireless-security'][
                    'key-mgmt'] = dbus.String(key_mgmt)
                if key_mgmt == "none":
                    settings._settings['802-11-wireless-security'][
                        'auth-alg'] = dbus.String(auth_alg)
                    if len(params["nm.wifi.key"]) > 0:
                        settings._settings['802-11-wireless-security'][
                            'wep-key0'] = dbus.String(params["nm.wifi.key"])
                        settings._settings['802-11-wireless-security'][
                            'wep-key1'] = dbus.String(params["nm.wifi.key"])
                else:
                    if len(params["nm.wifi.key"]) > 0:
                        settings._settings['802-11-wireless-security'][
                            'psk'] = dbus.String(params["nm.wifi.key"])

            if not "ipv6" in settings._settings:
                settings._settings['ipv6'] = dbus.Dictionary(signature='sv')
            settings._settings['ipv6']['method'] = dbus.String("ignore")

            if "ipv4" in settings._settings:
                try:
                    xbmc.log(a[1] + " ipv4 old: " +
                             str(settings._settings['ipv4']))
                except:
                    syslog.syslog(a[1] + " ipv4 old: " +
                                  str(settings._settings['ipv4']))
            else:
                settings._settings['ipv4'] = dbus.Dictionary(signature='sv')

            DHCP = False
            if a[1] == type2desc[1] and params['nm.dhcp'] == "true":
                DHCP = True
            if a[1] == type2desc[2] and params['nm.wifi.dhcp'] == "true":
                DHCP = True
            if DHCP:
                settings.set_auto()
                if params['nm.uid.enable'] == "true":
                    mac_list = settings.mac_address.split(":")
                    uid = "xbmc-" + mac_list[4].lower() + mac_list[5].lower()
                else:
                    uid = "xbmc"
                settings._settings['ipv4']['dhcp-client-id'] = dbus.String(uid)
                settings._settings['ipv4']['dhcp-hostname'] = dbus.String(uid)
                settings._settings['ipv4'][
                    'dhcp-send-hostname'] = dbus.Boolean(1)
            else:
                if not 'addresses' in settings._settings['ipv4']:
                    settings._settings['ipv4']['addresses'] = dbus.Array(
                        [], signature='au')
                settings.address = address
                settings.netmask = netmask
                settings.gateway = gateway
                settings.dns = dns
                settings._settings['ipv4']['dns-search'] = dbus.Array(
                    [dns_search], signature='s')

            #conn.proxy.Update(settings._settings, dbus_interface=NM_SETTINGS_CONNECTION)
            if old_settings != str(settings._settings):
                try:
                    xbmc.log(str(settings.type))
                    if "ipv4" in settings._settings:
                        xbmc.log(a[1] + "ipv4 new: " +
                                 str(settings._settings['ipv4']))
                    if "802-11-wireless" in settings._settings:
                        xbmc.log(a[1] + "802-11-wireless: " +
                                 str(settings._settings['802-11-wireless']))
                    if "802-11-wireless-security" in settings._settings:
                        xbmc.log(a[1] + "802-11-wireless-security: " + str(
                            settings._settings['802-11-wireless-security']))
                except:
                    syslog.syslog(str(settings.type))
                    if "ipv4" in settings._settings:
                        syslog.syslog(a[1] + "ipv4 new: " +
                                      str(settings._settings['ipv4']))
                    if "802-11-wireless" in settings._settings:
                        syslog.syslog(
                            a[1] + "802-11-wireless new: " +
                            str(settings._settings['802-11-wireless']))
                    if "802-11-wireless-security" in settings._settings:
                        syslog.syslog(
                            a[1] + "802-11-wireless-security new: " +
                            str(settings._settings['802-11-wireless-security'])
                        )
                conn.update(settings)
                # return 10 if settings need to update
                RETURN_CODE = 10
            else:
                # return 0 if settings do not need to update
                RETURN_CODE = 0

    return RETURN_CODE
Exemplo n.º 7
0
    def test_login_mutual_auth(self):
        self._set_initiator_name(
        )  # set initiator name to the one set in targetcli config

        manager = self.get_object('/Manager')
        nodes, _ = manager.DiscoverSendTargets(
            self.address,
            self.port,
            self.no_options,
            dbus_interface=self.iface_prefix + '.Manager.ISCSI.Initiator')

        node = next((node for node in nodes if node[0] == self.mutual_iqn),
                    None)
        self.assertIsNotNone(node)

        (iqn, tpg, host, port, iface) = node
        self.assertEqual(iqn, self.mutual_iqn)
        self.assertEqual(host, self.address)
        self.assertEqual(port, self.port)

        options = dbus.Dictionary(signature='sv')
        options['username'] = self.initiator
        options['password'] = self.password
        options['reverse-username'] = self.mutual_iqn
        options['reverse-password'] = self.mutual_password

        self.addCleanup(self._force_lougout, self.mutual_iqn)
        manager.Login(iqn,
                      tpg,
                      host,
                      port,
                      iface,
                      options,
                      dbus_interface=self.iface_prefix +
                      '.Manager.ISCSI.Initiator')

        devs = glob.glob('/dev/disk/by-path/*%s*' % iqn)
        self.assertEqual(len(devs), 1)

        # check if the block device have 'Symlinks' property updated
        disk_name = os.path.realpath(devs[0]).split('/')[-1]
        disk_obj = self.get_object('/block_devices/' + disk_name)
        dbus_path = str(disk_obj.object_path)
        self.assertIsNotNone(disk_obj)

        symlinks = self.get_property_raw(disk_obj, '.Block', 'Symlinks')
        self.assertIn(self.str_to_ay(devs[0]), symlinks)

        manager.Logout(iqn,
                       tpg,
                       host,
                       port,
                       iface,
                       self.no_options,
                       dbus_interface=self.iface_prefix +
                       '.Manager.ISCSI.Initiator')

        devs = glob.glob('/dev/disk/by-path/*%s*' % iqn)
        self.assertEqual(len(devs), 0)

        # make sure the disk is no longer on dbus
        udisks = self.get_object('')
        objects = udisks.GetManagedObjects(
            dbus_interface='org.freedesktop.DBus.ObjectManager')
        self.assertNotIn(dbus_path, objects.keys())
Exemplo n.º 8
0
    def test_open(self):

        # O_ACCMODE is node defined in Python 2 version of 'os' module
        try:
            from os import O_ACCMODE
        except ImportError:
            O_ACCMODE = 3

        # format the disk
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        disk.Format('xfs',
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')

        self.addCleanup(self.wipe_fs, self.vdevs[0])

        # OpenForBackup
        dbus_fd = disk.OpenForBackup(self.no_options,
                                     dbus_interface=self.iface_prefix +
                                     '.Block')
        self.assertIsNotNone(dbus_fd)

        fd = dbus_fd.take()
        mode = fcntl.fcntl(fd, fcntl.F_GETFL) & O_ACCMODE
        self.assertEqual(mode, os.O_RDONLY)
        os.close(fd)

        # OpenForRestore
        dbus_fd = disk.OpenForRestore(self.no_options,
                                      dbus_interface=self.iface_prefix +
                                      '.Block')
        self.assertIsNotNone(dbus_fd)

        fd = dbus_fd.take()
        mode = fcntl.fcntl(fd, fcntl.F_GETFL) & O_ACCMODE
        self.assertEqual(mode, os.O_WRONLY)
        os.close(fd)

        # OpenForBenchmark
        dbus_fd = disk.OpenForBenchmark(self.no_options,
                                        dbus_interface=self.iface_prefix +
                                        '.Block')
        self.assertIsNotNone(dbus_fd)

        fd = dbus_fd.take()
        mode = fcntl.fcntl(fd, fcntl.F_GETFL)
        self.assertTrue(bool(mode & os.O_DIRECT))
        self.assertTrue(bool(mode & os.O_SYNC))
        os.close(fd)

        # OpenDevice
        with self.assertRaises(dbus.exceptions.DBusException):  # invalid mode
            disk.OpenDevice('abc',
                            self.no_options,
                            dbus_interface=self.iface_prefix + '.Block')

        d = dbus.Dictionary(signature='sv')
        d['flags'] = os.O_RDWR
        with self.assertRaises(dbus.exceptions.DBusException
                               ):  # read-only mode with O_RDWR flag
            disk.OpenDevice('r',
                            d,
                            dbus_interface=self.iface_prefix + '.Block')

        d = dbus.Dictionary(signature='sv')
        d['flags'] = os.O_ASYNC | os.O_DIRECT
        dbus_fd = disk.OpenDevice('w',
                                  d,
                                  dbus_interface=self.iface_prefix + '.Block')
        self.assertIsNotNone(dbus_fd)

        fd = dbus_fd.take()
        mode = fcntl.fcntl(fd, fcntl.F_GETFL)
        self.assertTrue(bool(mode & os.O_WRONLY))
        self.assertTrue(bool(mode & os.O_DIRECT))
        self.assertTrue(bool(mode & os.O_ASYNC))
        os.close(fd)
Exemplo n.º 9
0
    def test_format(self):

        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # this might fail in case of stray udev rules or records in /etc/fstab
        hint_auto = self.get_property_raw(disk, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(False))
        hint_ignore = self.get_property_raw(disk, '.Block', 'HintIgnore')
        self.assertEqual(hint_ignore, dbus.Boolean(False))
        hint_partitionable = self.get_property_raw(disk, '.Block',
                                                   'HintPartitionable')
        self.assertEqual(hint_partitionable, dbus.Boolean(True))
        hint_system = self.get_property_raw(disk, '.Block', 'HintSystem')
        self.assertEqual(hint_system, dbus.Boolean(True))

        # create xfs filesystem
        disk.Format('xfs',
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')

        usage = self.get_property(disk, '.Block', 'IdUsage')
        usage.assertEqual('filesystem')

        fstype = self.get_property(disk, '.Block', 'IdType')
        fstype.assertEqual('xfs')

        hint_auto = self.get_property_raw(disk, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(False))
        hint_ignore = self.get_property_raw(disk, '.Block', 'HintIgnore')
        self.assertEqual(hint_ignore, dbus.Boolean(False))
        hint_partitionable = self.get_property_raw(disk, '.Block',
                                                   'HintPartitionable')
        self.assertEqual(hint_partitionable, dbus.Boolean(True))
        hint_system = self.get_property_raw(disk, '.Block', 'HintSystem')
        self.assertEqual(hint_system, dbus.Boolean(True))

        _ret, sys_fstype = self.run_command('lsblk -d -no FSTYPE %s' %
                                            self.vdevs[0])
        self.assertEqual(sys_fstype, 'xfs')

        # remove the format
        d = dbus.Dictionary(signature='sv')
        d['erase'] = True
        disk.Format('empty', d, dbus_interface=self.iface_prefix + '.Block')

        # check if the disk is empty
        usage = self.get_property(disk, '.Block', 'IdUsage')
        usage.assertEqual('')

        fstype = self.get_property(disk, '.Block', 'IdType')
        fstype.assertEqual('')

        hint_auto = self.get_property_raw(disk, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(False))
        hint_ignore = self.get_property_raw(disk, '.Block', 'HintIgnore')
        self.assertEqual(hint_ignore, dbus.Boolean(False))
        hint_partitionable = self.get_property_raw(disk, '.Block',
                                                   'HintPartitionable')
        self.assertEqual(hint_partitionable, dbus.Boolean(True))
        hint_system = self.get_property_raw(disk, '.Block', 'HintSystem')
        self.assertEqual(hint_system, dbus.Boolean(True))

        _ret, sys_fstype = self.run_command('lsblk -d -no FSTYPE %s' %
                                            self.vdevs[0])
        self.assertEqual(sys_fstype, '')
Exemplo n.º 10
0
 def reply(data):
     dbus_async_cb(
         dbus.Dictionary(data, signature='sv', variant_level=4))
Exemplo n.º 11
0
 def GetFacts(self, sender=None):
     collection = self.facts_collector.collect()
     cleaned = dict([(str(key), str(value))
                     for key, value in list(collection.data.items())])
     return dbus.Dictionary(cleaned, signature="ss")
Exemplo n.º 12
0
 def __add_connection(self, ssid):
     debug("Adding connection: " + ssid)
     server_alt_subject_name_list = dbus.Array(Config.servers)
     server_name = Config.server_match
     if self.nm_version == "0.9" or self.nm_version == "1.0":
         match_key = 'altsubject-matches'
         match_value = server_alt_subject_name_list
     else:
         match_key = 'subject-match'
         match_value = server_name
     s_8021x_data = {
         'eap': [Config.eap_outer.lower()],
         'identity':
         self.user_data.username,
         'ca-cert':
         dbus.ByteArray("file://{0}\0".format(
             self.cacert_file).encode('utf8')),
         match_key:
         match_value
     }
     if Config.eap_outer == 'PEAP' or Config.eap_outer == 'TTLS':
         s_8021x_data['password'] = self.user_data.password
         s_8021x_data['phase2-auth'] = Config.eap_inner.lower()
         if Config.anonymous_identity != '':
             s_8021x_data['anonymous-identity'] = Config.anonymous_identity
         s_8021x_data['password-flags'] = 0
     if Config.eap_outer == 'TLS':
         s_8021x_data['client-cert'] = dbus.ByteArray("file://{0}\0".format(
             self.pfx_file).encode('utf8'))
         s_8021x_data['private-key'] = dbus.ByteArray("file://{0}\0".format(
             self.pfx_file).encode('utf8'))
         s_8021x_data['private-key-password'] = self.user_data.password
         s_8021x_data['private-key-password-flags'] = 0
     s_con = dbus.Dictionary({
         'type':
         '802-11-wireless',
         'uuid':
         str(uuid.uuid4()),
         'permissions': ['user:'******'USER')],
         'id':
         ssid
     })
     s_wifi = dbus.Dictionary({
         'ssid': dbus.ByteArray(ssid.encode('utf8')),
         'security': '802-11-wireless-security'
     })
     s_wsec = dbus.Dictionary({
         'key-mgmt': 'wpa-eap',
         'proto': ['rsn'],
         'pairwise': ['ccmp'],
         'group': ['ccmp', 'tkip']
     })
     s_8021x = dbus.Dictionary(s_8021x_data)
     s_ip4 = dbus.Dictionary({'method': 'auto'})
     s_ip6 = dbus.Dictionary({'method': 'auto'})
     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
     })
     self.settings.AddConnection(con)
def test(q, bus, mc):
    params = dbus.Dictionary({"account": "*****@*****.**",
        "password": "******"}, signature='sv')
    simulated_cm, account = create_fakecm_account(q, bus, mc, params)
    conn = enable_fakecm_account(q, bus, mc, account, params)

    text_fixed_properties = dbus.Dictionary({
        cs.CHANNEL + '.TargetHandleType': cs.HT_CONTACT,
        cs.CHANNEL + '.ChannelType': cs.CHANNEL_TYPE_TEXT,
        }, signature='sv')
    vague_fixed_properties = dbus.Dictionary({
        cs.CHANNEL + '.ChannelType': cs.CHANNEL_TYPE_TEXT,
        }, signature='sv')

    empathy_bus = dbus.bus.BusConnection()
    q.attach_to_bus(empathy_bus)
    empathy = SimulatedClient(q, empathy_bus, 'Empathy',
            observe=[text_fixed_properties], approve=[text_fixed_properties],
            handle=[text_fixed_properties], bypass_approval=False)

    # Kopete's filter is less specific than Empathy's, so we'll prefer Empathy
    kopete_bus = dbus.bus.BusConnection()
    q.attach_to_bus(kopete_bus)
    kopete = SimulatedClient(q, kopete_bus, 'Kopete',
            observe=[], approve=[],
            handle=[vague_fixed_properties], bypass_approval=False)

    # wait for MC to download the properties
    expect_client_setup(q, [empathy, kopete])

    # subscribe to the OperationList interface (MC assumes that until this
    # property has been retrieved once, nobody cares)

    cd = bus.get_object(cs.CD, cs.CD_PATH)
    cd_props = dbus.Interface(cd, cs.PROPERTIES_IFACE)
    assert cd_props.Get(cs.CD_IFACE_OP_LIST, 'DispatchOperations') == []

    channel_properties = dbus.Dictionary(text_fixed_properties,
            signature='sv')
    channel_properties[cs.CHANNEL + '.TargetID'] = 'juliet'
    channel_properties[cs.CHANNEL + '.TargetHandle'] = \
            conn.ensure_handle(cs.HT_CONTACT, 'juliet')
    channel_properties[cs.CHANNEL + '.InitiatorID'] = 'juliet'
    channel_properties[cs.CHANNEL + '.InitiatorHandle'] = \
            conn.ensure_handle(cs.HT_CONTACT, 'juliet')
    channel_properties[cs.CHANNEL + '.Requested'] = False
    channel_properties[cs.CHANNEL + '.Interfaces'] = dbus.Array(signature='s')

    chan = SimulatedChannel(conn, channel_properties)
    chan.announce()

    # A channel dispatch operation is created

    e = q.expect('dbus-signal',
            path=cs.CD_PATH,
            interface=cs.CD_IFACE_OP_LIST,
            signal='NewDispatchOperation')

    cdo_path = e.args[0]
    cdo_properties = e.args[1]

    assert cdo_properties[cs.CDO + '.Account'] == account.object_path
    assert cdo_properties[cs.CDO + '.Connection'] == conn.object_path
    assert cs.CDO + '.Interfaces' in cdo_properties

    # In this test Empathy's filter has more things in it than Kopete's, so
    # MC will prefer Empathy
    handlers = cdo_properties[cs.CDO + '.PossibleHandlers'][:]
    assert handlers == [cs.tp_name_prefix + '.Client.Empathy',
            cs.tp_name_prefix + '.Client.Kopete'], handlers

    assert cs.CD_IFACE_OP_LIST in cd_props.Get(cs.CD, 'Interfaces')
    assert cd_props.Get(cs.CD_IFACE_OP_LIST, 'DispatchOperations') ==\
            [(cdo_path, cdo_properties)]

    cdo = bus.get_object(cs.CD, cdo_path)
    cdo_iface = dbus.Interface(cdo, cs.CDO)
    cdo_props_iface = dbus.Interface(cdo, cs.PROPERTIES_IFACE)

    assert cdo_props_iface.Get(cs.CDO, 'Interfaces') == \
            cdo_properties[cs.CDO + '.Interfaces']
    assert cdo_props_iface.Get(cs.CDO, 'Connection') == conn.object_path
    assert cdo_props_iface.Get(cs.CDO, 'Account') == account.object_path
    assert cdo_props_iface.Get(cs.CDO, 'Channels') == [(chan.object_path,
        channel_properties)]
    assert cdo_props_iface.Get(cs.CDO, 'PossibleHandlers') == \
            cdo_properties[cs.CDO + '.PossibleHandlers']

    e = q.expect('dbus-method-call',
            path=empathy.object_path,
            interface=cs.OBSERVER, method='ObserveChannels',
            handled=False)
    assert e.args[0] == account.object_path, e.args
    assert e.args[1] == conn.object_path, e.args
    assert e.args[3] == cdo_path, e.args
    assert e.args[4] == [], e.args      # no requests satisfied
    channels = e.args[2]
    assert len(channels) == 1, channels
    assert channels[0][0] == chan.object_path, channels
    assert channels[0][1] == channel_properties, channels

    q.dbus_return(e.message, bus=empathy_bus, signature='')

    e = q.expect('dbus-method-call',
            path=empathy.object_path,
            interface=cs.APPROVER, method='AddDispatchOperation',
            handled=False)

    assert e.args == [[(chan.object_path, channel_properties)],
            cdo_path, cdo_properties]

    q.dbus_return(e.message, bus=empathy_bus, signature='')

    call_async(q, cdo_iface, 'HandleWith',
            cs.tp_name_prefix + '.Client.Empathy')

    # Empathy is asked to handle the channels
    e = q.expect('dbus-method-call',
            path=empathy.object_path,
            interface=cs.HANDLER, method='HandleChannels',
            handled=False)

    # Empathy rejects the channels
    q.dbus_raise(e.message, cs.NOT_AVAILABLE, 'Blind drunk', bus=empathy_bus)

    e = q.expect('dbus-error', method='HandleWith')
    assert e.error.get_dbus_name() == cs.NOT_AVAILABLE
    assert e.error.get_dbus_message() == 'Blind drunk'

    # The channels no longer count as having been approved. Check that MC
    # doesn't carry on regardless
    forbidden = [EventPattern('dbus-method-call', method='HandleChannels')]
    q.forbid_events(forbidden)
    sync_dbus(bus, q, mc)
    q.unforbid_events(forbidden)

    # I'm Feeling Lucky. It might work if I try again? Maybe?
    call_async(q, cdo_iface, 'HandleWith',
            cs.tp_name_prefix + '.Client.Empathy')

    # Empathy is asked to handle the channels, again
    e = q.expect('dbus-method-call',
            path=empathy.object_path,
            interface=cs.HANDLER, method='HandleChannels',
            handled=False)

    # Empathy rejects the channels, again
    q.dbus_raise(e.message, cs.NOT_CAPABLE, 'Still drunk', bus=empathy_bus)

    e = q.expect('dbus-error', method='HandleWith')
    assert e.error.get_dbus_name() == cs.NOT_CAPABLE
    assert e.error.get_dbus_message() == 'Still drunk'

    # OK, OK, is anyone else competent enough to handle them?
    # (Also, assert that MC doesn't offer them back to Empathy, knowing that
    # it already tried and failed)
    forbidden = [EventPattern('dbus-method-call', method='HandleChannels',
        path=empathy.object_path)]
    q.forbid_events(forbidden)
    call_async(q, cdo_iface, 'HandleWith', '')

    # Kopete is asked to handle the channels
    k = q.expect('dbus-method-call',
                path=kopete.object_path,
                interface=cs.HANDLER, method='HandleChannels',
                handled=False)

    # Kopete rejects the channels too
    q.dbus_raise(k.message, cs.NOT_AVAILABLE, 'Also blind drunk',
            bus=kopete_bus)

    e = q.expect('dbus-error', method='HandleWith')

    assert e.error.get_dbus_name() == cs.NOT_AVAILABLE
    assert e.error.get_dbus_message() == 'Also blind drunk'

    # MC gives up and closes the channel. This is the end of the CDO.
    q.expect_many(
            EventPattern('dbus-method-call', path=chan.object_path,
                interface=cs.CHANNEL, method='Close', args=[]),
            EventPattern('dbus-signal', interface=cs.CDO, signal='Finished'),
            EventPattern('dbus-signal', interface=cs.CD_IFACE_OP_LIST,
                signal='DispatchOperationFinished'),
            )

    # Now there are no more active channel dispatch operations
    assert cd_props.Get(cs.CD_IFACE_OP_LIST, 'DispatchOperations') == []
Exemplo n.º 14
0
# both old and new versions of NetworkManager. Compare
# add-connection.py, which only supports NM 1.0 and later.
#
# Configuration settings are described at
# https://developer.gnome.org/NetworkManager/1.0/ref-settings.html
#

import socket, struct, dbus, uuid


def ip_to_int(ip_string):
    return struct.unpack("=I", socket.inet_aton(ip_string))[0]


# full duplex
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":
Exemplo n.º 15
0
 def py2_dbus_dictionary(self, setting_dict):
     return dbus.Dictionary(setting_dict, signature = dbus.Signature('sv'))
Exemplo n.º 16
0
    def test_configuration_fstab(self):

        # this test will change /etc/fstab, we might want to revert the changes when it finishes
        fstab = self.read_file('/etc/fstab')
        self.addCleanup(self.write_file, '/etc/fstab', fstab)

        # format the disk
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        disk.Format('xfs',
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')

        # cleanup -- remove format
        self.addCleanup(self.wipe_fs, self.vdevs[0])

        # configuration items as arrays of dbus.Byte
        mnt = self.str_to_ay('/mnt/test')
        fstype = self.str_to_ay('xfs')
        opts = self.str_to_ay('defaults')

        # set the new configuration
        conf = dbus.Dictionary(
            {
                'dir': mnt,
                'type': fstype,
                'opts': opts,
                'freq': 0,
                'passno': 0
            },
            signature=dbus.Signature('sv'))
        disk.AddConfigurationItem(('fstab', conf),
                                  self.no_options,
                                  dbus_interface=self.iface_prefix + '.Block')

        # get the configuration
        old_conf = self.get_property(disk, '.Block', 'Configuration')
        old_conf.assertTrue()
        self.assertEqual(old_conf.value[0][1]['dir'], mnt)
        self.assertEqual(old_conf.value[0][1]['type'], fstype)
        self.assertEqual(old_conf.value[0][1]['opts'], opts)
        self.assertEqual(old_conf.value[0][1]['passno'], 0)
        self.assertEqual(old_conf.value[0][1]['freq'], 0)

        # update the configuration
        new_opts = self.str_to_ay('defaults,noauto')
        new_conf = copy.deepcopy(old_conf.value)
        new_conf[0][1]['opts'] = new_opts

        disk.UpdateConfigurationItem(
            (old_conf.value[0][0], old_conf.value[0][1]),
            (new_conf[0][0], new_conf[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        # get the configuration after the update
        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertTrue()
        upd_conf.assertEqual(new_opts, getter=lambda c: c[0][1]['opts'])

        # this might fail in case of stray udev rules or records in /etc/fstab
        hint_auto = self.get_property_raw(disk, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(False))
        hint_ignore = self.get_property_raw(disk, '.Block', 'HintIgnore')
        self.assertEqual(hint_ignore, dbus.Boolean(False))
        hint_partitionable = self.get_property_raw(disk, '.Block',
                                                   'HintPartitionable')
        self.assertEqual(hint_partitionable, dbus.Boolean(True))
        hint_system = self.get_property_raw(disk, '.Block', 'HintSystem')
        self.assertEqual(hint_system, dbus.Boolean(True))

        # remove the configuration
        disk.RemoveConfigurationItem(
            (upd_conf.value[0][0], upd_conf.value[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertFalse()
Exemplo n.º 17
0
class UdisksTestCase(unittest.TestCase):
    iface_prefix = None
    path_prefix = None
    bus = None
    vdevs = None
    distro = (None, None, None)       # (project, distro_name, version)
    no_options = dbus.Dictionary(signature="sv")


    @classmethod
    def setUpClass(self):
        self.iface_prefix = 'org.freedesktop.UDisks2'
        self.path_prefix = '/org/freedesktop/UDisks2'
        self.bus = dbus.SystemBus()

        self.distro = get_version()

        self._orig_call_async = self.bus.call_async
        self._orig_call_blocking = self.bus.call_blocking
        self.bus.call_async = get_call_long(self._orig_call_async)
        self.bus.call_blocking = get_call_long(self._orig_call_blocking)
        self.vdevs = test_devs
        assert len(self.vdevs) > 3;


    @classmethod
    def tearDownClass(self):
        self.bus.call_async = self._orig_call_async
        self.bus.call_blocking = self._orig_call_blocking


    def run(self, *args):
        record = []
        now = datetime.now()
        now_mono = monotonic()
        with open(FLIGHT_RECORD_FILE, "a") as record_f:
            record_f.write("================%s[%0.8f] %s.%s.%s================\n" % (now.strftime('%Y-%m-%d %H:%M:%S'),
                                                                                     now_mono,
                                                                                     self.__class__.__module__,
                                                                                     self.__class__.__name__,
                                                                                     self._testMethodName))
            with JournalRecorder("journal", record):
                with CmdFlightRecorder("udisksctl monitor", ["udisksctl", "monitor"], record):
                    with CmdFlightRecorder("udevadm monitor", ["udevadm", "monitor"], record):
                        super(UdisksTestCase, self).run(*args)
            record_f.write("".join(record))
        self.udev_settle()

    @classmethod
    def get_object(self, path_suffix):
        # if given full path, just use it, otherwise prepend the prefix
        if path_suffix.startswith(self.path_prefix):
            path = path_suffix
        else:
            path = self.path_prefix + path_suffix
        try:
            # self.iface_prefix is the same as the DBus name we acquire
            obj = self.bus.get_object(self.iface_prefix, path)
        except:
            obj = None
        return obj

    @classmethod
    def get_interface(self, obj, iface_suffix):
        """Get interface for the given object either specified by an object path suffix
        (appended to the common UDisks2 prefix) or given as the object
        itself.

        :param obj: object to get the interface for
        :type obj: str or dbus.proxies.ProxyObject
        :param iface_suffix: suffix appended to the common UDisks2 interface prefix
        :type iface_suffix: str

        """
        if isinstance(obj, str):
            obj = self.get_object(obj)
        return dbus.Interface(obj, self.iface_prefix + iface_suffix)


    @classmethod
    def get_property(self, obj, iface_suffix, prop):
        return DBusProperty(obj, self.iface_prefix + iface_suffix, prop)


    @classmethod
    def get_property_raw(self, obj, iface_suffix, prop):
        res = obj.Get(self.iface_prefix + iface_suffix, prop, dbus_interface=dbus.PROPERTIES_IFACE)
        return res

    @classmethod
    def get_device(self, dev_name):
        """Get block device object for a given device (e.g. "sda")"""
        dev = self.get_object('/block_devices/' + os.path.basename(dev_name))
        return dev

    @classmethod
    def get_drive_name(self, device):
        """Get drive name for the given block device object"""
        drive_name = self.get_property_raw(device, '.Block', 'Drive').split('/')[-1]
        return drive_name

    @classmethod
    def udev_settle(self):
        self.run_command('udevadm settle')

    @classmethod
    def wipe_fs(self, device):
        for _ in range(10):
            ret, _out = self.run_command('wipefs -a %s' % device)
            if ret == 0:
                return True
            time.sleep(1)

        return False

    @classmethod
    def read_file(self, filename):
        with open(filename, 'r') as f:
            content = f.read()
        return content


    @classmethod
    def write_file(self, filename, content, ignore_nonexistent=False):
        try:
            with open(filename, 'w') as f:
                f.write(content)
        except FileNotFoundError as e:
            if not ignore_nonexistent:
                raise e

    @classmethod
    def run_command(self, command):
        return run_command(command)

    @classmethod
    def check_module_loaded(self, module):
        manager_obj = self.get_object('/Manager')
        manager = self.get_interface(manager_obj, '.Manager')
        manager_intro = dbus.Interface(manager_obj, "org.freedesktop.DBus.Introspectable")
        intro_data = manager_intro.Introspect()
        modules_loaded = 'interface name="org.freedesktop.UDisks2.Manager.%s"' % module in intro_data

        if not modules_loaded:
            manager.EnableModules(dbus.Boolean(True))
            intro_data = manager_intro.Introspect()
            return 'interface name="org.freedesktop.UDisks2.Manager.%s"' % module in intro_data
        else:
            return True


    @classmethod
    def ay_to_str(self, ay):
        """Convert a bytearray (terminated with '\0') to a string"""

        return ''.join(chr(x) for x in ay[:-1])

    @classmethod
    def str_to_ay(self, string, terminate=True):
        """Convert a string to a bytearray (terminated with '\0')"""

        if terminate:
            string += '\0'

        return dbus.Array([dbus.Byte(ord(c)) for c in string],
                          signature=dbus.Signature('y'), variant_level=1)

    @classmethod
    def set_udev_property(self, device, prop, value):
        udev = GUdev.Client()
        dev = udev.query_by_device_file(device)
        serial = dev.get_property("ID_SERIAL")

        try:
            os.makedirs("/run/udev/rules.d/")
        except OSError:
            # already exists
            pass

        self.write_file("/run/udev/rules.d/99-udisks_test.rules",
                        'ENV{ID_SERIAL}=="%s", ENV{%s}="%s"\n' % (serial, prop, value))
        self.run_command("udevadm control --reload")
        uevent_path = os.path.join(dev.get_sysfs_path(), "uevent")
        self.write_file(uevent_path, "change\n")
        self.udev_settle()
        os.unlink("/run/udev/rules.d/99-udisks_test.rules")
        self.run_command("udevadm control --reload")

    @classmethod
    def assertHasIface(self, obj, iface):
        obj_intro = dbus.Interface(obj, "org.freedesktop.DBus.Introspectable")
        intro_data = obj_intro.Introspect()

        for _ in range(20):
            if ('interface name="%s"' % iface) in intro_data:
                return
            time.sleep(0.5)

        raise AssertionError("Object '%s' has no interface '%s'" % (obj.object_path, iface))

    def assertStartswith(self, val, prefix):
        if not val.startswith(prefix):
            raise AssertionError("'%s' does not start with '%s'" % (val, prefix))
Exemplo n.º 18
0
    def test_configuration_fstab_removable(self):

        # this test will change /etc/fstab, we might want to revert the changes when it finishes
        fstab = self.read_file('/etc/fstab')
        self.addCleanup(self.write_file, '/etc/fstab', fstab)

        # this might fail in case of stray udev rules or records in /etc/fstab
        hint_auto = self.get_property_raw(self.cd_device, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(True))
        hint_ignore = self.get_property_raw(self.cd_device, '.Block',
                                            'HintIgnore')
        self.assertEqual(hint_ignore, dbus.Boolean(False))
        hint_partitionable = self.get_property_raw(self.cd_device, '.Block',
                                                   'HintPartitionable')
        self.assertEqual(hint_partitionable, dbus.Boolean(True))
        hint_system = self.get_property_raw(self.cd_device, '.Block',
                                            'HintSystem')
        self.assertEqual(hint_system, dbus.Boolean(False))

        # configuration items as arrays of dbus.Byte
        mnt = self.str_to_ay('/mnt/test')
        fstype = self.str_to_ay('xfs')
        opts = self.str_to_ay('defaults')

        # set the new configuration
        conf = dbus.Dictionary(
            {
                'dir': mnt,
                'type': fstype,
                'opts': opts,
                'freq': 0,
                'passno': 0
            },
            signature=dbus.Signature('sv'))
        self.cd_device.AddConfigurationItem(
            ('fstab', conf),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        hint_auto = self.get_property_raw(self.cd_device, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(True))

        # get the configuration
        old_conf = self.get_property(self.cd_device, '.Block', 'Configuration')
        old_conf.assertTrue()

        # update the configuration
        new_opts = self.str_to_ay('defaults,noauto')
        new_conf = copy.deepcopy(old_conf.value)
        new_conf[0][1]['opts'] = new_opts

        self.cd_device.UpdateConfigurationItem(
            (old_conf.value[0][0], old_conf.value[0][1]),
            (new_conf[0][0], new_conf[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        # get the configuration after the update
        upd_conf = self.get_property(self.cd_device, '.Block', 'Configuration')
        upd_conf.assertTrue()
        upd_conf.assertEqual(new_opts, getter=lambda c: c[0][1]['opts'])

        # 'noauto' option specified, should be reflected in the HintAuto property
        hint_auto = self.get_property_raw(self.cd_device, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(False))

        # remove the configuration
        self.cd_device.RemoveConfigurationItem(
            (upd_conf.value[0][0], upd_conf.value[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        upd_conf = self.get_property(self.cd_device, '.Block', 'Configuration')
        upd_conf.assertFalse()

        hint_auto = self.get_property_raw(self.cd_device, '.Block', 'HintAuto')
        self.assertEqual(hint_auto, dbus.Boolean(True))
def test(q, bus, mc):
    params = dbus.Dictionary(
        {
            "account": "*****@*****.**",
            "password": "******"
        },
        signature='sv')
    simulated_cm, account = create_fakecm_account(q, bus, mc, params)
    conn = enable_fakecm_account(q, bus, mc, account, params)

    text_fixed_properties = dbus.Dictionary(
        {
            cs.CHANNEL + '.ChannelType': cs.CHANNEL_TYPE_TEXT,
            cs.CHANNEL + '.TargetHandleType': cs.HT_CONTACT,
        },
        signature='sv')

    # subscribe to the OperationList interface (MC assumes that until this
    # property has been retrieved once, nobody cares)

    cd = bus.get_object(cs.CD, cs.CD_PATH)
    cd_props = dbus.Interface(cd, cs.PROPERTIES_IFACE)
    assert cd_props.Get(cs.CD_IFACE_OP_LIST, 'DispatchOperations') == []

    client = SimulatedClient(q,
                             bus,
                             'Client',
                             observe=[text_fixed_properties],
                             approve=[text_fixed_properties],
                             handle=[],
                             bypass_approval=False)

    # wait for MC to download the properties
    expect_client_setup(q, [client])

    channel_properties = dbus.Dictionary(text_fixed_properties, signature='sv')
    channel_properties[cs.CHANNEL + '.TargetID'] = 'juliet'
    channel_properties[cs.CHANNEL + '.TargetHandle'] = \
            conn.ensure_handle(cs.HT_CONTACT, 'juliet')
    channel_properties[cs.CHANNEL + '.InitiatorID'] = 'juliet'
    channel_properties[cs.CHANNEL + '.InitiatorHandle'] = \
            conn.ensure_handle(cs.HT_CONTACT, 'juliet')
    channel_properties[cs.CHANNEL + '.Requested'] = False
    channel_properties[cs.CHANNEL + '.Interfaces'] = dbus.Array(signature='s')

    forbidden = [
        EventPattern('dbus-method-call', method='AddDispatchOperation'),
    ]
    q.forbid_events(forbidden)

    chan = SimulatedChannel(conn, channel_properties)
    chan.announce()

    e = q.expect('dbus-signal',
                 path=cs.CD_PATH,
                 interface=cs.CD_IFACE_OP_LIST,
                 signal='NewDispatchOperation')

    cdo_path = e.args[0]
    cdo_properties = e.args[1]

    assert cdo_properties[cs.CDO + '.Account'] == account.object_path
    assert cdo_properties[cs.CDO + '.Connection'] == conn.object_path
    assert cs.CDO + '.Interfaces' in cdo_properties

    handlers = cdo_properties[cs.CDO + '.PossibleHandlers'][:]
    assertEquals([], handlers)

    e = q.expect('dbus-method-call',
                 path=client.object_path,
                 interface=cs.OBSERVER,
                 method='ObserveChannels',
                 handled=False)

    sync_dbus(bus, q, mc)

    q.dbus_return(e.message, signature='')

    # now (but only now) MC kills the channel
    q.expect_many(
        EventPattern('dbus-signal', path=cdo_path, signal='Finished'),
        EventPattern('dbus-method-call',
                     path=chan.object_path,
                     method='Close',
                     handled=True),
    )

    # There are no active channel dispatch operations
    assert cd_props.Get(cs.CD_IFACE_OP_LIST, 'DispatchOperations') == []
Exemplo n.º 20
0
SupportedMimeTypes = [
    'audio/aac', 'audio/m4a', 'audio/mp3', 'audio/wav', 'audio/wma',
    'audio/x-ape', 'audio/x-flac', 'audio/x-ogg', 'audio/x-oggflac',
    'audio/x-vorbis'
]
BusName = 'org.mpris.MediaPlayer2.feeluown'
ObjectPath = '/org/mpris/MediaPlayer2'
AppInterface = 'org.mpris.MediaPlayer2'
PlayerInterface = 'org.mpris.MediaPlayer2.Player'
AppProperties = dbus.Dictionary(
    {
        'DesktopEntry': 'FeelUOwn',
        'Identity': 'feeluown',
        'CanQuit': False,
        'CanRaise': False,
        'HasTrackList': False,
        'SupportedUriSchemes': ['http', 'file', 'smb'],
        'SupportedMimeTypes': SupportedMimeTypes,
    },
    signature='sv')

logger = logging.getLogger(__name__)


def to_dbus_position(p):
    return dbus.Int64(p * 1000 * 1000)


def to_fuo_position(p):
    return p / 1000 / 1000
Exemplo n.º 21
0
def PropDict(mapping=()):
    return dbus.Dictionary(mapping, signature='sv')
Exemplo n.º 22
0
 def __init__(self, app, bus):
     super().__init__(bus, ObjectPath)
     self._app = app
     self._metadata = dbus.Dictionary({}, signature='sv', variant_level=1)
     self._old_position = dbus.Int64(0)
Exemplo n.º 23
0
 def add_service_data(self, uuid, data):
     if not self.service_data:
         self.service_data = dbus.Dictionary({}, signature="sv")
     self.service_data[uuid] = dbus.Array(data, signature="y")
Exemplo n.º 24
0
 def __get_filters_handler_cb(self):
     filter_dict = dbus.Dictionary({}, signature='sv')
     return dbus.Array([filter_dict], signature='a{sv}')
Exemplo n.º 25
0
    def test_configuration_fstab(self):

        # this test will change /etc/fstab, we might want to revert the changes when it finishes
        fstab = self.read_file('/etc/fstab')
        self.addCleanup(self.write_file, '/etc/fstab', fstab)

        # format the disk
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        disk.Format('xfs',
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')

        # cleanup -- remove format
        self.addCleanup(self._clean_format, disk)

        # configuration items as arrays of dbus.Byte
        mnt = self.str_to_ay('/mnt/test')
        fstype = self.str_to_ay('xfs')
        opts = self.str_to_ay('defaults')

        # set the new configuration
        conf = dbus.Dictionary(
            {
                'dir': mnt,
                'type': fstype,
                'opts': opts,
                'freq': 0,
                'passno': 0
            },
            signature=dbus.Signature('sv'))
        disk.AddConfigurationItem(('fstab', conf),
                                  self.no_options,
                                  dbus_interface=self.iface_prefix + '.Block')

        # get the configuration
        old_conf = self.get_property(disk, '.Block', 'Configuration')
        old_conf.assertTrue()
        self.assertEqual(old_conf.value[0][1]['dir'], mnt)
        self.assertEqual(old_conf.value[0][1]['type'], fstype)
        self.assertEqual(old_conf.value[0][1]['opts'], opts)
        self.assertEqual(old_conf.value[0][1]['passno'], 0)
        self.assertEqual(old_conf.value[0][1]['freq'], 0)

        # update the configuration
        new_opts = self.str_to_ay('defaults,noauto')
        new_conf = copy.deepcopy(old_conf.value)
        new_conf[0][1]['opts'] = new_opts

        disk.UpdateConfigurationItem(
            (old_conf.value[0][0], old_conf.value[0][1]),
            (new_conf[0][0], new_conf[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')
        time.sleep(5)

        # get the configuration after the update
        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertTrue()
        self.assertEqual(upd_conf.value[0][1]['opts'], new_opts)

        # remove the configuration
        disk.RemoveConfigurationItem(
            (upd_conf.value[0][0], upd_conf.value[0][1]),
            self.no_options,
            dbus_interface=self.iface_prefix + '.Block')

        upd_conf = self.get_property(disk, '.Block', 'Configuration')
        upd_conf.assertFalse()
Exemplo n.º 26
0
def _create_ds_entry(properties, filename, transfer_ownership=False):
    object_id = _get_data_store().create(dbus.Dictionary(properties), filename,
                                         transfer_ownership)
    return object_id
Exemplo n.º 27
0
def get_unique_values(key):
    """Returns a list with the different values a property has taken
    """
    empty_dict = dbus.Dictionary({}, signature='ss')
    return _get_datastore().get_uniquevaluesfor(key, empty_dict)
Exemplo n.º 28
0
INTERFACE = 'org.gajim.dbus.RemoteInterface'
OBJ_PATH = '/org/gajim/dbus/RemoteObject'
SERVICE = 'org.gajim.dbus'

# type mapping

# in most cases it is a utf-8 string
DBUS_STRING = dbus.String

# general type (for use in dicts, where all values should have the same type)
DBUS_BOOLEAN = dbus.Boolean
DBUS_DOUBLE = dbus.Double
DBUS_INT32 = dbus.Int32
# dictionary with string key and binary value
DBUS_DICT_SV = lambda: dbus.Dictionary({}, signature="sv")
# dictionary with string key and value
DBUS_DICT_SS = lambda: dbus.Dictionary({}, signature="ss")
# empty type (there is no equivalent of None on D-Bus, but historically gajim
# used 0 instead)
DBUS_NONE = lambda: dbus.Int32(0)


def get_dbus_struct(obj):
    """
    Recursively go through all the items and replace them with their casted dbus
    equivalents
    """
    if obj is None:
        return DBUS_NONE()
    if isinstance(obj, str):
import dbus

from servicetest import call_async, EventPattern, tp_name_prefix, unwrap
from gabbletest import exec_test, acknowledge_iq
import constants as cs
import ns

from twisted.words.xish import domish

import tubetestutil as t

sample_parameters = dbus.Dictionary(
    {
        's': 'hello',
        'ay': dbus.ByteArray(b'hello'),
        'u': dbus.UInt32(123),
        'i': dbus.Int32(-123),
    },
    signature='sv')


def test(q, bus, conn, stream):
    conn.Connect()

    properties = conn.GetAll(cs.CONN_IFACE_REQUESTS,
                             dbus_interface=cs.PROPERTIES_IFACE)
    assert properties.get('Channels') == [], properties['Channels']
    assert ({cs.CHANNEL_TYPE: cs.CHANNEL_TYPE_STREAM_TUBE,
             cs.TARGET_HANDLE_TYPE: cs.HT_CONTACT,
             },
             [cs.TARGET_HANDLE, cs.TARGET_ID, cs.STREAM_TUBE_SERVICE]
Exemplo n.º 30
0
    def test_mount_fstab(self):
        if not self._can_create:
            self.skipTest('Cannot create %s filesystem' % self._fs_name)

        if not self._can_mount:
            self.skipTest('Cannot mount %s filesystem' % self._fs_name)

        # this test will change /etc/fstab, we might want to revert the changes after it finishes
        fstab = self.read_file('/etc/fstab')
        self.addCleanup(self.write_file, '/etc/fstab', fstab)

        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create filesystem
        disk.Format(self._fs_name,
                    self.no_options,
                    dbus_interface=self.iface_prefix + '.Block')
        self.addCleanup(self._clean_format, self.vdevs[0])

        # create a tempdir
        tmp = tempfile.mkdtemp()
        self.addCleanup(self._rmtree, tmp)

        # configuration items as arrays of dbus.Byte
        mnt = self.str_to_ay(tmp)
        fstype = self.str_to_ay(self._fs_name)
        opts = self.str_to_ay('ro')

        # set the new configuration
        conf = dbus.Dictionary(
            {
                'dir': mnt,
                'type': fstype,
                'opts': opts,
                'freq': 0,
                'passno': 0
            },
            signature=dbus.Signature('sv'))
        disk.AddConfigurationItem(('fstab', conf),
                                  self.no_options,
                                  dbus_interface=self.iface_prefix + '.Block')

        # mount using fstab options
        disk.Mount(self.no_options,
                   dbus_interface=self.iface_prefix + '.Filesystem')
        self.addCleanup(self._unmount, self.vdevs[0])

        # dbus mountpoint
        dbus_mounts = self.get_property(disk, '.Filesystem', 'MountPoints')
        dbus_mounts.assertLen(1)  # just one mountpoint
        dbus_mnt = self.ay_to_str(
            dbus_mounts.value[0])  # mountpoints are arrays of bytes
        self.assertEqual(dbus_mnt, tmp)

        # system mountpoint
        self.assertTrue(os.path.ismount(tmp))

        _ret, out = self.run_command('mount | grep %s' % self.vdevs[0])
        self.assertIn(tmp, out)
        self.assertIn('ro', out)