def CreateContainer(self, display_name, container_type, child_types): upload_id = self.next_upload_id self.next_upload_id += 1 path = "{0}/up{1:03}".format(self.__dbus_object_path__, upload_id) upload = { 'ChildCount': dbus.UInt32(0), 'DisplayName': display_name, 'Parent': self.__dbus_object_path__, 'Path': path, 'Type': 'container', 'TypeEx': container_type, } self.items.append(upload) self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = self.items obj.AddTemplate("dleynamediaobject.py", filter_properties(upload, MEDIA_OBJECT2_PROPERTIES)) obj.AddTemplate("dleynamediacontainer.py", filter_properties(upload, MEDIA_CONTAINER2_PROPERTIES)) device = get_object( find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change({'ChangeType': CHANGE_TYPES['Add'], 'Path': path}) return (path)
def RemoveWifiConnection(self, dev_path, connection_path): '''Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) settings_obj = dbusmock.get_object(SETTINGS_OBJ) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') main_connections = settings_obj.ListConnections() if connection_path not in connections and connection_path not in main_connections: return connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.RemoveObject(connection_path)
def Upload(self, display_name, filename): upload_id = self.next_upload_id self.next_upload_id += 1 path = "{0}/up{1:03}".format(self.__dbus_object_path__, upload_id) size = os.stat(filename).st_size upload = { 'DisplayName': display_name, 'Parent': self.__dbus_object_path__, 'Path': path, 'UploadFilename': filename, 'UploadId': upload_id, 'UploadSize': size, } self.items.append(upload) self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = self.items obj.AddTemplate("dleynamediaobject.py", filter_properties(upload, MEDIA_OBJECT2_PROPERTIES)) device = get_object( find_root(self.items, self.__dbus_object_path__)['Path']) def upload_completed(): device.EmitSignal(MEDIA_DEVICE_IFACE, 'UploadUpdate', 'ustt', (upload_id, 'COMPLETED', size, size)) device.queue_change({'ChangeType': CHANGE_TYPES['Add'], 'Path': path}) GLib.idle_add(upload_completed) item = find_item(self.items, self.__dbus_object_path__) item['ChildCount'] += 1 return (upload_id, path)
def ConnectionDelete(self): '''Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If this was the only active connection, we change the global connection state. ''' connection_path = self.connection_path NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) # Find the associated active connection(s). active_connections = NM.Get(MAIN_IFACE, 'ActiveConnections') associated_active_connections = [] for ac in active_connections: ac_obj = dbusmock.get_object(ac) ac_con = ac_obj.Get(ACTIVE_CONNECTION_IFACE, 'Connection') if ac_con == connection_path: associated_active_connections.append(ac) # We found that the connection we are deleting are associated to all # active connections and subsequently set the global state to # disconnected. if len(active_connections) == len(associated_active_connections): self.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTED) # Remove the connection from all associated devices. # We also remove all associated active connections. for dev_path in NM.GetDevices(): dev_obj = dbusmock.get_object(dev_path) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') for ac in associated_active_connections: NM.RemoveActiveConnection(dev_path, ac) if connection_path not in connections: continue connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) # Remove the connection from the settings interface main_connections = settings_obj.ListConnections() if connection_path not in main_connections: return main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) # Remove the connection from the mock connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.RemoveObject(connection_path)
def AddPartitionDevice(self, device_name): """ Just a testing method """ # add a disk path = "/org/freedesktop/UDisks2/block_devices/" + device_name block_properties = { 'Device': dbus.ByteArray("/dev/" + device_name + "\000"), 'Id': "by-id-scsi-0QEMU_QEMU_HARDDISK_drive-scsi0-0-0-0", } self.AddObject(path, BLOCK_IFACE, block_properties, []) obj = dbusmock.get_object(path) partition_properties = { 'Test': 'hello world ' + device_name, } obj.AddProperties(PARTITION_IFACE, partition_properties) manager = dbusmock.get_object(MAIN_OBJ) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), { BLOCK_IFACE: block_properties} # PARTITION_IFACE: partition_properties, # }, ]) print >> sys.stderr, "sending event on", path return path
def UploadToAnyContainer(self, display_name, filename): upload_id = self.next_upload_id self.next_upload_id += 1 path = '{0}/any{1:03}'.format(self.__dbus_object_path__, upload_id) size = os.stat(filename).st_size upload = { 'DisplayName': display_name, 'Parent': self.__dbus_object_path__, 'Path': path, 'Type': 'item.unclassified', 'UploadFilename': filename, 'UploadId': upload_id, 'UploadSize': size, } self.items.append(upload) self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = self.items obj.AddTemplate('dleynamediaobject.py', filter_properties(upload, MEDIA_OBJECT2_PROPERTIES)) device = get_object(find_root(self.items, self.__dbus_object_path__)['Path']) def upload_completed(): device.EmitSignal(MAIN_IFACE, 'UploadUpdate', 'ustt', (upload_id, 'COMPLETED', size, size)) self.queue_change ({ 'ChangeType': CHANGE_TYPES['Add'], 'Path': path }) GLib.idle_add(upload_completed) return (upload_id, path)
def CreateContainer(self, display_name, container_type, child_types): upload_id = self.next_upload_id self.next_upload_id += 1 path = "{0}/up{1:03}".format(self.__dbus_object_path__, upload_id) upload = { 'ChildCount': dbus.UInt32(0), 'DisplayName': display_name, 'Parent': self.__dbus_object_path__, 'Path': path, 'Type': 'container', 'TypeEx': container_type, } self.items.append(upload) self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = self.items obj.AddTemplate("dleynamediaobject.py", filter_properties(upload, MEDIA_OBJECT2_PROPERTIES)) obj.AddTemplate("dleynamediacontainer.py", filter_properties(upload, MEDIA_CONTAINER2_PROPERTIES)) device = get_object(find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change ({ 'ChangeType': CHANGE_TYPES['Add'], 'Path': path }) return (path)
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit https://developer.gnome.org/NetworkManager/unstable/nm-dbus-types.html#NMDeviceState Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, WIRELESS_DEVICE_IFACE, { 'HwAddress': dbus.String('11:22:33:44:55:66'), 'PermHwAddress': dbus.String('11:22:33:44:55:66'), 'Bitrate': dbus.UInt32(5400), 'Mode': dbus.UInt32(2), 'WirelessCapabilities': dbus.UInt32(255), 'AccessPoints': dbus.Array([], signature='o'), }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ('GetAllAccessPoints', '', 'ao', 'ret = self.access_points'), ('RequestScan', 'a{sv}', '', ''), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties(DEVICE_IFACE, { 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'DeviceType': dbus.UInt32(2), 'State': dbus.UInt32(state), 'StateReason': (dbus.UInt32(state), dbus.UInt32(0)), 'Interface': iface_name, 'IpInterface': iface_name, }) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
def get_device_by_ip_iface(_self, iface): NM = dbusmock.get_object(MANAGER_OBJ) for dev_path in NM.GetDevices(): dev_obj = dbusmock.get_object(dev_path) interface = dev_obj.Get(DEVICE_IFACE, 'Interface') if interface == iface: return dev_path return None
def ConnectionUpdate(self, connection_path, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) conn_obj = dbusmock.get_object(connection_path) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MAIN_IFACE + '.DoesNotExist', ) conn_settings = conn_obj.Get(CSETTINGS_IFACE, 'Settings') changed_settings = {} for key, value in settings.items(): for k, v in value.items(): changed_settings[k] = v if key not in conn_settings: conn_settings[key] = dbus.Dictionary({}, signature='sv') conn_settings[key][k] = v conn_obj.Set(CSETTINGS_IFACE, 'Settings', conn_settings) settings_obj.EmitSignal(CSETTINGS_IFACE, 'PropertiesChanged', 'a{sv}', [changed_settings]) settings_obj.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def ConnectionUpdate(self, connection_path, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) conn_obj = dbusmock.get_object(connection_path) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MAIN_IFACE + '.DoesNotExist',) conn_settings = conn_obj.Get(CSETTINGS_IFACE, 'Settings') changed_settings = {} for key, value in settings.items(): for k, v in value.items(): changed_settings[k] = v if key not in conn_settings: conn_settings[key] = dbus.Dictionary({}, signature='sv') conn_settings[key][k] = v conn_obj.Set(CSETTINGS_IFACE, 'Settings', conn_settings) settings_obj.EmitSignal(CSETTINGS_IFACE, 'PropertiesChanged', 'a{sv}', [changed_settings]) settings_obj.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path. ''' conn_obj = dbusmock.get_object(connection_device) settings = conn_obj.settings conn_uuid = settings['connection']['uuid'] conn_type = settings['connection']['type'] conn_id = settings['connection']['id'] device_objects = [dbus.ObjectPath(dev) for dev in devices] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self.AddObject(active_connection_path, ACTIVE_CONNECTION_IFACE, { 'Devices': dbus.Array(device_objects, signature='o'), 'Default6': False, 'Default': True, 'Type': conn_type, 'Vpn': (conn_type == 'vpn'), 'Connection': dbus.ObjectPath(connection_device), 'Master': dbus.ObjectPath('/'), 'SpecificObject': dbus.ObjectPath(specific_object), 'Uuid': conn_uuid, 'State': dbus.UInt32(state), 'Id': conn_id, }, []) for dev_path in devices: self.SetDeviceActive(dev_path, active_connection_path) self.object_manager_emit_added(active_connection_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') active_connections.append(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) return active_connection_path
def AddServer(self): root = '/com/intel/dLeynaServer/server/%d' % (self.next_server_id,) # Pre-process the items tree anchoring paths to the new root object items = copy.deepcopy(ITEMS) for item in items: item['Path'] = dbus.ObjectPath(item['Path'].replace('{root}', root)) item['Parent'] = dbus.ObjectPath(item['Parent'].replace('{root}', root)) for item in items: path = item['Path'] self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = items if path == root: item['FriendlyName'] = 'Mock Server <#{0}>'.format(self.next_server_id) item['UDN'] = str(uuid.uuid5(uuid.UUID('9123ef5c-f083-11e2-8000-000000000000'), str(self.next_server_id))) obj.AddTemplate("dleynamediadevice.py", filter_properties (item, MEDIA_DEVICE_PROPERTIES)) obj.AddTemplate("dleynamediaobject.py", filter_properties(item, MEDIA_OBJECT2_PROPERTIES)) obj.AddTemplate("dleynamediacontainer.py", filter_properties(item, MEDIA_CONTAINER2_PROPERTIES)) self.servers.append(root) self.EmitSignal(MAIN_IFACE, 'FoundServer', 'o', [root]) self.next_server_id += 1 return path
def SetModemOffline(_self, index): '''Convenience method to change a modem's state from online to offline. index: the modem to update Calling this methof will trigger the modem's PropertiesChanged signal. ''' modem = dbusmock.get_object( f'/org/freedesktop/ModemManager1/Modem/{index}') properties = { 'Sim': dbus.ObjectPath('/'), 'UnlockRequired': dbus.UInt32(0), 'UnlockRetries': dbus.Dictionary({}, signature='uu'), 'State': dbus.Int32(-1), 'StateFailedReason': dbus.UInt32(2), 'AccessTechnologies': dbus.UInt32(0), 'SignalQuality': (dbus.UInt32(0), True), 'OwnNumbers': dbus.Array([], signature='s'), 'CurrentModes': (dbus.UInt32(4294967295), dbus.UInt32(0)), 'CurrentBands': dbus.Array([0], signature='u'), } for name, value in properties.items(): modem._set_property(MODEM_IFACE, name, value) modem.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [MODEM_IFACE, properties, []])
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = {'Carrier': dbus.Boolean(0, variant_level=1), 'HwAddress': dbus.String("78:DD:08:D2:3D:43", variant_level=1), 'PermHwAddress': dbus.String("78:DD:08:D2:3D:43", variant_level=1), 'Speed': dbus.UInt32(0, variant_level=1)} self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = {'DeviceType': dbus.UInt32(1, variant_level=1), 'State': dbus.UInt32(state, variant_level=1), 'Interface': dbus.String(iface_name, variant_level=1), 'IpInterface': dbus.String('', variant_level=1)} obj = dbusmock.get_object(path) obj.AddProperties('org.freedesktop.NetworkManager.Device', props) return path
def SetDeviceActive(self, device_path, active_connection_path): dev_obj = dbusmock.get_object(device_path) dev_obj.Set(DEVICE_IFACE, 'ActiveConnection', dbus.ObjectPath(active_connection_path)) old_state = dev_obj.Get(DEVICE_IFACE, 'State') dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.ACTIVATED)) dev_obj.EmitSignal(DEVICE_IFACE, 'StateChanged', 'uuu', [dbus.UInt32(DeviceState.ACTIVATED), old_state, dbus.UInt32(1)])
def SetDeviceDisconnected(self, device_path): dev_obj = dbusmock.get_object(device_path) dev_obj.Set(DEVICE_IFACE, 'ActiveConnection', dbus.ObjectPath('/')) old_state = dev_obj.Get(DEVICE_IFACE, 'State') dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.DISCONNECTED)) dev_obj.EmitSignal(DEVICE_IFACE, 'StateChanged', 'uuu', [dbus.UInt32(DeviceState.DISCONNECTED), old_state, dbus.UInt32(1)])
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit connection uuid or timestamp, this method adds one for you. Note that this automatically associates the connection settings object with the first device that was created. ''' NM = dbusmock.get_object(MAIN_OBJ) devices = NM.GetDevices() dev = None auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] # Grab the first device if we are to auto-connect if auto_connect and len(devices) > 0: dev = devices[0] connection_path = self.AddDeviceConnection(dev, connection_settings) if auto_connect and dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def SetDeviceActive(self, device_path, active_connection_path, ip_address='192.168.0.1'): dev_obj = dbusmock.get_object(device_path) dev_obj.Set(DEVICE_IFACE, 'ActiveConnection', dbus.ObjectPath(active_connection_path)) old_state = dev_obj.Get(DEVICE_IFACE, 'State') dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.ACTIVATED)) dev_obj.EmitSignal( DEVICE_IFACE, 'StateChanged', 'uuu', [dbus.UInt32(DeviceState.ACTIVATED), old_state, dbus.UInt32(1)]) ip4_config_path = '/org/freedesktop/NetworkManager/IP4Config/0' self.AddObject( ip4_config_path, IP4_CONFIG_IFACE, { 'AddressData': dbus.Array([{ 'address': dbus.String(ip_address), 'prefix': dbus.UInt32(24) }], signature='a{sv}') }, []) dev_obj.Set(DEVICE_IFACE, 'Ip4Config', dbus.ObjectPath(ip4_config_path))
def AddServer(self): root = '/com/intel/dLeynaServer/server/%d' % (self.next_server_id, ) # Pre-process the items tree anchoring paths to the new root object items = copy.deepcopy(ITEMS) for item in items: item['Path'] = dbus.ObjectPath(item['Path'].replace('{root}', root)) item['Parent'] = dbus.ObjectPath(item['Parent'].replace( '{root}', root)) for item in items: path = item['Path'] self.AddObject(path, 'org.gnome.UPnP.MediaObject2', {}, []) obj = get_object(path) obj.items = items if path == root: item['FriendlyName'] = 'Mock Server <#{0}>'.format( self.next_server_id) item['UDN'] = str( uuid.uuid5(uuid.UUID('9123ef5c-f083-11e2-8000-000000000000'), str(self.next_server_id))) obj.AddTemplate("dleynamediadevice.py", filter_properties(item, MEDIA_DEVICE_PROPERTIES)) obj.AddTemplate("dleynamediaobject.py", filter_properties(item, MEDIA_OBJECT2_PROPERTIES)) obj.AddTemplate("dleynamediacontainer.py", filter_properties(item, MEDIA_CONTAINER2_PROPERTIES)) self.servers.append(root) self.EmitSignal(MAIN_IFACE, 'FoundServer', 'o', [root]) self.next_server_id += 1 return path
def set_hotspot_enabled(self, value): self.SetProperty(NETS_OBJ, NETS_IFACE, 'HotspotEnabled', value) # Set HotspotStored = True if not stored and we're enabling it. stored = dbusmock.get_object(NETS_OBJ).Get(NETS_IFACE, 'HotspotStored') if value and not bool(stored): self.SetProperty(NETS_OBJ, NETS_IFACE, 'HotspotStored', True)
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = { 'Carrier': False, 'HwAddress': dbus.String('78:DD:08:D2:3D:43'), 'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'), 'Speed': dbus.UInt32(0) } self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = { 'DeviceType': dbus.UInt32(1), 'State': dbus.UInt32(state), 'Interface': iface_name, 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'IpInterface': '' } obj = dbusmock.get_object(path) obj.AddProperties(DEVICE_IFACE, props) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
def SettingsGetConnectionByUuid(self, conn_uuid): conns = self.ListConnections() for o in conns: self.conn = dbusmock.get_object(o) settings = self.conn.GetSettings() if settings['connection']['uuid'] == conn_uuid: return o raise dbus.exceptions.DBusException("There was no connection with uuid %s" % conn_uuid)
def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MANAGER_IFACE + '.DoesNotExist', ) # Take care not to overwrite the secrets for setting_name in settings: setting = settings[setting_name] for k in setting: if setting_name not in self.settings: self.settings[setting_name] = {} self.settings[setting_name][k] = setting[k] self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MAIN_IFACE + '.DoesNotExist',) # Take care not to overwrite the secrets for setting_name in settings: setting = settings[setting_name] for k in setting: if setting_name not in self.settings: self.settings[setting_name] = {} self.settings[setting_name][k] = setting[k] self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def Logout(self, logout_type): # only Normal logout is supported in this mock assert logout_type == 0 for path in dbusmock.get_objects(): if 'MockClientPrivate/' in path: obj = dbusmock.get_object(path) obj.EmitSignal(CLIENT_PRIVATE_IFACE, 'EndSession', 'u', [0]) obj.EmitSignal(CLIENT_PRIVATE_IFACE, 'Stop', '', [])
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, WIRELESS_DEVICE_IFACE, { 'HwAddress': dbus.String('11:22:33:44:55:66'), 'PermHwAddress': dbus.String('11:22:33:44:55:66'), 'Bitrate': dbus.UInt32(5400), 'Mode': dbus.UInt32(2), 'WirelessCapabilities': dbus.UInt32(255), 'AccessPoints': dbus.Array([], signature='o'), }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ('GetAllAccessPoints', '', 'ao', 'ret = self.access_points'), ('RequestScan', 'a{sv}', '', ''), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties(DEVICE_IFACE, { 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'DeviceType': dbus.UInt32(2), 'State': dbus.UInt32(state), 'Interface': iface_name, 'IpInterface': iface_name, }) devices = self.Get(MAIN_IFACE, 'Devices') devices.append(path) self.Set(MAIN_IFACE, 'Devices', devices) self.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
def auth_session_process(self, params, method): auth_service = dbusmock.get_object(MAIN_OBJ) if self.identity in auth_service.auth_replies: return auth_service.auth_replies[self.identity] if 'errorName' in params: raise dbus.exceptions.DBusException('Authentication error', name=params['errorName']) if 'delay' in params: time.sleep(params['delay']) return params
def Update(self, to_add_update, to_delete): item = find_item(self.items, self.__dbus_object_path__) for prop in to_delete: del item[prop] for prop, val in to_add_update.items(): item[prop] = val device = get_object(find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change ({ 'ChangeType': CHANGE_TYPES['Mod'], 'Path': self.__dbus_object_path__ })
def Delete(self): device = get_object(find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change ({ 'ChangeType': CHANGE_TYPES['Del'], 'Path': self.__dbus_object_path__ }) item = find_item(self.items, self.__dbus_object_path__) self.items.remove(item) parent = find_item(self.items, item['Parent']) parent['ChildCount'] -= 1
def get_identity(self, identity): if identity not in self.identities: raise dbus.exceptions.DBusException('Identity not found', name=ERROR_IDENTITY_NOT_FOUND) path = '/Identity%s' % identity if not path in dbusmock.get_objects(): self.AddObject(path, IDENTITY_IFACE, {}, [('getInfo', '', 'a{sv}', 'ret = self.parent.identities[%s]' % identity)]) identity_obj = dbusmock.get_object(path) identity_obj.parent = self return (path, self.identities[identity])
def load(mock, parameters): manager_props = {'ActiveConnections': dbus.Array([], signature='o'), 'Devices': dbus.Array([], signature='o'), 'NetworkingEnabled': parameters.get('NetworkingEnabled', True), 'Connectivity': parameters.get('Connectivity', dbus.UInt32(NMConnectivityState.NM_CONNECTIVITY_FULL)), 'State': parameters.get('State', dbus.UInt32(NMState.NM_STATE_CONNECTED_GLOBAL)), 'Startup': False, 'Version': parameters.get('Version', '0.9.6.0'), 'WimaxEnabled': parameters.get('WimaxEnabled', True), 'WimaxHardwareEnabled': parameters.get('WimaxHardwareEnabled', True), 'WirelessEnabled': parameters.get('WirelessEnabled', True), 'WirelessHardwareEnabled': parameters.get('WirelessHardwareEnabled', True), 'WwanEnabled': parameters.get('WwanEnabled', False), 'WwanHardwareEnabled': parameters.get('WwanHardwareEnabled', True)} manager_methods = [('GetDevices', '', 'ao', 'ret = [k for k in objects.keys() if "/Devices" in k]'), ('GetPermissions', '', 'a{ss}', 'ret = {}'), ('state', '', 'u', "ret = self.Get('%s', 'State')" % MANAGER_IFACE), ('CheckConnectivity', '', 'u', "ret = self.Get('%s', 'Connectivity')" % MANAGER_IFACE), ('ActivateConnection', 'ooo', 'o', "ret = self.activate_connection(self, args[0], args[1], args[2])"), ('DeactivateConnection', 'o', '', "self.deactivate_connection(self, args[0])"), ('AddAndActivateConnection', 'a{sa{sv}}oo', 'oo', 'ret = self.add_and_activate_connection(self, args[0], args[1], args[2])'), ('GetDeviceByIpIface', 's', 'o', 'ret = self.get_device_by_ip_iface(self, args[0])'), ('Reload', 'u', '', ''), ('Enable', 'b', '', 'self.set_networking_enabled(self, args[0])')] mock.AddObject(MANAGER_OBJ, MANAGER_IFACE, manager_props, manager_methods) mock.object_manager_emit_added(MANAGER_OBJ) obj = dbusmock.get_object(MANAGER_OBJ) obj.activate_connection = activate_connection obj.deactivate_connection = deactivate_connection obj.add_and_activate_connection = add_and_activate_connection obj.get_device_by_ip_iface = get_device_by_ip_iface obj.set_networking_enabled = set_networking_enabled settings_props = {'Hostname': 'hostname', 'CanModify': True, 'Connections': dbus.Array([], signature='o')} settings_methods = [('ListConnections', '', 'ao', "ret = self.Get('%s', 'Connections')" % SETTINGS_IFACE), ('GetConnectionByUuid', 's', 'o', 'ret = self.SettingsGetConnectionByUuid(args[0])'), ('AddConnection', 'a{sa{sv}}', 'o', 'ret = self.SettingsAddConnection(args[0])'), ('AddConnectionUnsaved', 'a{sa{sv}}', 'o', 'ret = self.SettingsAddConnection(args[0])'), ('SaveHostname', 's', '', '')] mock.AddObject(SETTINGS_OBJ, SETTINGS_IFACE, settings_props, settings_methods) mock.object_manager_emit_added(SETTINGS_OBJ)
def SetDeviceProperties(_self, object_path, properties): '''Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. Changing this property will trigger the device's PropertiesChanged signal. ''' device = dbusmock.get_object(object_path) # set the properties for key, value in properties.items(): device.Set(DEVICE_IFACE, key, value)
def Update(self, to_add_update, to_delete): item = find_item(self.items, self.__dbus_object_path__) for prop in to_delete: del item[prop] for prop, val in to_add_update.items(): item[prop] = val device = get_object( find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change({ 'ChangeType': CHANGE_TYPES['Mod'], 'Path': self.__dbus_object_path__ })
def Delete(self): device = get_object( find_root(self.items, self.__dbus_object_path__)['Path']) device.queue_change({ 'ChangeType': CHANGE_TYPES['Del'], 'Path': self.__dbus_object_path__ }) item = find_item(self.items, self.__dbus_object_path__) self.items.remove(item) parent = find_item(self.items, item['Parent']) parent['ChildCount'] -= 1
def add_and_activate_connection(self, conn_conf, dev, ap): name = ap.rsplit('/', 1)[1] RemoveWifiConnection(self, dev, '/org/freedesktop/NetworkManager/Settings/' + name) try: raw_ssid = ''.join([chr(byte) for byte in conn_conf["802-11-wireless"]["ssid"]]) except KeyError: raw_ssid = dbusmock.get_object(ap).props['org.freedesktop.NetworkManager.AccessPoint']['Ssid'].decode() wifi_conn = dbus.ObjectPath(AddWiFiConnection(self, dev, name, raw_ssid, "")) active_conn = activate_connection(self, wifi_conn, dev, ap) return (wifi_conn, active_conn)
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html# org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal( WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path] ) return ap_path
def activate_connection(self, conn, dev, ap): # find a new name count = 0 dev_obj = dbusmock.get_object(dev) dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.ACTIVATED)) active_connections = dbusmock.get_object(MANAGER_OBJ).Get( MANAGER_IFACE, 'ActiveConnections') while True: path = dbus.ObjectPath( '/org/freedesktop/NetworkManager/ActiveConnection/' + str(count)) if path not in active_connections: break count += 1 state = dbus.UInt32( NMActiveConnectionState.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) devices = [] if str(dev) != '/': devices.append(dev) active_conn = dbus.ObjectPath( AddActiveConnection(self, devices, conn, ap, str(count), state)) return active_conn
def AddUdevObject(self, path, interfaces): first = True for iface in interfaces: (name, propcode, methcode) = iface props = eval(propcode) methods = eval(methcode) if first: first = False self.AddObject(path, name, props, methods) obj = dbusmock.get_object(path) else: obj.AddProperties(name, props) obj.AddMethods(name, methods)
def add_openvpn_object(mock, path): obj = dbusmock.get_object(path) obj.AddProperties( VPN_CONN_OPENVPN_IFACE, { 'connectionType': dbus.UInt32(0), 'remote': dbus.String(), 'ca': dbus.String(), 'cert': dbus.String(), 'certPass': dbus.String(), 'key': dbus.String(), 'username': dbus.String(), 'password': dbus.String(), 'localIp': dbus.String(), 'remoteIp': dbus.String(), 'staticKey': dbus.String(), 'staticKeyDirection': dbus.UInt32(0), 'portSet': dbus.Boolean(False), 'port': dbus.UInt32(1194), 'renegSecondsSet': dbus.Boolean(False), 'renegSeconds': dbus.UInt32(0), 'compLzo': dbus.Boolean(False), 'protoTcp': dbus.Boolean(False), 'devTypeSet': dbus.Boolean(False), 'devType': dbus.UInt32(0), 'dev': dbus.String(), 'tunnelMtuSet': dbus.Boolean(False), 'tunnelMtu': dbus.UInt32(1500), 'fragmentSizeSet': dbus.Boolean(False), 'fragmentSize': dbus.UInt32(1300), 'mssFix': dbus.Boolean(False), 'remoteRandom': dbus.Boolean(False), 'cipher': dbus.UInt32(0), 'keysizeSet': dbus.Boolean(False), 'keysize': dbus.UInt32(128), 'auth': dbus.UInt32(0), 'tlsRemote': dbus.String(), 'remoteCertTlsSet': dbus.Boolean(False), 'remoteCertTls': dbus.UInt32(0), 'taSet': dbus.Boolean(False), 'ta': dbus.String(), 'taDir': dbus.UInt32(0), 'proxyType': dbus.UInt32(), 'proxyServer': dbus.String(), 'proxyPort': dbus.UInt32(80), 'proxyRetry': dbus.Boolean(False), 'proxyUsername': dbus.String(), 'proxyPassword': dbus.String(), })
def get_auth_session_object_path(self, identity, method): if identity != 0 and (identity not in self.identities): raise dbus.exceptions.DBusException('Identity not found', name=ERROR_IDENTITY_NOT_FOUND) path = '/AuthSession%s' % self.sessions_counter self.sessions_counter += 1 self.AddObject(path, AUTH_SESSION_IFACE, {}, [ ('process', 'a{sv}s', 'a{sv}', 'ret = self.auth_session_process(self.identity, args[0], args[1])'), ]) auth_session = dbusmock.get_object(path) auth_session.auth_session_process = auth_session_process auth_session.identity = identity auth_session.method = method return path
def block(self, index, should_block): should_block = bool(should_block) if index not in type2objectname: return False objname = type2objectname[index] if should_block: new_block_state = 1 else: new_block_state = 0 if self.internal_states[objname] != new_block_state: path = '/org/freedesktop/URfkill/' + objname obj = dbusmock.get_object(path) self.internal_states[objname] = new_block_state obj.Set('org.freedesktop.URfkill.Killswitch', 'state', new_block_state) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) return True
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path]) return ap_path
def activate_connection(self, conn, dev, ap): # find a new name count = 0 active_connections = dbusmock.get_object(MAIN_OBJ).Get(MAIN_IFACE, 'ActiveConnections') while True: path = dbus.ObjectPath('/org/freedesktop/NetworkManager/ActiveConnection/' + str(count)) if path not in active_connections: break count += 1 state = dbus.UInt32(NMActiveConnectionState.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) devices = [] if str(dev) != '/': devices.append(dev) active_conn = dbus.ObjectPath(AddActiveConnection(self, devices, conn, ap, str(count), state)) return active_conn
def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path. ''' conn_obj = dbusmock.get_object(connection_device) settings = conn_obj.Get(CSETTINGS_IFACE, 'Settings') conn_uuid = settings['connection']['uuid'] conn_type = settings['connection']['type'] device_objects = [dbus.ObjectPath(dev) for dev in devices] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self.AddObject(active_connection_path, ACTIVE_CONNECTION_IFACE, { 'Devices': device_objects, 'Default6': False, 'Default': True, 'Type': conn_type, 'Vpn': (conn_type == 'vpn'), 'Connection': dbus.ObjectPath(connection_device), 'Master': dbus.ObjectPath('/'), 'SpecificObject': dbus.ObjectPath(specific_object), 'Uuid': conn_uuid, 'State': state, }, []) for dev_path in devices: self.SetDeviceActive(dev_path, active_connection_path) active_connections = self.Get(MAIN_IFACE, 'ActiveConnections') active_connections.append(dbus.ObjectPath(active_connection_path)) self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'ActiveConnections', active_connections) return active_connection_path
def toggle_flight_mode(self, new_block_state): new_block_state = bool(new_block_state) if self.flight_mode == new_block_state: return True self.flight_mode = new_block_state for i in individual_objects: old_value = self.internal_states[i] if old_value == 1: continue # It was already blocked so we don't need to do anything path = '/org/freedesktop/URfkill/' + i obj = dbusmock.get_object(path) if new_block_state: obj.Set('org.freedesktop.URfkill.Killswitch', 'state', 1) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) else: obj.Set('org.freedesktop.URfkill.Killswitch', 'state', 0) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) self.EmitSignal(MAIN_IFACE, 'FlightModeChanged', 'b', [self.flight_mode]) return True
def SetDeviceProperties(self, object_path, properties): """Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; otherwise, the older org.freedesktop.UPower DeviceChanged signal will be emitted. """ device = dbusmock.get_object(object_path) # set the properties for key, value in properties.items(): device.Set(DEVICE_IFACE, key, value) # notify the listeners if not self.api1: self.EmitSignal(MAIN_IFACE, "DeviceChanged", "s", [object_path])
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = {'Carrier': False, 'HwAddress': dbus.String('78:DD:08:D2:3D:43'), 'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'), 'Speed': dbus.UInt32(0)} self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = {'DeviceType': dbus.UInt32(1), 'State': dbus.UInt32(state), 'Interface': iface_name, 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'IpInterface': ''} obj = dbusmock.get_object(path) obj.AddProperties(DEVICE_IFACE, props) devices = self.Get(MAIN_IFACE, 'Devices') devices.append(path) self.Set(MAIN_IFACE, 'Devices', devices) self.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
def RemoveAccessPoint(self, dev_path, ap_path): '''Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.remove(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.access_points.remove(ap_path) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointRemoved', 'o', [ap_path]) self.RemoveObject(ap_path)
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wireless', { 'HwAddress': dbus.String('11:22:33:44:55:66', variant_level=1), 'PermHwAddress': dbus.String('11:22:33:44:55:66', variant_level=1), 'Bitrate': dbus.UInt32(5400, variant_level=1), 'Mode': dbus.UInt32(2, variant_level=1), 'WirelessCapabilities': dbus.UInt32(255, variant_level=1) }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties('org.freedesktop.NetworkManager.Device', { 'DeviceType': dbus.UInt32(2, variant_level=1), 'State': dbus.UInt32(state, variant_level=1), 'Interface': dbus.String(iface_name, variant_level=1), 'IpInterface': dbus.String(iface_name, variant_level=1) }) return path
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( MAIN_IFACE + '.AlreadyExists', 'Access point %s on device %s already exists' % (ap_name, dev_path)) self.AddObject(ap_path, 'org.freedesktop.NetworkManager.AccessPoint', { 'Ssid': dbus.ByteArray(ssid.encode('UTF-8'), variant_level=1), 'HwAddress': dbus.String(hw_address.encode('UTF-8'), variant_level=1), 'Flags': dbus.UInt32(1, variant_level=1), 'Frequency': dbus.UInt32(frequency, variant_level=1), 'MaxBitrate': dbus.UInt32(rate, variant_level=1), 'Mode': dbus.UInt32(mode, variant_level=1), 'RsnFlags': dbus.UInt32(324, variant_level=1), 'WpaFlags': dbus.UInt32(security, variant_level=1), 'Strength': dbus.Byte(strength, variant_level=1), }, []) dev_obj.access_points.append(ap_path) return ap_path
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'uuid' not in connection_settings['connection']: connection_settings['connection']['uuid'] = str(uuid.uuid4()) NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() # Mimic how NM names connections count = 0 while True: connection_obj_path = dbus.ObjectPath(SETTINGS_OBJ + '/' + str(count)) if connection_obj_path not in main_connections: break count += 1 connection_path = str(connection_obj_path) self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = connection_settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path]) auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access points. Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) connection_path = '/org/freedesktop/NetworkManager/Settings/' + connection_name connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() ssid = ssid_name.encode('UTF-8') # Find the access point by ssid access_point = None access_points = dev_obj.access_points for ap_path in access_points: ap = dbusmock.get_object(ap_path) if ap.Get(ACCESS_POINT_IFACE, 'Ssid') == ssid: access_point = ap break if not access_point: raise dbus.exceptions.DBusException( 'Access point with SSID [%s] could not be found' % (ssid_name), name=MAIN_IFACE + '.DoesNotExist') hw_address = access_point.Get(ACCESS_POINT_IFACE, 'HwAddress') mode = access_point.Get(ACCESS_POINT_IFACE, 'Mode') security = access_point.Get(ACCESS_POINT_IFACE, 'WpaFlags') if connection_path in connections or connection_path in main_connections: raise dbus.exceptions.DBusException( 'Connection %s on device %s already exists' % (connection_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') # Parse mac address string into byte array mac_bytes = binascii.unhexlify(hw_address.replace(':', '')) settings = { '802-11-wireless': { 'seen-bssids': [hw_address], 'ssid': dbus.ByteArray(ssid), 'mac-address': dbus.ByteArray(mac_bytes), 'mode': InfrastructureMode.NAME_MAP[mode] }, 'connection': { 'timestamp': dbus.UInt64(1374828522), 'type': '802-11-wireless', 'id': ssid_name, 'uuid': str(uuid.uuid4()) }, } if security != NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: settings['802-11-wireless']['security'] = '802-11-wireless-security' settings['802-11-wireless-security'] = NM80211ApSecurityFlags.NAME_MAP[security] self.AddObject(connection_path, CSETTINGS_IFACE, { 'Settings': dbus.Dictionary(settings, signature='sa{sv}'), 'Secrets': dbus.Dictionary({}, signature='sa{sv}'), }, [ ('Delete', '', '', 'self.ConnectionDelete("%s")' % connection_path), ('GetSettings', '', 'a{sa{sv}}', "ret = self.Get('%s', 'Settings')" % CSETTINGS_IFACE), ('GetSecrets', 's', 'a{sa{sv}}', "ret = self.Get('%s', 'Secrets')" % CSETTINGS_IFACE), ( 'Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate("%s", args[0])' % connection_path), ]) connections.append(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [ap_path]) return connection_path
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'uuid' not in connection_settings['connection']: connection_settings['connection']['uuid'] = str(uuid.uuid4()) NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() # Mimic how NM names connections connection_name = str(len(main_connections)) connection_path = SETTINGS_OBJ + '/' + connection_name if connection_path in main_connections: raise dbus.exceptions.DBusException( 'Connection %s already exists' % connection_path, name=MAIN_IFACE + '.AlreadyExists',) self.AddObject(connection_path, CSETTINGS_IFACE, { 'Settings': dbus.Dictionary(connection_settings, signature='sa{sv}'), 'Secrets': dbus.Dictionary({}, signature='sa{sv}'), }, [ ('Delete', '', '', 'self.ConnectionDelete("%s")' % connection_path), ( 'GetSettings', '', 'a{sa{sv}}', "ret = self.Get('%s', 'Settings')" % CSETTINGS_IFACE), ( 'GetSecrets', 's', 'a{sa{sv}}', "ret = self.Get('%s', 'Secrets')" % CSETTINGS_IFACE), ( 'Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate("%s", args[0])' % connection_path), ]) main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path]) auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
def deactivate_connection(self, active_conn_path): NM = dbusmock.get_object(MAIN_OBJ) for dev_path in NM.GetDevices(): RemoveActiveConnection(self, dev_path, active_conn_path)
def SetProperty(self, path, iface, name, value): obj = dbusmock.get_object(path) obj.Set(iface, name, value) obj.EmitSignal(iface, 'PropertiesChanged', 'a{sv}', [{name: value}])