def RequestPasskey(self, device): print("RequestPasskey (%s)" % (device)) set_trusted(device) passkey = ask("Enter passkey: ") return dbus.UInt32(passkey)
def SetGlobalConnectionState(self, state): self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'State', dbus.UInt32(state, variant_level=1)) self.EmitSignal(MAIN_IFACE, 'StateChanged', 'u', [state])
def to_dbus(klass, method, arg, val, signature): if arg in ('connection' 'properties') and signature == 'a{sa{sv}}': settings = copy.deepcopy(val) for key in settings: if 'mac-address' in settings[key]: settings[key]['mac-address'] = fixups.mac_to_dbus( settings[key]['mac-address']) if 'cloned-mac-address' in settings[key]: settings[key]['cloned-mac-address'] = fixups.mac_to_dbus( settings[key]['cloned-mac-address']) if 'bssid' in settings[key]: settings[key]['bssid'] = fixups.mac_to_dbus( settings[key]['bssid']) for cert in [ 'ca-cert', 'client-cert', 'phase2-ca-cert', 'phase2-client-cert', 'private-key' ]: if cert in settings[key]: settings[key][cert] = fixups.cert_to_dbus( settings[key][cert]) if 'ssid' in settings.get('802-11-wireless', {}): settings['802-11-wireless']['ssid'] = fixups.ssid_to_dbus( settings['802-11-wireless']['ssid']) if 'ipv4' in settings: if 'address-data' in settings['ipv4']: for item in settings['ipv4']['address-data']: item['prefix'] = dbus.UInt32(item['prefix']) settings['ipv4']['address-data'] = dbus.Array( settings['ipv4']['address-data'], signature=dbus.Signature('a{sv}')) if 'addresses' in settings['ipv4']: settings['ipv4']['addresses'] = [ fixups.addrconf_to_dbus(addr, socket.AF_INET) for addr in settings['ipv4']['addresses'] ] if 'routes' in settings['ipv4']: settings['ipv4']['routes'] = [ fixups.route_to_dbus(route, socket.AF_INET) for route in settings['ipv4']['routes'] ] if 'dns' in settings['ipv4']: settings['ipv4']['dns'] = [ fixups.addr_to_dbus(addr, socket.AF_INET) for addr in settings['ipv4']['dns'] ] if 'ipv6' in settings: if 'addresses' in settings['ipv6']: settings['ipv6']['addresses'] = [ fixups.addrconf_to_dbus(addr, socket.AF_INET6) for addr in settings['ipv6']['addresses'] ] if 'routes' in settings['ipv6']: settings['ipv6']['routes'] = [ fixups.route_to_dbus(route, socket.AF_INET6) for route in settings['ipv6']['routes'] ] if 'dns' in settings['ipv6']: settings['ipv6']['dns'] = [ fixups.addr_to_dbus(addr, socket.AF_INET6) for addr in settings['ipv6']['dns'] ] # Get rid of empty arrays/dicts. dbus barfs on them (can't guess # signatures), and if they were to get through, NetworkManager # ignores them anyway. for key in list(settings.keys()): if isinstance(settings[key], dict): for key2 in list(settings[key].keys()): if settings[key][key2] in ({}, []): del settings[key][key2] if settings[key] in ({}, []): del settings[key] val = settings return fixups.base_to_dbus(val)
def TransferOwnership(self, sesspath, new_uid): self.__manager_intf.TransferOwnership(dbus.ObjectPath(sesspath), dbus.UInt32(new_uid))
def handle(interface, protocol, name, type, domain, flags): if found[0]: return if regexp.match(name): found[0] = True server.ResolveService(interface, protocol, name, type, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler = handle2, error_handler = handle_error)
def set_discoverable_timeout(self, timeout): self.set_property("DiscoverableTimeout", dbus.UInt32(timeout))
def test(q, bus, conn, stream): # we don't yet know we have PEP assertEquals( 0, conn.Get(cs.CONN_IFACE_LOCATION, "SupportedLocationFeatures", dbus_interface=cs.PROPERTIES_IFACE)) conn.Connect() # discard activities request and status change q.expect_many( EventPattern('stream-iq', iq_type='set', query_ns=ns.PUBSUB), EventPattern('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]), ) # we now know we have PEP assertEquals( cs.LOCATION_FEATURE_CAN_SET, conn.Get(cs.CONN_IFACE_LOCATION, "SupportedLocationFeatures", dbus_interface=cs.PROPERTIES_IFACE)) # check location properties access_control_types = conn.Get(cs.CONN_IFACE_LOCATION, "LocationAccessControlTypes", dbus_interface=cs.PROPERTIES_IFACE) # only one access control is implemented in Gabble at the moment: assert len(access_control_types) == 1, access_control_types assert access_control_types[0] == \ Rich_Presence_Access_Control_Type_Publish_List access_control = conn.Get(cs.CONN_IFACE_LOCATION, "LocationAccessControl", dbus_interface=cs.PROPERTIES_IFACE) assert len(access_control) == 2, access_control assert access_control[0] == \ Rich_Presence_Access_Control_Type_Publish_List properties = conn.GetAll(cs.CONN_IFACE_LOCATION, dbus_interface=cs.PROPERTIES_IFACE) assert properties.get('LocationAccessControlTypes') == access_control_types assert properties.get('LocationAccessControl') == access_control # Test setting the properties # Enum out of range bad_access_control = dbus.Struct( [dbus.UInt32(99), dbus.UInt32(0, variant_level=1)], signature=dbus.Signature('uv')) try: conn.Set(cs.CONN_IFACE_LOCATION, 'LocationAccessControl', bad_access_control, dbus_interface=cs.PROPERTIES_IFACE) except dbus.DBusException as e: pass else: assert False, "Should have had an error!" # Bad type bad_access_control = dbus.String("This should not be a string") try: conn.Set(cs.CONN_IFACE_LOCATION, 'LocationAccessControl', bad_access_control, dbus_interface=cs.PROPERTIES_IFACE) except dbus.DBusException as e: assert e.get_dbus_name() == cs.INVALID_ARGUMENT, e.get_dbus_name() else: assert False, "Should have had an error!" # Bad type bad_access_control = dbus.Struct([ dbus.String("bad"), dbus.String("!"), dbus.UInt32(0, variant_level=1) ], signature=dbus.Signature('ssv')) try: conn.Set(cs.CONN_IFACE_LOCATION, 'LocationAccessControl', bad_access_control, dbus_interface=cs.PROPERTIES_IFACE) except dbus.DBusException as e: assert e.get_dbus_name() == cs.INVALID_ARGUMENT, e.get_dbus_name() else: assert False, "Should have had an error!" # Correct conn.Set(cs.CONN_IFACE_LOCATION, 'LocationAccessControl', access_control, dbus_interface=cs.PROPERTIES_IFACE) # LocationAccessControlTypes is read-only, check Gabble return the # PermissionDenied error try: conn.Set(cs.CONN_IFACE_LOCATION, 'LocationAccessControlTypes', access_control_types, dbus_interface=cs.PROPERTIES_IFACE) except dbus.DBusException as e: assert e.get_dbus_name() == cs.PERMISSION_DENIED, e.get_dbus_name() else: assert False, "Should have had an error!" date = dbus.Int64(time.time()) date_str = datetime.datetime.utcfromtimestamp(date).strftime( '%FT%H:%M:%SZ') # set a Location call_async( q, conn.Location, 'SetLocation', { 'lat': dbus.Double(0.0, variant_level=1), 'lon': 0.0, 'language': 'en', 'timestamp': date, 'country': 'Congo', 'accuracy': 1.4, # Gabble silently ignores unknown keys 'badger': 'mushroom' }) geoloc_iq_set_event = EventPattern( 'stream-iq', predicate=lambda x: xpath.queryForNodes( "/iq/pubsub/publish/item/geoloc", x.stanza)) event = q.expect_many(geoloc_iq_set_event)[0] geoloc = xpath.queryForNodes("/iq/pubsub/publish/item/geoloc", event.stanza)[0] assertEquals(geoloc.getAttribute((ns.XML, 'lang')), 'en') lon = xpath.queryForNodes('/geoloc/lon', geoloc)[0] assertEquals(float(str(lon)), 0.0) lat = xpath.queryForNodes('/geoloc/lat', geoloc)[0] assertEquals(float(str(lat)), 0.0) timestamp = xpath.queryForNodes('/geoloc/timestamp', geoloc)[0] assertEquals(str(timestamp), date_str) country = xpath.queryForNodes('/geoloc/country', geoloc)[0] assertEquals(str(country), 'Congo') lat = xpath.queryForNodes('/geoloc/accuracy', geoloc)[0] assertEquals(float(str(lat)), 1.4) acknowledge_iq(stream, event.stanza) q.expect('dbus-return', method='SetLocation') # Server refuses to set Location call_async(q, conn.Location, 'SetLocation', {'lat': 0.0, 'lon': 0.0}) geoloc_iq_set_event = EventPattern( 'stream-iq', predicate=lambda x: xpath.queryForNodes( "/iq/pubsub/publish/item/geoloc", x.stanza)) event = q.expect_many(geoloc_iq_set_event)[0] send_error_reply(stream, event.stanza) q.expect('dbus-error', method='SetLocation') # Request Bob's location bob_handle = conn.get_contact_handle_sync('*****@*****.**') # Gabble should not send a pubsub query. The point of PEP is that we don't # have to do this. pubsub_get_pattern = EventPattern('stream-iq', iq_type='get', query_ns=ns.PUBSUB) q.forbid_events([pubsub_get_pattern]) location = get_location(conn, bob_handle) # Location isn't known yet assertEquals(None, location) # Sync the XMPP stream to ensure Gabble hasn't sent a query. sync_stream(q, stream) # Bob updates his location message = elem('message', from_='*****@*****.**')( elem((ns.PUBSUB_EVENT), 'event')( elem('items', node=ns.GEOLOC)( elem('item', id='12345')( elem(ns.GEOLOC, 'geoloc', attrs={'xml:lang': 'en'})( elem('lat')(u'1.25'), elem('lon')(u'5.5'), elem('country')(u'Belgium'), elem('accuracy')(u'2.3'), elem('timestamp')(date_str), # invalid element, will be ignored by Gabble elem('badger')(u'mushroom'), ))))) stream.send(message) update_event = q.expect('dbus-signal', signal='LocationUpdated') handle, location = update_event.args assertEquals(bob_handle, handle) assertLength(6, location) assertEquals(location['language'], 'en') assertEquals(location['lat'], 1.25) assertEquals(location['lon'], 5.5) assertEquals(location['country'], 'Belgium') assertEquals(location['accuracy'], 2.3) assertEquals(location['timestamp'], date) # Get location again; Gabble should return the cached location loc = get_location(conn, bob_handle) assertEquals(loc, location) charles_handle = conn.get_contact_handle_sync('*****@*****.**') # check that Contacts interface supports location attributes = conn.Contacts.GetContactAttributes( [bob_handle, charles_handle], [cs.CONN_IFACE_LOCATION], False) assertLength(2, attributes) assertContains(bob_handle, attributes) assertContains(charles_handle, attributes) assertEquals( { cs.CONN_IFACE_LOCATION + '/location': location, cs.CONN + '/contact-id': '*****@*****.**' }, attributes[bob_handle]) assertEquals({cs.CONN + '/contact-id': '*****@*****.**'}, attributes[charles_handle]) # Try to set our location by passing a valid with an invalid type (lat is # supposed to be a double) q.forbid_events([geoloc_iq_set_event]) try: conn.Location.SetLocation({'lat': 'pony'}) except dbus.DBusException as e: assertEquals(e.get_dbus_name(), cs.INVALID_ARGUMENT) else: assert False # Bob updates his location again message = elem('message', from_='*****@*****.**')(elem( (ns.PUBSUB_EVENT), 'event')(elem('items', node=ns.GEOLOC)(elem('item', id='12345')(elem( ns.GEOLOC, 'geoloc')(elem('country')(u'France')))))) stream.send(message) update_event = q.expect('dbus-signal', signal='LocationUpdated') handle, location = update_event.args assertEquals(handle, bob_handle) assertLength(1, location) assertEquals(location['country'], 'France') # Now we test explicitly retrieving Bob's location, so we should not forbid # such queries. :) q.unforbid_events([pubsub_get_pattern]) call_async(q, conn.Location, 'RequestLocation', bob_handle) e = q.expect('stream-iq', iq_type='get', query_ns=ns.PUBSUB, to='*****@*****.**') # Hey, while we weren't looking Bob moved abroad! result = make_result_iq(stream, e.stanza) result['from'] = '*****@*****.**' pubsub_node = result.firstChildElement() pubsub_node.addChild( elem('items', node=ns.GEOLOC)(elem('item', id='12345')(elem( ns.GEOLOC, 'geoloc')(elem('country')(u'Chad'))))) stream.send(result) ret = q.expect('dbus-return', method='RequestLocation') location, = ret.value assertLength(1, location) assertEquals(location['country'], 'Chad') # Let's ask again; this time Bob's server hates us for some reason. call_async(q, conn.Location, 'RequestLocation', bob_handle) e = q.expect('stream-iq', iq_type='get', query_ns=ns.PUBSUB, to='*****@*****.**') send_error_reply(stream, e.stanza, elem('error', type='auth')(elem(ns.STANZA, 'forbidden'))) e = q.expect('dbus-error', method='RequestLocation') assertEquals(cs.PERMISSION_DENIED, e.name) # FIXME: maybe we should check that the cache gets invalidated in this # case? We should also test whether or not the cache is invalidated # properly if the contact clears their PEP node. # Let's ask a final time, and disconnect while we're doing so, to make sure # this doesn't break Gabble or Wocky. call_async(q, conn.Location, 'RequestLocation', bob_handle) e = q.expect('stream-iq', iq_type='get', query_ns=ns.PUBSUB, to='*****@*****.**') # Tasty argument unpacking. disconnect_conn returns two lists, one for # expeced_before=[] and one for expected_after=[...] _, (e, ) = disconnect_conn( q, conn, stream, expected_after=[EventPattern('dbus-error', method='RequestLocation')]) assertEquals(cs.CANCELLED, e.name)
def new_service_type(self, interface, protocol, stype, domain, flags): global service_browsers # Are we already browsing this domain for this type? if (interface, protocol, stype, domain) in service_browsers: return print("Browsing for services of type '%s' in domain '%s' on %i.%i ..." % (stype, domain, interface, protocol)) b = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceBrowserNew(interface, protocol, stype, domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) b.connect_to_signal('ItemNew', self.new_service) b.connect_to_signal('ItemRemove', self.remove_service) service_browsers[(interface, protocol, stype, domain)] = b
def browse_domain(self, interface, protocol, domain): global service_type_browsers # Are we already browsing this domain? if (interface, protocol, domain) in service_type_browsers: return if self.stype is None: print("Browsing domain '%s' on %i.%i ..." % (domain, interface, protocol)) try: b = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceTypeBrowserNew(interface, protocol, domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_TYPE_BROWSER) except DBusException as e: print(e) error_msg("You should check that the avahi daemon is running.\n\nError : %s" % e) sys.exit(0) b.connect_to_signal('ItemNew', self.new_service_type) service_type_browsers[(interface, protocol, domain)] = b else: self.new_service_type(interface, protocol, self.stype, domain)
def attempt_notify(self): ntype = self.ntype if self.kde_notifications: notification_text = ('<html><img src="%(image)s" align=left />' \ '%(title)s<br/>%(text)s</html>') % {'title': self.title, 'text': self.text, 'image': self.path_to_image} gajim_icon = gtkgui_helpers.get_icon_path('gajim', 48) try: self.notif.Notify( dbus.String(_('Gajim')), # app_name (string) dbus.UInt32(0), # replaces_id (uint) ntype, # event_id (string) dbus.String(gajim_icon), # app_icon (string) dbus.String(''), # summary (string) dbus.String(notification_text), # body (string) # actions (stringlist) (dbus.String('default'), dbus.String(self.event_type), dbus.String('ignore'), dbus.String(_('Ignore'))), [], # hints (not used in KDE yet) dbus.UInt32(self.timeout * 1000), # timeout (int), in ms reply_handler=self.attach_by_id, error_handler=self.notify_another_way) return except Exception: pass version = self.version if version[:2] == [0, 2]: actions = {} if 'actions' in self.capabilities and self.msg_type: actions = {'default': 0} try: self.notif.Notify(dbus.String(_('Gajim')), dbus.String(self.path_to_image), dbus.UInt32(0), ntype, dbus.Byte(0), dbus.String(self.title), dbus.String(self.text), [dbus.String(self.path_to_image)], actions, [''], True, dbus.UInt32(self.timeout), reply_handler=self.attach_by_id, error_handler=self.notify_another_way) except AttributeError: # we're actually dealing with the newer version version = [0, 3, 1] if version > [0, 3]: if gajim.interface.systray_enabled and \ gajim.config.get('attach_notifications_to_systray'): status_icon = gajim.interface.systray.status_icon rect = status_icon.get_geometry()[2] x, y, width, height = rect.x, rect.y, rect.width, rect.height pos_x = x + (width / 2) pos_y = y + (height / 2) hints = {'x': pos_x, 'y': pos_y} else: hints = {} if version >= [0, 3, 2]: hints['urgency'] = dbus.Byte(0) # Low Urgency hints['category'] = dbus.String(ntype) # it seems notification-daemon doesn't like empty text if self.text: text = self.text if len(self.text) > 200: text = '%s\n…' % self.text[:200] else: text = ' ' if os.environ.get('KDE_FULL_SESSION') == 'true': text = '<table style=\'padding: 3px\'><tr><td>' \ '<img src=\"%s\"></td><td width=20> </td>' \ '<td>%s</td></tr></table>' % (self.path_to_image, text) self.path_to_image = os.path.abspath( gtkgui_helpers.get_icon_path('gajim', 48)) actions = () if 'actions' in self.capabilities and self.msg_type: actions = (dbus.String('default'), dbus.String(self.event_type)) try: self.notif.Notify( dbus.String(_('Gajim')), # this notification does not replace other dbus.UInt32(0), dbus.String(self.path_to_image), dbus.String(self.title), dbus.String(text), actions, hints, dbus.UInt32(self.timeout * 1000), reply_handler=self.attach_by_id, error_handler=self.notify_another_way) except Exception as e: self.notify_another_way(e) else: try: self.notif.Notify(dbus.String(_('Gajim')), dbus.String(self.path_to_image), dbus.UInt32(0), dbus.String(self.title), dbus.String(self.text), dbus.String(''), hints, dbus.UInt32(self.timeout * 1000), reply_handler=self.attach_by_id, error_handler=self.notify_another_way) except Exception as e: self.notify_another_way(e)
if not r: exit(1) # Get the originals. dns_org = connection_config["ipv4"]["dns"] gw_org = connection_config["ipv4"]["gateway"] ip_org = connection_config["ipv4"]["address-data"]["address"] ifname_org = connection_config["connection"]["interface-name"] prefix_org = connection_config["ipv4"]["address-data"]["prefix"] # Add new connection. # Prepare DNS entry. if connection_config["ipv4"]["dns"] != "": connection_config["ipv4"]["dns"] = \ [dbus.UInt32(struct.unpack("L", socket.inet_aton(connection_config["ipv4"]["dns"]))[0])] else: connection_config["ipv4"]["dns"] = [dbus.UInt32(0L)] # Prepare address information entry. connection_config["ipv4"]["address-data"]["prefix"] = \ dbus.UInt32(connection_config["ipv4"]["address-data"]["prefix"]) connection_config["ipv4"]["address-data"] = \ dbus.Array([connection_config["ipv4"]["address-data"]], signature = dbus.Signature("a{sv}")) # Get list of all available devices. device_object_paths = \ dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, DBUS_NM_OBJECT_PATH), dbus_interface = DBUS_NM_INTERFACE).GetDevices() # Do WiFi connection specific preparations.
def getCodecDetails(self, account, codecId): """ Return codec details""" codecId=dbus.UInt32(codecId) return self.configurationmanager.getCodecDetails(account, codecId)
def beacon(config): """ Broadcast values via zeroconf If the announced values are static, it is advised to set run_once: True (do not poll) on the beacon configuration. The following are required configuration settings: - ``servicetype`` - The service type to announce - ``port`` - The port of the service to announce - ``txt`` - The TXT record of the service being announced as a dict. Grains can be used to define TXT values using one of following two formats: - ``grains.<grain_name>`` - ``grains.<grain_name>[i]`` where i is an integer representing the index of the grain to use. If the grain is not a list, the index is ignored. The following are optional configuration settings: - ``servicename`` - Set the name of the service. Will use the hostname from the minion's ``host`` grain if this value is not set. - ``reset_on_change`` - If ``True`` and there is a change in TXT records detected, it will stop announcing the service and then restart announcing the service. This interruption in service announcement may be desirable if the client relies on changes in the browse records to update its cache of TXT records. Defaults to ``False``. - ``reset_wait`` - The number of seconds to wait after announcement stops announcing and before it restarts announcing in the case where there is a change in TXT records detected and ``reset_on_change`` is ``True``. Defaults to ``0``. - ``copy_grains`` - If ``True``, Salt will copy the grains passed into the beacon when it backs them up to check for changes on the next iteration. Normally, instead of copy, it would use straight value assignment. This will allow detection of changes to grains where the grains are modified in-place instead of completely replaced. In-place grains changes are not currently done in the main Salt code but may be done due to a custom plug-in. Defaults to ``False``. Example Config .. code-block:: yaml beacons: avahi_announce: - run_once: True - servicetype: _demo._tcp - port: 1234 - txt: ProdName: grains.productname SerialNo: grains.serialnumber Comments: 'this is a test' """ ret = [] changes = {} txt = {} global LAST_GRAINS _config = {} list(map(_config.update, config)) if "servicename" in _config: servicename = _config["servicename"] else: servicename = __grains__["host"] # Check for hostname change if LAST_GRAINS and LAST_GRAINS["host"] != servicename: changes["servicename"] = servicename if LAST_GRAINS and _config.get("reset_on_change", False): # Check for IP address change in the case when we reset on change if LAST_GRAINS.get("ipv4", []) != __grains__.get("ipv4", []): changes["ipv4"] = __grains__.get("ipv4", []) if LAST_GRAINS.get("ipv6", []) != __grains__.get("ipv6", []): changes["ipv6"] = __grains__.get("ipv6", []) for item in _config["txt"]: changes_key = "txt." + salt.utils.stringutils.to_unicode(item) if _config["txt"][item].startswith("grains."): grain = _config["txt"][item][7:] grain_index = None square_bracket = grain.find("[") if square_bracket != -1 and grain[-1] == "]": grain_index = int(grain[square_bracket + 1 : -1]) grain = grain[:square_bracket] grain_value = __grains__.get(grain, "") if isinstance(grain_value, list): if grain_index is not None: grain_value = grain_value[grain_index] else: grain_value = ",".join(grain_value) txt[item] = _enforce_txt_record_maxlen(item, grain_value) if LAST_GRAINS and ( LAST_GRAINS.get(grain, "") != __grains__.get(grain, "") ): changes[changes_key] = txt[item] else: txt[item] = _enforce_txt_record_maxlen(item, _config["txt"][item]) if not LAST_GRAINS: changes[changes_key] = txt[item] if changes: if not LAST_GRAINS: changes["servicename"] = servicename changes["servicetype"] = _config["servicetype"] changes["port"] = _config["port"] changes["ipv4"] = __grains__.get("ipv4", []) changes["ipv6"] = __grains__.get("ipv6", []) GROUP.AddService( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", "", dbus.UInt16(_config["port"]), avahi.dict_to_txt_array(txt), ) GROUP.Commit() elif _config.get("reset_on_change", False) or "servicename" in changes: # A change in 'servicename' requires a reset because we can only # directly update TXT records GROUP.Reset() reset_wait = _config.get("reset_wait", 0) if reset_wait > 0: time.sleep(reset_wait) GROUP.AddService( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", "", dbus.UInt16(_config["port"]), avahi.dict_to_txt_array(txt), ) GROUP.Commit() else: GROUP.UpdateServiceTxt( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", avahi.dict_to_txt_array(txt), ) ret.append({"tag": "result", "changes": changes}) if _config.get("copy_grains", False): LAST_GRAINS = __grains__.copy() else: LAST_GRAINS = __grains__ return ret
def parse_array_of_uint32(array): dbus_array = dbus.Array([], signature=dbus.Signature('u')) for uint32val in array: dbus_array.append(dbus.UInt32(uint32val)) return dbus_array
def item_new(self, interface, protocol, name, stype, domain, flags): with self.lock: self.server.ResolveService(interface, protocol, name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.resolved, error_handler=self.resolve_error)
def new(self): self.treemodel=Gtk.TreeStore(GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) self.tree_view.set_model(self.treemodel) #creating the columns headers self.tree_view.set_headers_visible(False) renderer=Gtk.CellRendererText() column=Gtk.TreeViewColumn("",renderer, text=0) column.set_resizable(True) column.set_sizing(Gtk.TreeViewColumnSizing.GROW_ONLY) column.set_expand(True) self.tree_view.append_column(column) self.domain = None self.stype = None self.zc_ifaces = {} self.zc_domains = {} self.zc_types = {} self.services_browsed = {} try: self.bus = dbus.SystemBus() self.server = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) except Exception as e: print("Failed to connect to Avahi Server (Is it running?): %s" % e) sys.exit(1) if self.domain is None: # Explicitly browse .local self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "local") # Browse for other browsable domains db = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.DomainBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "", avahi.DOMAIN_BROWSER_BROWSE, dbus.UInt32(0))), avahi.DBUS_INTERFACE_DOMAIN_BROWSER) db.connect_to_signal('ItemNew', self.new_domain) else: # Just browse the domain the user wants us to browse self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, self.domain)
def mask_to_dbus(mask): return dbus.UInt32(mask)
def on_tree_view_cursor_changed(self, widget, *args): (model, iter) = widget.get_selection().get_selected() stype = None if iter is not None: (name,interface,protocol,stype,domain) = self.treemodel.get(iter,1,2,3,4,5) if stype == None: self.info_label.set_markup(_("<i>No service currently selected.</i>")) return #Asynchronous resolving self.server.ResolveService( int(interface), int(protocol), name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.service_resolved, error_handler=self.print_error)
def set_pairable_timeout(self, timeout): self.set_property("PairableTimeout", dbus.UInt32(timeout))
session, dbus_interface='org.genivi.navigation.navigationcore.Session') # Get SessionHandle ret = session_interface.CreateSession(dbus.String('test location input')) session_handle = ret[1] print('Session handle = ' + str(session_handle)) location_input_obj = bus.get_object( 'org.genivi.navigation.navigationcore.LocationInput', '/org/genivi/navigationcore') location_input_interface = dbus.Interface( location_input_obj, dbus_interface='org.genivi.navigation.navigationcore.LocationInput') # Get LocationInputHandle ret = location_input_interface.CreateLocationInput(dbus.UInt32(session_handle)) location_input_handle = ret[1] print('LocationInput handle = ' + str(location_input_handle)) attributes = location_input_interface.GetSupportedAddressAttributes() print('Initially supported address attributes = ' + selection_criteria_array_to_string(attributes)) # Configuration current_address_index = 0 entered_search_string = '' spell_next_character = 0 found_exact_match = 0 available_characters = '' target_search_string = ''
def __init__(self, name, service_type='_ros-master._tcp', host=socket.gethostname(), port=11311, domain='local', txt_array=[]): ''' Initialization method of the Zeroconf class. :param name: the name of the local ROS master :type name: str :param service_type: the avahi service type :type service_type: str :param host: the host of the local ROS master :type host: str :param port: the port of the local ROS master :type port: int :param domain: the domain name :type domain: str :param txt_array: (optional) additional information :type txt_array: list of strings ''' self.masterInfo = MasterInfo(name, service_type, domain, host, port, txt_array) # FIXME Review thread locking as needed. # init thread threading.Thread.__init__(self) self._lock = threading.RLock() # Gobjects are an event based model of evil, do not trust them, DBusGMainLoop(set_as_default=True) # Magic? Yes, don't start threads without it. # Why? I'm sure thats documented somewhere. gobject.threads_init() dbus.mainloop.glib.threads_init() self.__main_loop = gobject.MainLoop() self.__bus = dbus.SystemBus() # Initialize iterface to DBUS Server self.__server = dbus.Interface( self.__bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) # The DBUS entry group self.__group = None # Monitor server state changes self.__server.connect_to_signal("StateChanged", self.__avahi_callback_state_changed) # the browser to register the updates and new services self.__browser = dbus.Interface( self.__bus.get_object( avahi.DBUS_NAME, self.__server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, self.masterInfo.stype, self.masterInfo.domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) self.__browser.connect_to_signal( "ItemNew", self.__avahi_callback_service_browser_new) self.__browser.connect_to_signal( "ItemRemove", self.__avahi_callback_service_browser_remove)
class GlitterCapabilities( telepathy.server.ConnectionInterfaceCapabilities, telepathy.server.ConnectionInterfaceContactCapabilities, ): text_chat_class = \ ({telepathy.CHANNEL_INTERFACE + '.ChannelType': telepathy.CHANNEL_TYPE_TEXT, telepathy.CHANNEL_INTERFACE + '.TargetHandleType': dbus.UInt32(telepathy.HANDLE_TYPE_CONTACT)}, [telepathy.CHANNEL_INTERFACE + '.TargetHandle', telepathy.CHANNEL_INTERFACE + '.TargetID']) audio_chat_class = \ ({telepathy.CHANNEL_INTERFACE + '.ChannelType': telepathy.CHANNEL_TYPE_STREAMED_MEDIA, telepathy.CHANNEL_INTERFACE + '.TargetHandleType': dbus.UInt32(telepathy.HANDLE_TYPE_CONTACT)}, [telepathy.CHANNEL_INTERFACE + '.TargetHandle', telepathy.CHANNEL_INTERFACE + '.TargetID', telepathy.CHANNEL_TYPE_STREAMED_MEDIA + '.InitialAudio']) av_chat_class = \ ({telepathy.CHANNEL_INTERFACE + '.ChannelType': telepathy.CHANNEL_TYPE_STREAMED_MEDIA, telepathy.CHANNEL_INTERFACE + '.TargetHandleType': dbus.UInt32(telepathy.HANDLE_TYPE_CONTACT)}, [telepathy.CHANNEL_INTERFACE + '.TargetHandle', telepathy.CHANNEL_INTERFACE + '.TargetID', telepathy.CHANNEL_TYPE_STREAMED_MEDIA + '.InitialAudio', telepathy.CHANNEL_TYPE_STREAMED_MEDIA + '.InitialVideo']) file_transfer_class = \ ({telepathy.CHANNEL_INTERFACE + '.ChannelType': telepathy.CHANNEL_TYPE_FILE_TRANSFER, telepathy.CHANNEL_INTERFACE + '.TargetHandleType': dbus.UInt32(telepathy.HANDLE_TYPE_CONTACT)}, [telepathy.CHANNEL_INTERFACE + '.TargetHandle', telepathy.CHANNEL_INTERFACE + '.TargetID', telepathy.CHANNEL_TYPE_FILE_TRANSFER + '.Requested', telepathy.CHANNEL_TYPE_FILE_TRANSFER + '.Filename', telepathy.CHANNEL_TYPE_FILE_TRANSFER + '.Size', telepathy.CHANNEL_TYPE_FILE_TRANSFER + '.ContentType']) def __init__(self): telepathy.server.ConnectionInterfaceCapabilities.__init__(self) telepathy.server.ConnectionInterfaceContactCapabilities.__init__(self) self._video_clients = [] self._update_capabilities_calls = [] ### Events handling ------------------------------------------------------ # papyon.event.ContactEventInterface def on_contact_client_capabilities_changed(self, contact): handle = self.ensure_contact_handle(contact) if handle == self._self_handle: return # don't update our own capabilities using server ones self._update_capabilities(handle) self._update_contact_capabilities([handle]) # papyon.event.AddressBookEventInterface def on_addressbook_contact_added(self, contact): """When we add a contact in our contact list, add the default capabilities to the contact""" handle = self.ensure_contact_handle(contact) self._add_default_capabilities([handle]) self._update_contact_capabilities([handle]) ### Capabilities interface ----------------------------------------------- def _get_capabilities(self, contact): gen_caps = 0 spec_caps = 0 caps = contact.client_capabilities if caps.supports_sip_invite: gen_caps |= telepathy.CONNECTION_CAPABILITY_FLAG_CREATE gen_caps |= telepathy.CONNECTION_CAPABILITY_FLAG_INVITE spec_caps |= telepathy.CHANNEL_MEDIA_CAPABILITY_AUDIO spec_caps |= telepathy.CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN if caps.has_webcam: spec_caps |= telepathy.CHANNEL_MEDIA_CAPABILITY_VIDEO return gen_caps, spec_caps def _add_default_capabilities(self, handles): """Add the default capabilities to these contacts.""" ret = [] for handle in handles: new_flag = telepathy.CONNECTION_CAPABILITY_FLAG_CREATE ctype = telepathy.CHANNEL_TYPE_TEXT diff = self._diff_capabilities(handle, ctype, added_gen=new_flag) ret.append(diff) ctype = telepathy.CHANNEL_TYPE_FILE_TRANSFER diff = self._diff_capabilities(handle, ctype, added_gen=new_flag) ret.append(diff) self.CapabilitiesChanged(ret) def _update_capabilities(self, handle): ctype = telepathy.CHANNEL_TYPE_STREAMED_MEDIA new_gen, new_spec = self._get_capabilities(handle.contact) diff = self._diff_capabilities(handle, ctype, new_gen, new_spec) if diff is not None: self.CapabilitiesChanged([diff]) ### ContactCapabilities interface ---------------------------------------- def AdvertiseCapabilities(self, add, remove): #for caps, specs in add: # if caps == telepathy.CHANNEL_TYPE_STREAMED_MEDIA: # if specs & telepathy.CHANNEL_MEDIA_CAPABILITY_VIDEO: # self._msn_client.profile.client_id.has_webcam = True # self._msn_client.profile.client_id.supports_rtc_video = True #for caps in remove: # if caps == telepathy.CHANNEL_TYPE_STREAMED_MEDIA: # self._msn_client.profile.client_id.has_webcam = False return telepathy.server.ConnectionInterfaceCapabilities.\ AdvertiseCapabilities(self, add, remove) def UpdateCapabilities(self, caps): if self._status != telepathy.CONNECTION_STATUS_CONNECTED: self._update_capabilities_calls.append(caps) return # We only care about voip. for client, classes, capabilities in caps: video = False for channel_class in classes: # Does this client support video? if channel_class[telepathy.CHANNEL_INTERFACE + '.ChannelType'] == \ telepathy.CHANNEL_TYPE_STREAMED_MEDIA: video = True break if video and client not in self._video_clients: self._video_clients.append(client) elif not video and client in self._video_clients: # *Did* it used to support video? self._video_clients.remove(client) video = (len(self._video_clients) > 0) changed = False # We've got no more clients that support video; remove the cap. if not video and not self._video_clients: self._msn_client.profile.client_id.has_webcam = False changed = True # We want video. #if video and (not self._msn_client.profile.client_id.has_webcam or # not self._msn_client.profile.client_id.supports_rtc_video): # self._msn_client.profile.client_id.has_webcam = True # self._msn_client.profile.client_id.supports_rtc_video = True # changed = True # Signal. if changed: updated = dbus.Dictionary( {self._self_handle: self._contact_caps[self._self_handle]}, signature='ua(a{sv}as)') self.ContactCapabilitiesChanged(updated) def _get_contact_capabilities(self, contact): contact_caps = [] contact_caps.append(self.text_chat_class) return contact_caps def _update_contact_capabilities(self, handles): caps = {} for handle in handles: caps[handle] = self._get_contact_capabilities(handle) self._contact_caps[handle] = caps[handle] # update global dict ret = dbus.Dictionary(caps, signature='ua(a{sv}as)') self.ContactCapabilitiesChanged(ret) ### Start ContactCapabilities @dbus.service.method( dbus_interface=telepathy.CONNECTION_INTERFACE_CONTACT_CAPABILITIES, in_signature="au", out_signature="a{ua(a{sv}as)}") def GetContactCapabilities(self, handles): logger.debug("GetContactCapabilities: (in) %s", str(handles)) handles = set(handles) if 0 in handles: handles.remove(0) ret = dbus.Dictionary(signature="u(a{sv}as)") channels = dbus.Dictionary(signature="sv") channels[ 'org.freedesktop.Telepathy.Channel.TargetHandleType'] = telepathy.HANDLE_TYPE_CONTACT channels['org.freedesktop.Telepathy.Channel.ChannelType'] = \ 'org.freedesktop.Telepathy.Channel.Type.Text' interfaces = dbus.Array( ['org.freedesktop.Telepathy.Channel.TargetHandle'], signature="s") struct = dbus.Struct((channels, interfaces), signature="(a{sv}as)") for h in handles: ret[int(h)] = dbus.Array([ struct, ], signature="(a{sv}as)") # (channels, interfaces) return ret ### End ContactCapabilities ### Initialization ------------------------------------------------------- @async def _populate_capabilities(self): """ Add the default capabilities to all contacts in our contacts list.""" handles = set([self._self_handle]) for contact in self._contact_handles: handles.add(contact) self._add_default_capabilities(handles) self._update_contact_capabilities(handles) # These caps were updated before we were online. for caps in self._update_capabilities_calls: self.UpdateCapabilities(caps) self._update_capabilities_calls = []
def __init__(self, address, tls = None, disconnect_cb = None, remote = None): # {{{ '''Create a connection. @param address: connection target. This is a unix domain socket if there is a / in it. It is an avahi service if there is a | in it. This is written as service|regexp, where regexp must match the long service name and can be empty to match all. If it is not a unix domain socket or an avahi service, it is port number or service name, optionally prefixed with a hostname and a :. If no hostname is present, localhost is used. @param tls: whether TLS encryption should be used. Can be True or False, or None to try encryption first and fall back to unencrypted. Setting this to None may trigger an error message and may fail to connect to unencrypted sockets due to the encryption handshake not returning. @param disconnect_cb: callback function for when the connection is lost. @param remote: For internal use only. ''' ## read only variable which indicates whether TLS encryption is used on this socket. self.tls = tls ## remote end of the network connection. self.remote = remote ## underlying socket object. self.socket = None self._disconnect_cb = disconnect_cb self._event = None self._linebuffer = b'' if isinstance(address, (_Fake, socket.socket)): #log('new %d' % id(address)) self.socket = address return if isinstance(address, str) and '/' in address: # Unix socket. # TLS is ignored for those. self.remote = address self.socket = socket.socket(socket.AF_UNIX) self.socket.connect(self.remote) elif have_avahi and isinstance(address, str) and '|' in address: # Avahi. ret = [] found = [False] info = address.split('|') assert len(info) == 2 regexp = re.compile(info[1]) type = '_%s._tcp' % info[0] bus = dbus.SystemBus(mainloop = DBusGMainLoop()) server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, '/'), 'org.freedesktop.Avahi.Server') browser = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, type, 'local', dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) def handle2(*args): self.remote = (str(args[5]), int(args[8])) mainloop.quit() def handle_error(*args): log('avahi lookup error(ignored): %s' % args[0]) def handle(interface, protocol, name, type, domain, flags): if found[0]: return if regexp.match(name): found[0] = True server.ResolveService(interface, protocol, name, type, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler = handle2, error_handler = handle_error) def handle_eof(): if found[0]: return self.remote = None mainloop.quit() browser.connect_to_signal('ItemNew', handle) browser.connect_to_signal('AllForNow', handle_eof) browser.connect_to_signal('Failure', handle_eof) mainloop = GLib.MainLoop() mainloop.run() if self.remote is not None: self._setup_connection() else: raise EOFError('Avahi service not found') else: if isinstance(address, str) and ':' in address: host, port = address.rsplit(':', 1) else: host, port = 'localhost', address self.remote = (host, lookup(port)) #log('remote %s' % str(self.remote)) self._setup_connection()
def RequestPasskey(self, device): print("RequestPasskey (%s)" % (device)) set_trusted(device) return dbus.UInt32(getSerial())
def __init__(self, port, obj, address = '', backlog = 5, tls = None, disconnect_cb = None): '''Start a server. @param port: Port to listen on. Can be an avahi service as "name|description" or a unix domain socket, or a numerical port or service name. @param obj: Object to create when a new connection is accepted. The new object gets the nex Socket as parameter. This can be a function instead of an object. @param address: Address to listen on. If empty, listen on all IPv4 and IPv6 addresses. If IPv6 is not supported, set this to "0.0.0.0" to listen only on IPv4. @param backlog: Number of connections that are accepted by the kernel while waiting for the program to handle them. @param tls: Whether TLS encryption should be enabled. If False or "-", it is disabled. If True, it is enabled with the default hostname. If None or "", it is enabled if possible. If a str, it is enabled with that string used as hostname. New keys are generated if they are not available. If you are serving to the internet, it is a good idea to get them signed by a certificate authority. They are in ~/.local/share/network/. @param disconnect_cb: Function which is called when a socket loses its connection. It receives the socket and any data that was remaining in the buffer as an argument. ''' self._disconnect_cb = disconnect_cb self._group = None self._obj = obj ## Port that is listened on. (read only) self.port = '' ## Whether the server listens for IPv6. (read only) self.ipv6 = False self._socket = None ## False or the hostname for which the TLS keys are used. (read only) self.tls = tls ## Currently active connections for this server. (read only set, but elements may be changed) self.connections = set() if isinstance(port, str) and '/' in port: # Unix socket. # TLS is ignored for these sockets. self.tls = False self._socket = socket.socket(socket.AF_UNIX) self._socket.bind(port) self.port = port self._socket.listen(backlog) elif have_avahi and isinstance(port, str) and '|' in port: self._tls_init() self._socket = socket.socket() self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if address == '': self._socket6 = socket.socket(socket.AF_INET6) self._socket6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) info = port.split('|') self.port = port if len(info) > 2: self._socket.bind((address, lookup(info[2]))) self._socket.listen(backlog) if address == '': p = self._socket.getsockname()[1] self._socket6.bind(('::1', p)) self._socket6.listen(backlog) self.ipv6 = True bus = dbus.SystemBus() server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) self._group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) self._group.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), info[1], '_%s._tcp' % info[0], '', '', dbus.UInt16(self._socket.getsockname()[1]), '') self._group.Commit() else: self._tls_init() port = lookup(port) self._socket = socket.socket() self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket.bind((address, port)) self._socket.listen(backlog) if address == '': self._socket6 = socket.socket(socket.AF_INET6) self._socket6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket6.bind(('::1', port)) self._socket6.listen(backlog) self.ipv6 = True self.port = port fd = self._socket.fileno() GLib.io_add_watch(fd, GLib.IO_IN | GLib.IO_PRI | GLib.IO_HUP | GLib.IO_ERR, self._cb) if self.ipv6: fd = self._socket6.fileno() GLib.io_add_watch(fd, GLib.IO_IN | GLib.IO_PRI | GLib.IO_HUP | GLib.IO_ERR, self._cb)
def test_action_multiple_device_batteries(self): '''critical actions for multiple device batteries''' # add a fake battery to upower bat1_path = self.obj_upower.AddDischargingBattery( 'mock_BAT1', 'Bat0', 30.0, 1200) obj_bat1 = self.system_bus_con.get_object('org.freedesktop.UPower', bat1_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 's', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') bat2_path = '/org/freedesktop/UPower/devices/' + 'mock_MOUSE_BAT1' self.obj_upower.AddObject( bat2_path, 'org.freedesktop.UPower.Device', { 'PowerSupply': dbus.Boolean(False, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String('Bat1', variant_level=1), 'Percentage': dbus.Double(40.0, variant_level=1), 'TimeToEmpty': dbus.Int64(1600, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(40.0, variant_level=1), # UP_DEVICE_STATE_DISCHARGING 'State': dbus.UInt32(2, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, dbus.Array([], signature='(ssss)')) obj_bat2 = self.system_bus_con.get_object('org.freedesktop.UPower', bat2_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 's', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') time.sleep(1) # now change the mouse battery to critical charge obj_bat2.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(30, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.5, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 's', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') # wait long enough to ensure it didn't do anything (as we still have # the second battery) self.check_no_suspend(5) # now change the main battery to critical charge as well obj_bat1.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(25, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.4, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 's', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') self.check_for_suspend(5)
def SetConnectivity(self, connectivity): self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'Connectivity', dbus.UInt32(connectivity, variant_level=1))
bus = dbus.SystemBus() o = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings') s = dbus.Dictionary( { 'connection': { 'id': 'con_general', 'uuid': str(uuid.uuid1()), 'interface-name': 'nonexistant', 'type': '802-3-ethernet', }, 'ipv4': { 'addresses': dbus.Array([[ip_to_int('192.168.1.1'), dbus.UInt32(24), 0]], signature='au'), 'method': 'manual' }, '802-3-ethernet': {} }, signature='sa{sv}') object_path = o.AddConnection( s, dbus_interface='org.freedesktop.NetworkManager.Settings') o = bus.get_object('org.freedesktop.NetworkManager', object_path) setting = o.GetSettings( dbus_interface='org.freedesktop.NetworkManager.Settings.Connection')
def addr_to_dbus(addr, family): if (family == socket.AF_INET): return dbus.UInt32( struct.unpack('I', socket.inet_pton(family, addr))[0]) else: return dbus.ByteArray(socket.inet_pton(family, addr))
for t in tests: try: netw_obj.set(t, dbus_interface=WPAS_DBUS_OLD_NETWORK) raise Exception("Invalid set() accepted: " + str(t)) except dbus.exceptions.DBusException, e: if "InvalidOptions" not in str(e): raise Exception("Unexpected error message for invalid set: " + str(e)) params = dbus.Dictionary( { 'ssid': ssid, 'key_mgmt': 'WPA-PSK', 'psk': passphrase, 'identity': dbus.ByteArray([1, 2]), 'priority': dbus.Int32(0), 'scan_freq': dbus.UInt32(2412) }, signature='sv') netw_obj.set(params, dbus_interface=WPAS_DBUS_OLD_NETWORK) id = int(dev[0].list_networks()[0]['id']) val = dev[0].get_network(id, "scan_freq") if val != "2412": raise Exception("Invalid scan_freq value: " + str(val)) params = dbus.Dictionary( { 'scan_freq': "2412 2432", 'freq_list': "2412 2417 2432" }, signature='sv') netw_obj.set(params, dbus_interface=WPAS_DBUS_OLD_NETWORK) val = dev[0].get_network(id, "scan_freq")