"""Test 1-1 tubes support.""" import dbus from servicetest import call_async, EventPattern, sync_dbus, assertEquals from gabbletest import acknowledge_iq, sync_stream, make_result_iq import constants as cs import ns import tubetestutil as t from twisted.words.xish import domish, xpath sample_parameters = dbus.Dictionary( { 's': 'hello', 'ay': dbus.ByteArray(b'hello'), 'u': dbus.UInt32(123), 'i': dbus.Int32(-123), }, signature='sv') new_sample_parameters = dbus.Dictionary( { 's': 'newhello', 'ay': dbus.ByteArray(b'newhello'), 'u': dbus.UInt32(123), 'i': dbus.Int32(-123), }, signature='sv')
def notify_tx_bytes(self): if not self.notifying: return self.PropertiesChanged( GATT_CHRC_IFACE, {'Value': dbus.ByteArray(self.tx_bytes)}, [])
def wifi_ap(up=True, iface="wlan0"): our_uuid = '2b0d0f1d-b79d-43af-bde1-7174462564EE' s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'uuid': our_uuid, 'autoconnect': False, 'id': 'OPQ'}) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray("OPQBox"), 'mode': "ap"}) s_ip4 = dbus.Dictionary({'method': 'shared'}) s_ip6 = dbus.Dictionary({'method': 'ignore'}) con = dbus.Dictionary({ 'connection': s_con, '802-11-wireless': s_wifi, 'ipv4': s_ip4, 'ipv6': s_ip6 }) bus = dbus.SystemBus() service_name = "org.freedesktop.NetworkManager" proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") iface = iface proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager") nm = dbus.Interface(proxy, "org.freedesktop.NetworkManager") devpath = nm.GetDeviceByIpIface(iface) # Find our existing hotspot connection connection_path = None for path in settings.ListConnections(): proxy = bus.get_object(service_name, path) settings_connection = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") config = settings_connection.GetSettings() if config['connection']['uuid'] == our_uuid: settings_connection.Update(con) connection_path = path break # If the hotspot connection didn't already exist, add it if not connection_path: connection_path = settings.AddConnection(con) # Now start or stop the hotspot on the requested device proxy = bus.get_object(service_name, devpath) device = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Device") operation = "up" if up else "down" if operation == "up": try: acpath = nm.ActivateConnection(connection_path, devpath, "/") proxy = bus.get_object(service_name, acpath) active_props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") except Exception as e: return False else: try: device.Disconnect() proxy = bus.get_object(service_name, connection_path) settings_connection = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") settings_connection.Delete() except Exception as e: print e return True # Wait to connect start = time.time() while time.time() < start + 30: try: state = active_props.Get("org.freedesktop.NetworkManager.Connection.Active", "State") if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED print "Connected to access point" return True except Exception as e: pass time.sleep(1) return False
# with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright (C) 2015 Red Hat, Inc. # import dbus, uuid s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'uuid': str(uuid.uuid4()), 'id': 'My-WPA-PSK' }) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray("best-wifi".encode("utf-8")), 'mode': 'infrastructure', }) s_wsec = dbus.Dictionary({ 'key-mgmt': 'wpa-psk', 'auth-alg': 'open', 'psk': 'super-secret-password', }) s_ip4 = dbus.Dictionary({'method': 'auto'}) s_ip6 = dbus.Dictionary({'method': 'ignore'}) con = dbus.Dictionary({ 'connection': s_con, '802-11-wireless': s_wifi,
def _migrate_old_wifi_connections(): """Migrate connections.cfg from Sugar-0.94 and previous to NetworkManager system-wide connections """ profile_path = env.get_profile_path() config_path = os.path.join(profile_path, 'nm', 'connections.cfg') if not os.path.exists(config_path): return config = configparser.ConfigParser() try: if not config.read(config_path): logging.error('Error reading the nm config file') return except configparser.ParsingError: logging.exception('Error reading the nm config file') return for section in config.sections(): try: settings = Settings() settings.connection.id = section ssid = config.get(section, 'ssid').encode() settings.wireless.ssid = dbus.ByteArray(ssid) config_uuid = config.get(section, 'uuid') settings.connection.uuid = config_uuid nmtype = config.get(section, 'type') settings.connection.type = nmtype autoconnect = bool(config.get(section, 'autoconnect')) settings.connection.autoconnect = autoconnect if config.has_option(section, 'timestamp'): timestamp = int(config.get(section, 'timestamp')) settings.connection.timestamp = timestamp if config.has_option(section, 'key-mgmt'): settings.wireless_security = WirelessSecurity() mgmt = config.get(section, 'key-mgmt') settings.wireless_security.key_mgmt = mgmt security = config.get(section, 'security') settings.wireless.security = security key = config.get(section, 'key') if mgmt == 'none': settings.wireless_security.wep_key = key auth_alg = config.get(section, 'auth-alg') settings.wireless_security.auth_alg = auth_alg elif mgmt == 'wpa-psk': settings.wireless_security.psk = key if config.has_option(section, 'proto'): value = config.get(section, 'proto') settings.wireless_security.proto = value if config.has_option(section, 'group'): value = config.get(section, 'group') settings.wireless_security.group = value if config.has_option(section, 'pairwise'): value = config.get(section, 'pairwise') settings.wireless_security.pairwise = value except configparser.Error: logging.exception('Error reading section') else: add_connection(settings) os.unlink(config_path)
def test_complex_success(q, bus, conn, stream, with_extra_data=True, accept_early=False): chan, props = connect_and_get_sasl_channel(q, bus, conn) assertSameSets(MECHANISMS + ['X-TELEPATHY-PASSWORD'], props.get(cs.SASL_AVAILABLE_MECHANISMS)) call_async(q, chan.SASLAuthentication, 'StartMechanismWithData', "FOO", "") q.expect('dbus-error', method='StartMechanismWithData', name=cs.NOT_IMPLEMENTED) if with_extra_data: chan.SASLAuthentication.StartMechanismWithData("SCOTTISH-PLAY", INITIAL_RESPONSE) e = q.expect('sasl-auth', initial_response=INITIAL_RESPONSE) else: chan.SASLAuthentication.StartMechanism("SCOTTISH-PLAY") e = q.expect('sasl-auth', has_initial_response=False) authenticator = e.authenticator q.expect('dbus-signal', signal='SASLStatusChanged', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[cs.SASL_STATUS_IN_PROGRESS, '', {}]) if not with_extra_data: # send the stage directions in-band instead authenticator.challenge(b'') e = q.expect('dbus-signal', signal='NewChallenge', interface=cs.CHANNEL_IFACE_SASL_AUTH) # this ought to be '' but dbus-python has fd.o #28131 assert e.args in ([b''], [b'None']) chan.SASLAuthentication.Respond(INITIAL_RESPONSE) q.expect('sasl-response', response=INITIAL_RESPONSE) for challenge, response in CR_PAIRS: authenticator.challenge(challenge) q.expect('dbus-signal', signal='NewChallenge', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[challenge]) chan.SASLAuthentication.Respond(response) q.expect('sasl-response', response=response) if with_extra_data: authenticator.success(SUCCESS_DATA) else: # The success data is sent in-band as a challenge authenticator.challenge(SUCCESS_DATA) q.expect('dbus-signal', signal='NewChallenge', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[SUCCESS_DATA]) if accept_early: # the UI can tell that this challenge isn't actually a challenge, # it's a success in disguise chan.SASLAuthentication.AcceptSASL() q.expect('dbus-signal', signal='SASLStatusChanged', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[cs.SASL_STATUS_CLIENT_ACCEPTED, '', {}]) else: chan.SASLAuthentication.Respond(dbus.ByteArray(b'')) if with_extra_data: # Wocky removes the distinction between a challenge containing # success data followed by a plain success, and a success # containing initial data, so we won't get to Server_Succeeded # til we "respond" to the "challenge". However, at the XMPP level, # we shouldn't get a response to a success. q.forbid_events([EventPattern('sasl-response')]) else: q.expect('sasl-response', response=b'') authenticator.success(None) if not accept_early: # *now* we accept q.expect('dbus-signal', signal='SASLStatusChanged', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[cs.SASL_STATUS_SERVER_SUCCEEDED, '', {}]) # We're willing to accept this SASL transaction chan.SASLAuthentication.AcceptSASL() q.expect('dbus-signal', signal='SASLStatusChanged', interface=cs.CHANNEL_IFACE_SASL_AUTH, args=[cs.SASL_STATUS_SUCCEEDED, '', {}]) q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]) chan.Close() # ... and check that the Connection is still OK conn.Properties.Get(cs.CONN, "SelfHandle")
def __download_finished_cb(self, download): if hasattr(self._activity, 'busy'): self._activity.unbusy() if self._progress_sid is not None: GObject.source_remove(self._progress_sid) if self.dl_jobject is None: return # the "failed" signal was observed self.dl_jobject.metadata['title'] = self._suggested_filename self.dl_jobject.metadata['description'] = _('From: %s') \ % self._source self.dl_jobject.metadata['progress'] = '100' self.dl_jobject.file_path = self._dest_path mime_type = Gio.content_type_guess(self._dest_path)[0] if mime_type != 'application/vnd.olpc-sugar': mime_type = download.get_response().get_mime_type() self.dl_jobject.metadata['mime_type'] = mime_type if mime_type in ('image/bmp', 'image/gif', 'image/jpeg', 'image/png', 'image/tiff'): preview = self._get_preview() if preview is not None: self.dl_jobject.metadata['preview'] = \ dbus.ByteArray(preview) datastore.write(self.dl_jobject, transfer_ownership=True, reply_handler=self.__internal_save_cb, error_handler=self.__internal_error_cb, timeout=360) self._stop_alert = Alert() self._stop_alert.props.title = _('Download completed') self._stop_alert.props.msg = self._suggested_filename bundle = None if _HAS_BUNDLE_LAUNCHER: bundle = get_bundle(object_id=self._object_id) if bundle is not None: icon = Icon(file=bundle.get_icon()) label = _('Open with %s') % bundle.get_name() response_id = Gtk.ResponseType.APPLY else: icon = Icon(icon_name='zoom-activity') label = _('Show in Journal') response_id = Gtk.ResponseType.ACCEPT self._stop_alert.add_button(response_id, label, icon) icon.show() ok_icon = Icon(icon_name='dialog-ok') self._stop_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon) ok_icon.show() self._activity.add_alert(self._stop_alert) self._stop_alert.connect('response', self.__stop_response_cb) self._stop_alert.show()
raise Exception("Unexpected error message for invalid setBlobs: " + str(e)) tests = [ (["foo"], "RemoveError: Error removing blob"), ([""], "RemoveError: Invalid blob name"), ([1], "InvalidOptions"), ("foo", "InvalidOptions") ] for (arg,err) in tests: try: if_obj.removeBlobs(arg, dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid removeBlobs() accepted: " + str(arg)) except dbus.exceptions.DBusException, e: logger.debug("removeBlobs(%s): %s" % (str(arg), str(e))) if err not in str(e): raise Exception("Unexpected error message for invalid removeBlobs: " + str(e)) blobs = dbus.Dictionary({ 'blob1': dbus.ByteArray([ 1, 2, 3 ]), 'blob2': dbus.ByteArray([ 1, 2 ]) }, signature='sv') if_obj.setBlobs(blobs, dbus_interface=WPAS_DBUS_OLD_IFACE) if_obj.removeBlobs(['blob1', 'blob2'], dbus_interface=WPAS_DBUS_OLD_IFACE) def test_dbus_old_blob_oom(dev, apdev): """The old D-Bus interface - blob operations (OOM)""" (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0]) blobs = dbus.Dictionary({ 'blob1': dbus.ByteArray([ 1, 2, 3 ]), 'blob2': dbus.ByteArray([ 1, 2 ]) }, signature='sv') with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_iface_set_blobs", "setBlobs", "AddError: Not enough memory to add blob"):
def test_dbus_old_connect(dev, apdev): """The old D-Bus interface - add a network and connect""" (bus, wpas_obj, path, if_obj) = prepare_dbus(dev[0]) ssid = "test-wpa2-psk" passphrase = 'qwertyuiop' params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase) hapd = hostapd.add_ap(apdev[0], params) for p in [ "/no/where/to/be/found", path + "/Networks/12345", path + "/Networks/foo", "/fi/epitest/hostap/WPASupplicant/Interfaces", "/fi/epitest/hostap/WPASupplicant/Interfaces/12345/Networks/0" ]: obj = bus.get_object(WPAS_DBUS_OLD_SERVICE, p) try: if_obj.removeNetwork(obj, dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid removeNetwork accepted: " + p) except dbus.exceptions.DBusException as e: if not str(e).startswith( "fi.epitest.hostap.WPASupplicant.Interface.InvalidNetwork" ): raise Exception( "Unexpected error message for invalid removeNetwork: " + str(e)) try: if_obj.removeNetwork("foo", dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid removeNetwork accepted") except dbus.exceptions.DBusException as e: if not str(e).startswith( "fi.epitest.hostap.WPASupplicant.InvalidOptions"): raise Exception( "Unexpected error message for invalid removeNetwork: " + str(e)) try: if_obj.removeNetwork(path, dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid removeNetwork accepted") except dbus.exceptions.DBusException as e: if not str(e).startswith( "fi.epitest.hostap.WPASupplicant.Interface.InvalidNetwork"): raise Exception( "Unexpected error message for invalid removeNetwork: " + str(e)) tests = [(path, "InvalidNetwork"), (bus.get_object(WPAS_DBUS_OLD_SERVICE, "/no/where"), "InvalidInterface"), (bus.get_object(WPAS_DBUS_OLD_SERVICE, path + "/Networks/1234"), "InvalidNetwork"), (bus.get_object(WPAS_DBUS_OLD_SERVICE, path + "/Networks/foo"), "InvalidNetwork"), (1, "InvalidOptions")] for t, err in tests: try: if_obj.selectNetwork(t, dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid selectNetwork accepted: " + str(t)) except dbus.exceptions.DBusException as e: if err not in str(e): raise Exception( "Unexpected error message for invalid selectNetwork(%s): %s" % (str(t), str(e))) npath = if_obj.addNetwork(dbus_interface=WPAS_DBUS_OLD_IFACE) if not npath.startswith(WPAS_DBUS_OLD_PATH): raise Exception("Unexpected addNetwork result: " + path) netw_obj = bus.get_object(WPAS_DBUS_OLD_SERVICE, npath) tests = [123, dbus.Dictionary({'foo': 'bar'}, signature='sv')] 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 as 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") if val != "2412 2432": raise Exception("Invalid scan_freq value (2): " + str(val)) val = dev[0].get_network(id, "freq_list") if val != "2412 2417 2432": raise Exception("Invalid freq_list value: " + str(val)) if_obj.removeNetwork(npath, dbus_interface=WPAS_DBUS_OLD_IFACE) class TestDbusConnect(TestDbus): def __init__(self, bus): TestDbus.__init__(self, bus) self.state = 0 def __enter__(self): gobject.timeout_add(1, self.run_connect) gobject.timeout_add(15000, self.timeout) self.add_signal(self.scanDone, WPAS_DBUS_OLD_IFACE, "ScanResultsAvailable") self.add_signal(self.stateChange, WPAS_DBUS_OLD_IFACE, "StateChange") self.loop.run() return self def scanDone(self): logger.debug("scanDone") def stateChange(self, new, old): logger.debug("stateChange(%d): %s --> %s" % (self.state, old, new)) if new == "COMPLETED": if self.state == 0: self.state = 1 self.netw_obj.disable(dbus_interface=WPAS_DBUS_OLD_NETWORK) elif self.state == 2: self.state = 3 if_obj.disconnect(dbus_interface=WPAS_DBUS_OLD_IFACE) elif self.state == 4: self.state = 5 if_obj.disconnect(dbus_interface=WPAS_DBUS_OLD_IFACE) elif self.state == 6: self.state = 7 if_obj.removeNetwork(self.path, dbus_interface=WPAS_DBUS_OLD_IFACE) try: if_obj.removeNetwork( self.path, dbus_interface=WPAS_DBUS_OLD_IFACE) raise Exception("Invalid removeNetwork accepted") except dbus.exceptions.DBusException as e: if not str(e).startswith( "fi.epitest.hostap.WPASupplicant.Interface.InvalidNetwork" ): raise Exception( "Unexpected error message for invalid wpsPbc: " + str(e)) self.loop.quit() elif new == "DISCONNECTED": if self.state == 1: self.state = 2 self.netw_obj.enable(dbus_interface=WPAS_DBUS_OLD_NETWORK) elif self.state == 3: self.state = 4 if_obj.selectNetwork(dbus_interface=WPAS_DBUS_OLD_IFACE) elif self.state == 5: self.state = 6 if_obj.selectNetwork(self.path, dbus_interface=WPAS_DBUS_OLD_IFACE) def run_connect(self, *args): logger.debug("run_connect") path = if_obj.addNetwork(dbus_interface=WPAS_DBUS_OLD_IFACE) netw_obj = bus.get_object(WPAS_DBUS_OLD_SERVICE, path) netw_obj.disable(dbus_interface=WPAS_DBUS_OLD_NETWORK) params = dbus.Dictionary( { 'ssid': ssid, 'key_mgmt': 'WPA-PSK', 'psk': passphrase, 'scan_freq': 2412 }, signature='sv') netw_obj.set(params, dbus_interface=WPAS_DBUS_OLD_NETWORK) netw_obj.enable(dbus_interface=WPAS_DBUS_OLD_NETWORK) self.path = path self.netw_obj = netw_obj return False def success(self): return self.state == 7 with TestDbusConnect(bus) as t: if not t.success(): raise Exception("Expected signals not seen") if len(dev[0].list_networks()) != 0: raise Exception("Unexpected network")
def test(q, bus, mc): params = dbus.Dictionary( { "account": "*****@*****.**", "password": "******" }, signature='sv') (simulated_cm, account) = create_fakecm_account(q, bus, mc, params) account_iface = dbus.Interface(account, cs.ACCOUNT) account_props = dbus.Interface(account, cs.PROPERTIES_IFACE) assertEquals(cs.ACCOUNT_PATH_PREFIX, account.object_path[:len(cs.ACCOUNT_PATH_PREFIX)]) avatar_filename = account.object_path[len(cs.ACCOUNT_PATH_PREFIX):] avatar_filename = avatar_filename.replace('/', '-') + '.avatar' avatar_filename = (os.environ['XDG_DATA_HOME'] + '/telepathy/mission-control/' + avatar_filename) call_async(q, account_props, 'Set', cs.ACCOUNT_IFACE_AVATAR, 'Avatar', dbus.Struct((dbus.ByteArray('AAAA'), 'image/jpeg'))) q.expect_many( EventPattern('dbus-signal', path=account.object_path, signal='AvatarChanged', interface=cs.ACCOUNT_IFACE_AVATAR, args=[]), EventPattern('dbus-return', method='Set'), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='DeferringSetAttribute', args=[account.object_path, 'AvatarMime', 'image/jpeg']), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='CommittingOne', args=[account.object_path]), EventPattern('dbus-method-call', interface=cs.TEST_DBUS_ACCOUNT_SERVICE_IFACE, method='UpdateAttributes'), ) assert account_props.Get(cs.ACCOUNT_IFACE_AVATAR, 'Avatar', byte_arrays=True) == ('AAAA', 'image/jpeg') assertEquals('AAAA', ''.join(open(avatar_filename, 'r').readlines())) # We aren't storing in the old location assert not os.path.exists(os.environ['MC_ACCOUNT_DIR'] + '/fakecm') # OK, let's go online. The avatar is set regardless of the CM conn, e = enable_fakecm_account(q, bus, mc, account, params, has_avatars=True, avatars_persist=True, expect_after_connect=[ EventPattern( 'dbus-method-call', interface=cs.CONN_IFACE_AVATARS, method='SetAvatar', handled=True, args=['AAAA', 'image/jpeg']), ]) # Change avatar after going online call_async(q, account_props, 'Set', cs.ACCOUNT_IFACE_AVATAR, 'Avatar', (dbus.ByteArray('BBBB'), 'image/png')) q.expect_many( EventPattern('dbus-method-call', interface=cs.CONN_IFACE_AVATARS, method='SetAvatar', args=['BBBB', 'image/png'], handled=True), EventPattern('dbus-signal', path=account.object_path, interface=cs.ACCOUNT_IFACE_AVATAR, signal='AvatarChanged'), EventPattern('dbus-return', method='Set'), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='DeferringSetAttribute', args=[account.object_path, 'AvatarMime', 'image/png']), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='CommittingOne', args=[account.object_path]), EventPattern('dbus-method-call', interface=cs.TEST_DBUS_ACCOUNT_SERVICE_IFACE, method='UpdateAttributes'), ) assert account_props.Get(cs.ACCOUNT_IFACE_AVATAR, 'Avatar', byte_arrays=True) == ('BBBB', 'image/png') assertEquals('BBBB', ''.join(open(avatar_filename, 'r').readlines())) assert not os.path.exists(os.environ['MC_ACCOUNT_DIR'] + '/fakecm') someone_else = conn.ensure_handle(cs.HT_CONTACT, '*****@*****.**') # Another contact changes their avatar: ignored q.dbus_emit(conn.object_path, cs.CONN_IFACE_AVATARS, 'AvatarUpdated', someone_else, "mardy's avatar token", signature='us') # Another client changes our avatar remotely q.dbus_emit(conn.object_path, cs.CONN_IFACE_AVATARS, 'AvatarUpdated', conn.self_handle, 'CCCC', signature='us') e = q.expect('dbus-method-call', interface=cs.CONN_IFACE_AVATARS, method='RequestAvatars', args=[[conn.self_handle]], handled=False) q.dbus_return(e.message, signature='') q.dbus_emit(conn.object_path, cs.CONN_IFACE_AVATARS, 'AvatarRetrieved', conn.self_handle, 'CCCC', dbus.ByteArray('CCCC'), 'image/svg', signature='usays') q.expect_many( EventPattern('dbus-signal', path=account.object_path, interface=cs.ACCOUNT_IFACE_AVATAR, signal='AvatarChanged'), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='DeferringSetAttribute', args=[account.object_path, 'avatar_token', 'CCCC']), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='CommittingOne', args=[account.object_path]), EventPattern('dbus-method-call', interface=cs.TEST_DBUS_ACCOUNT_SERVICE_IFACE, method='UpdateAttributes'), ) assert account_props.Get(cs.ACCOUNT_IFACE_AVATAR, 'Avatar', byte_arrays=True) == ('CCCC', 'image/svg') assertEquals('CCCC', ''.join(open(avatar_filename, 'r').readlines())) # empty avatar tests conn.forget_avatar() q.dbus_emit(conn.object_path, cs.CONN_IFACE_AVATARS, 'AvatarUpdated', conn.self_handle, '', signature='us') q.expect_many( EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='DeferringSetAttribute', args=[account.object_path, 'avatar_token', '']), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='DeferringSetAttribute', args=[account.object_path, 'AvatarMime', '']), EventPattern('dbus-signal', path=account.object_path, interface=cs.ACCOUNT_IFACE_AVATAR, signal='AvatarChanged'), EventPattern('dbus-signal', interface=cs.TEST_DBUS_ACCOUNT_PLUGIN_IFACE, signal='CommittingOne', args=[account.object_path]), EventPattern('dbus-method-call', interface=cs.TEST_DBUS_ACCOUNT_SERVICE_IFACE, method='UpdateAttributes'), ) assertEquals( account_props.Get(cs.ACCOUNT_IFACE_AVATAR, 'Avatar', byte_arrays=False), ([], '')) # empty avatars are represented by an empty file, not no file, # to get the right precedence over XDG_DATA_DIRS assertEquals('', ''.join(open(avatar_filename, 'r').readlines()))
def _saveMediaToDatastore(el, recd, activity): # note that we update the recds that go through here to how they # would look on a fresh load from file since this won't just # happen on close() if recd.datastoreId: # already saved to the datastore, don't need to re-rewrite the # file since the mediums are immutable. However, they might # have changed the name of the file if recd.metaChange: recd.datastoreOb = getMediaFromDatastore(recd) if recd.datastoreOb.metadata['title'] != recd.title: recd.datastoreOb.metadata['title'] = recd.title datastore.write(recd.datastoreOb) if recd.datastoreOb.metadata['tags'] != recd.tags: recd.datastoreOb.metadata['tags'] = recd.tags datastore.write(recd.datastoreOb) # reset for the next title change if not closing... recd.metaChange = False # save the title to the xml recd.savedMedia = True _saveXml(el, recd) else: # this will remove the media from being accessed on the local # disk since it puts it away into cold storage, therefore this # is only called when write_file is called by the activity # superclass mediaObject = datastore.create() mediaObject.metadata['title'] = recd.title mediaObject.metadata['tags'] = recd.tags datastorePreviewPixbuf = recd.getThumbPixbuf() if recd.type == constants.TYPE_AUDIO: datastorePreviewPixbuf = recd.getAudioImagePixbuf() elif recd.type == constants.TYPE_PHOTO: datastorePreviewFilepath = recd.getMediaFilepath() datastorePreviewPixbuf = GdkPixbuf.Pixbuf.new_from_file( datastorePreviewFilepath) if datastorePreviewPixbuf: # journal shows previews in a 4:3 aspect ratio datastorePreviewWidth = 300 datastorePreviewHeight = 225 # scale to match available height, retaining aspect ratio consequentWidth = datastorePreviewHeight * \ datastorePreviewPixbuf.get_width() / \ datastorePreviewPixbuf.get_height() datastorePreviewPixbuf = \ datastorePreviewPixbuf.scale_simple( consequentWidth, datastorePreviewHeight, GdkPixbuf.InterpType.BILINEAR) # where aspect ratio is unconventional, e.g. 16:9, trim sides if consequentWidth != datastorePreviewWidth: trimmedPixbuf = GdkPixbuf.Pixbuf.new( datastorePreviewPixbuf.get_colorspace(), datastorePreviewPixbuf.get_has_alpha(), datastorePreviewPixbuf.get_bits_per_sample(), datastorePreviewWidth, datastorePreviewHeight) datastorePreviewPixbuf.copy_area( (consequentWidth - datastorePreviewWidth) / 2, 0, datastorePreviewWidth, datastorePreviewHeight, trimmedPixbuf, 0, 0) datastorePreviewPixbuf = trimmedPixbuf datastorePreview = utils.getStringFromPixbuf( datastorePreviewPixbuf) mediaObject.metadata['preview'] = dbus.ByteArray(datastorePreview) colors = str(recd.colorStroke) + "," + str(recd.colorFill) mediaObject.metadata['icon-color'] = colors mtype = constants.MEDIA_INFO[recd.type] mediaObject.metadata['mime_type'] = mtype['mime'] mediaObject.metadata['activity_id'] = activity._activity_id mediaFile = recd.getMediaFilepath() mediaObject.file_path = mediaFile mediaObject.transfer_ownership = True datastore.write(mediaObject) recd.datastoreId = mediaObject.object_id recd.savedMedia = True _saveXml(el, recd) recd.mediaFilename = None
def _saveMediaToDatastore(el, recd, activity): #note that we update the recds that go through here to how they would #look on a fresh load from file since this won't just happen on close() if recd.datastoreId: #already saved to the datastore, don't need to re-rewrite the file since the mediums are immutable #However, they might have changed the name of the file if recd.metaChange: recd.datastoreOb = getMediaFromDatastore(recd) if recd.datastoreOb.metadata['title'] != recd.title: recd.datastoreOb.metadata['title'] = recd.title datastore.write(recd.datastoreOb) if recd.datastoreOb.metadata['tags'] != recd.tags: recd.datastoreOb.metadata['tags'] = recd.tags datastore.write(recd.datastoreOb) #reset for the next title change if not closing... recd.metaChange = False #save the title to the xml recd.savedMedia = True _saveXml(el, recd) else: #this will remove the media from being accessed on the local disk since it puts it away into cold storage #therefore this is only called when write_file is called by the activity superclass mediaObject = datastore.create() mediaObject.metadata['title'] = recd.title mediaObject.metadata['tags'] = recd.tags datastorePreviewPixbuf = recd.getThumbPixbuf() if recd.type == constants.TYPE_AUDIO: datastorePreviewPixbuf = recd.getAudioImagePixbuf() elif recd.type == constants.TYPE_PHOTO: datastorePreviewFilepath = recd.getMediaFilepath() datastorePreviewPixbuf = gtk.gdk.pixbuf_new_from_file( datastorePreviewFilepath) if datastorePreviewPixbuf: datastorePreviewWidth = 300 datastorePreviewHeight = 225 if datastorePreviewPixbuf.get_width() != datastorePreviewWidth: datastorePreviewPixbuf = datastorePreviewPixbuf.scale_simple( datastorePreviewWidth, datastorePreviewHeight, gtk.gdk.INTERP_NEAREST) datastorePreview = utils.getStringFromPixbuf( datastorePreviewPixbuf) mediaObject.metadata['preview'] = dbus.ByteArray(datastorePreview) colors = str(recd.colorStroke) + "," + str(recd.colorFill) mediaObject.metadata['icon-color'] = colors mtype = constants.MEDIA_INFO[recd.type] mediaObject.metadata['mime_type'] = mtype['mime'] mediaObject.metadata['activity_id'] = activity._activity_id mediaFile = recd.getMediaFilepath() mediaObject.file_path = mediaFile mediaObject.transfer_ownership = True datastore.write(mediaObject) recd.datastoreId = mediaObject.object_id recd.savedMedia = True _saveXml(el, recd) recd.mediaFilename = None
def ReadValue(self): print('TX Bytes read: ' + repr(self.tx_bytes)) return dbus.ByteArray(self.tx_bytes)
def __state_change_cb(self, download, gparamspec): state = self._download.get_status() if state == WebKit.DownloadStatus.STARTED: # Check free space and cancel the download if there is not enough. total_size = self._download.get_total_size() logging.debug('Total size of the file: %s', total_size) enough_space = self.enough_space(total_size, path=self.temp_path) if not enough_space: logging.debug('Download canceled because of Disk Space') self.cancel() self._canceled_alert = Alert() self._canceled_alert.props.title = _('Not enough space ' 'to download') total_size_mb = total_size / 1024.0**2 free_space_mb = (self._free_available_space( path=self.temp_path) - SPACE_THRESHOLD) \ / 1024.0 ** 2 filename = self._download.get_suggested_filename() self._canceled_alert.props.msg = \ _('Download "%{filename}" requires %{total_size_in_mb}' ' MB of free space, only %{free_space_in_mb} MB' ' is available' % {'filename': filename, 'total_size_in_mb': format_float(total_size_mb), 'free_space_in_mb': format_float(free_space_mb)}) ok_icon = Icon(icon_name='dialog-ok') self._canceled_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon) ok_icon.show() self._canceled_alert.connect('response', self.__stop_response_cb) self._activity.add_alert(self._canceled_alert) else: # FIXME: workaround for SL #4385 # self._download.connect('notify::progress', # self.__progress_change_cb) self._download.connect('notify::current-size', self.__current_size_changed_cb) self._create_journal_object() self._object_id = self.dl_jobject.object_id alert = TimeoutAlert(9) alert.props.title = _('Download started') alert.props.msg = _('%s' % self._download.get_suggested_filename()) self._activity.add_alert(alert) alert.connect('response', self.__start_response_cb) alert.show() global _active_downloads _active_downloads.append(self) elif state == WebKit.DownloadStatus.FINISHED: self._stop_alert = Alert() self._stop_alert.props.title = _('Download completed') self._stop_alert.props.msg = \ _('%s' % self._download.get_suggested_filename()) open_icon = Icon(icon_name='zoom-activity') self._stop_alert.add_button(Gtk.ResponseType.APPLY, _('Show in Journal'), open_icon) open_icon.show() ok_icon = Icon(icon_name='dialog-ok') self._stop_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon) ok_icon.show() self._activity.add_alert(self._stop_alert) self._stop_alert.connect('response', self.__stop_response_cb) self._stop_alert.show() if self._progress_sid is not None: GObject.source_remove(self._progress_sid) self.dl_jobject.metadata['title'] = \ self._download.get_suggested_filename() self.dl_jobject.metadata['description'] = _('From: %s') \ % self._source self.dl_jobject.metadata['progress'] = '100' self.dl_jobject.file_path = self._dest_path # sniff for a mime type, no way to get headers from WebKit sniffed_mime_type = mime.get_for_file(self._dest_path) self.dl_jobject.metadata['mime_type'] = sniffed_mime_type if sniffed_mime_type in ('image/bmp', 'image/gif', 'image/jpeg', 'image/png', 'image/tiff'): preview = self._get_preview() if preview is not None: self.dl_jobject.metadata['preview'] = \ dbus.ByteArray(preview) datastore.write(self.dl_jobject, transfer_ownership=True, reply_handler=self.__internal_save_cb, error_handler=self.__internal_error_cb, timeout=360) elif state == WebKit.DownloadStatus.CANCELLED: self.cleanup()
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt, config): '''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 = '%s/%s' % (SETTINGS_OBJ, 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]) if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_802_1X: settings['802-1x'] = config['802-1x'] 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 wifi_connect(ssid, iface="wlan0"): m = md5.new() m.update(ssid["ssid"]) id = uuid.UUID(m.hexdigest()) our_uuid = str(id) s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'uuid': our_uuid, 'id': ssid["ssid"] }) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray(ssid["ssid"]), 'mode': "infrastructure" }) s_wsec = dbus.Dictionary({ 'key-mgmt': 'wpa-psk', 'auth-alg': 'open', 'psk': ssid["password"] }) s_ip4 = dbus.Dictionary({'method': 'auto'}) s_ip6 = dbus.Dictionary({'method': 'auto'}) con = dbus.Dictionary({ 'connection': s_con, '802-11-wireless': s_wifi, '802-11-wireless-security': s_wsec, 'ipv4': s_ip4, 'ipv6': s_ip6 }) bus = dbus.SystemBus() service_name = "org.freedesktop.NetworkManager" proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") iface = iface proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager") nm = dbus.Interface(proxy, "org.freedesktop.NetworkManager") devpath = nm.GetDeviceByIpIface(iface) # Find our existing hotspot connection connection_path = None for path in settings.ListConnections(): proxy = bus.get_object(service_name, path) settings_connection = dbus.Interface( proxy, "org.freedesktop.NetworkManager.Settings.Connection") config = settings_connection.GetSettings() if config['connection']['uuid'] == our_uuid: settings_connection.Update(con) connection_path = path break # If the hotspot connection didn't already exist, add it if not connection_path: connection_path = settings.AddConnection(con) proxy = bus.get_object(service_name, devpath) device = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Device") acpath = nm.ActivateConnection(connection_path, devpath, "/") proxy = bus.get_object(service_name, acpath) active_props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") # Wait to connect start = time.time() while time.time() < start + 30: try: state = active_props.Get( "org.freedesktop.NetworkManager.Connection.Active", "State") if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED print "Connected to access point" return True except Exception as e: pass time.sleep(1) return False
def test(q, bus, mc): account_manager = AccountManager(bus) # Check AccountManager has D-Bus property interface call_async(q, account_manager.Properties, 'GetAll', cs.AM) properties, = q.expect('dbus-return', method='GetAll').value assert properties is not None assert properties.get('ValidAccounts') == [], \ properties.get('ValidAccounts') assert properties.get('InvalidAccounts') == [], \ properties.get('InvalidAccounts') interfaces = properties.get('Interfaces') supported = properties.get('SupportedAccountProperties') assert (cs.ACCOUNT + '.AutomaticPresence') in supported assert (cs.ACCOUNT + '.Enabled') in supported assert (cs.ACCOUNT + '.Icon') in supported assert (cs.ACCOUNT + '.Nickname') in supported assert (cs.ACCOUNT + '.ConnectAutomatically') in supported assert (cs.ACCOUNT_IFACE_AVATAR + '.Avatar') in supported assert (cs.ACCOUNT + '.RequestedPresence') in supported assert (cs.ACCOUNT + '.Supersedes') in supported assertContains(cs.ACCOUNT + '.Service', supported) params = dbus.Dictionary( { "account": "*****@*****.**", "password": "******" }, signature='sv') simulated_cm = SimulatedConnectionManager(q, bus) creation_properties = dbus.Dictionary( { cs.ACCOUNT + '.Enabled': True, cs.ACCOUNT + '.AutomaticPresence': dbus.Struct((dbus.UInt32(cs.PRESENCE_BUSY), 'busy', 'Exploding'), signature='uss'), cs.ACCOUNT + '.RequestedPresence': dbus.Struct((dbus.UInt32(cs.PRESENCE_AWAY), 'away', 'Respawning'), signature='uss'), cs.ACCOUNT + '.Icon': 'quake3arena', cs.ACCOUNT + '.Nickname': 'AnArKi', cs.ACCOUNT + '.ConnectAutomatically': True, cs.ACCOUNT_IFACE_AVATAR + '.Avatar': (dbus.ByteArray('foo'), 'image/jpeg'), cs.ACCOUNT + '.Supersedes': dbus.Array([ cs.ACCOUNT_PATH_PREFIX + 'q1/q1/Ranger', cs.ACCOUNT_PATH_PREFIX + 'q2/q2/Grunt', ], signature='o'), cs.ACCOUNT + '.Service': 'arena', }, signature='sv') call_async(q, account_manager, 'CreateAccount', 'fakecm', 'fakeprotocol', 'fakeaccount', params, creation_properties) # The spec has no order guarantee here. # FIXME: MC ought to also introspect the CM and find out that the params # are in fact sufficient am_signal, ret, rc = q.expect_many( EventPattern('dbus-signal', path=cs.AM_PATH, signal='AccountValidityChanged', interface=cs.AM), EventPattern('dbus-return', method='CreateAccount'), EventPattern('dbus-method-call', method='RequestConnection'), ) account_path = ret.value[0] assert am_signal.args == [account_path, True], am_signal.args # We called IdentifyAccount, which normalized the silly account name. # The _xx hex-escaping and the trailing digit are implementation details. assert account_path.endswith('/anarki_40example_2ecom0'), account_path assert account_path is not None account = bus.get_object(cs.tp_name_prefix + '.AccountManager', account_path) account_props = dbus.Interface(account, cs.PROPERTIES_IFACE) properties = account_props.GetAll(cs.ACCOUNT) assert properties.get('AutomaticPresence') == (cs.PRESENCE_BUSY, 'busy', 'Exploding'), \ properties.get('AutomaticPresence') assert properties.get('RequestedPresence') == (cs.PRESENCE_AWAY, 'away', 'Respawning'), \ properties.get('RequestedPresence') assert properties.get('ConnectAutomatically') == True, \ properties.get('ConnectAutomatically') assert properties.get('Enabled') == True, \ properties.get('Enabled') assert properties.get('Valid') == True, \ properties.get('Valid') assert properties.get('Icon') == 'quake3arena', \ properties.get('Icon') assert properties.get('Nickname') == 'AnArKi', \ properties.get('Nickname') assertEquals( dbus.Array([ cs.ACCOUNT_PATH_PREFIX + 'q1/q1/Ranger', cs.ACCOUNT_PATH_PREFIX + 'q2/q2/Grunt', ], signature='o'), properties.get('Supersedes')) assertEquals('arena', properties.get('Service')) properties = account_props.GetAll(cs.ACCOUNT_IFACE_AVATAR) assert properties.get('Avatar') == ([ord('f'), ord('o'), ord('o')], 'image/jpeg') # tests for errors when creating an account creation_properties2 = creation_properties.copy() creation_properties2[cs.ACCOUNT + '.NonExistent'] = 'foo' call_async(q, account_manager, 'CreateAccount', 'fakecm', 'fakeprotocol', 'fakeaccount', params, creation_properties2) q.expect('dbus-error', method='CreateAccount') params2 = params.copy() params2['fake_param'] = 'foo' call_async(q, account_manager, 'CreateAccount', 'fakecm', 'fakeprotocol', 'fakeaccount', params2, creation_properties) q.expect('dbus-error', method='CreateAccount')
def Set(self, iface, prop, value): if iface == ACCOUNT_IFACE: props = {} if prop == 'Service': self._service = str(value) elif prop == 'DisplayName': self._display_name = str(value) elif prop == 'Icon': self._icon = str(value) elif prop == 'Enabled': self._enabled = bool(value) elif prop == 'Nickname': self._nickname = str(value) elif prop == 'AutomaticPresence': self._automatic_presence = dbus.Struct( (dbus.UInt32(value[0]), str(value[1]), str(value[2])), signature='uss') elif prop == 'RequestedPresence': self._requested_presence = dbus.Struct( (dbus.UInt32(value[0]), str(value[1]), str(value[2])), signature='uss') # pretend to put the account online, if the presence != offline if value[0] != Connection_Presence_Type_Offline: # simulate that we are connecting/changing presence props["ChangingPresence"] = True if self._connection_status == Connection_Status_Disconnected: self._connection_status = Connection_Status_Connecting props["ConnectionStatus"] = self._connection_status props[prop] = self._account_props()[prop] self.AccountPropertyChanged(props) props["ChangingPresence"] = False if "(deny)" in self._requested_presence[2]: self._connection_status = Connection_Status_Disconnected self._connection_status_reason = Connection_Status_Reason_Network_Error self._connection_error = TELEPATHY_ERROR_NETWORK_ERROR self._connection_error_details = dbus.Dictionary( {'debug-message': 'You asked for it'}, signature='sv') self._current_presence = dbus.Struct( (Connection_Presence_Type_Offline, 'offline', ''), signature='uss') else: self._connection_status = Connection_Status_Connected self._connection_status_reason = Connection_Status_Reason_None_Specified self._connection_error = '' self._connection_error_details = dbus.Dictionary( {}, signature='sv') self._current_presence = self._requested_presence if self._has_been_online == False: self._has_been_online = True props["HasBeenOnline"] = self._has_been_online else: self._connection_status = Connection_Status_Disconnected self._connection_status_reason = Connection_Status_Reason_Requested self._connection_error = TELEPATHY_ERROR_CANCELLED self._connection_error_details = dbus.Dictionary( {'debug-message': 'You asked for it'}, signature='sv') self._current_presence = dbus.Struct( (Connection_Presence_Type_Offline, 'offline', ''), signature='uss') props["ConnectionStatus"] = self._connection_status props[ "ConnectionStatusReason"] = self._connection_status_reason props["ConnectionError"] = self._connection_error props[ "ConnectionErrorDetails"] = self._connection_error_details props["CurrentPresence"] = self._current_presence elif prop == 'ConnectAutomatically': self._connect_automatically = bool(value) elif prop == 'Connection': self._connection = dbus.ObjectPath(value) else: raise ValueError('Read-only or nonexistent property') props[prop] = self._account_props()[prop] self.AccountPropertyChanged(props) elif iface == ACCOUNT_IFACE_AVATAR_IFACE: if prop == 'Avatar': self._avatar = dbus.Struct( (dbus.ByteArray(value[0]), str(value[1])), signature='ays') self.AvatarChanged() else: raise ValueError('Nonexistent property') else: raise ValueError('No such interface')
# # Configuration settings are described at # https://networkmanager.dev/docs/api/latest/ref-settings.html # import dbus, sys, time our_uuid = "2b0d0f1d-b79d-43af-bde1-71744625642e" s_con = dbus.Dictionary( {"type": "802-11-wireless", "uuid": our_uuid, "id": "Test Hotspot"} ) s_wifi = dbus.Dictionary( { "ssid": dbus.ByteArray("My Hotspot".encode("utf-8")), "mode": "ap", "band": "bg", "channel": dbus.UInt32(1), } ) s_wsec = dbus.Dictionary({"key-mgmt": "wpa-psk", "psk": "great password"}) s_ip4 = dbus.Dictionary({"method": "shared"}) s_ip6 = dbus.Dictionary({"method": "ignore"}) con = dbus.Dictionary( { "connection": s_con, "802-11-wireless": s_wifi,
def hotspot_control(iface, operation, ip, gateway, connection_uuid, network_name): print "attempting config" s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'uuid': connection_uuid, 'id': 'test hotspot' }) addr1 = dbus.Dictionary({'address': ip, 'prefix': dbus.UInt32(8)}) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray(network_name.encode("utf-8")), 'mode': "adhoc", 'band': "bg", 'channel': dbus.UInt32(1) }) s_wsec = dbus.Dictionary({ 'key-mgmt': 'none', 'wep-key0': '0123456789abcdef0123456789' }) # Use link-local for auto IP selection and manual for ability to set gateway etc but ability to manually # configure unique IPs within balena framework isn't yet done s_ip4 = dbus.Dictionary({'method': 'link-local'}) # s_ip4 = dbus.Dictionary({ # 'address-data': dbus.Array([addr1], signature=dbus.Signature('a{sv}')), # 'gateway': gateway, # 'method': 'manual'}) s_ip6 = dbus.Dictionary({'method': 'ignore'}) con = dbus.Dictionary({ 'connection': s_con, '802-11-wireless': s_wifi, '802-11-wireless-security': s_wsec, 'ipv4': s_ip4, 'ipv6': s_ip6 }) bus = dbus.SystemBus() service_name = "org.freedesktop.NetworkManager" proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager") nm = dbus.Interface(proxy, "org.freedesktop.NetworkManager") devpath = nm.GetDeviceByIpIface(iface) # Find the existing hotspot connection if it exists connection_path = None for path in settings.ListConnections(): proxy = bus.get_object(service_name, path) settings_connection = dbus.Interface( proxy, "org.freedesktop.NetworkManager.Settings.Connection") config = settings_connection.GetSettings() if config['connection']['uuid'] == connection_uuid: connection_path = path break # If the hotspot connection didn't already exist, add it if not connection_path: connection_path = settings.AddConnection(con) print "got a connection path" # Now start or stop the hotspot on the requested device proxy = bus.get_object(service_name, devpath) device = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Device") if operation == "up": acpath = nm.ActivateConnection(connection_path, devpath, "/") proxy = bus.get_object(service_name, acpath) active_props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") state = active_props.Get( "org.freedesktop.NetworkManager.Connection.Active", "State") print "started access point" print "Access point started, state: {}".format(state) elif operation == "down": device.Disconnect() print "Access point stopped" return
import dbus, uuid def path_to_value(path): return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8")) s_con = dbus.Dictionary({ "type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My Wifi" }) s_wifi = dbus.Dictionary({ "ssid": dbus.ByteArray("homewifi".encode("utf-8")), "security": "802-11-wireless-security", }) s_wsec = dbus.Dictionary({"key-mgmt": "wpa-eap"}) s_8021x = dbus.Dictionary({ "eap": ["tls"], "identity": "Bill Smith", "client-cert": path_to_value("/some/place/client.pem"), "ca-cert": path_to_value("/some/place/ca-cert.pem"), "private-key": path_to_value("/some/place/privkey.pem"),
def load(mock, parameters): global _parameters _parameters = parameters mock.set_hotspot_enabled = set_hotspot_enabled mock.set_hotspot_ssid = set_hotspot_ssid mock.set_hotspot_password = set_hotspot_password mock.set_wifi_enabled = set_wifi_enabled mock.set_hotspot_auth = set_hotspot_auth mock.add_vpn_connection = add_vpn_connection mock.remove_vpn_connection = remove_vpn_connection mock.AddObject( NETS_OBJ, NETS_IFACE, { 'HotspotSsid': _parameters.get('HotspotSsid', dbus.ByteArray('Ubuntu'.encode('UTF-8'))), 'HotspotEnabled': _parameters.get('HotspotEnabled', dbus.Boolean(False)), 'HotspotMode': _parameters.get('HotspotMode', dbus.String('ap')), 'HotspotStored': _parameters.get('HotspotStored', dbus.Boolean(False)), 'ModemAvailable': _parameters.get('ModemAvailable', dbus.Boolean(True)), 'FlightModeSwitchEnabled': _parameters.get('FlightModeSwitchEnabled', dbus.Boolean(False)), 'WifiSwitchEnabled': _parameters.get('WifiSwitchEnabled', dbus.Boolean(False)), 'HotspotSwitchEnabled': _parameters.get('HotspotSwitchEnabled', dbus.Boolean(False)), 'FlightMode': _parameters.get('FlightMode', dbus.Boolean(False)), 'WifiEnabled': _parameters.get('WifiEnabled', dbus.Boolean(False)), # One of online, offline and connecting. 'Status': _parameters.get('Status', 'offline') }, []) mock.AddObject( PRIV_OBJ, PRIV_IFACE, { 'HotspotPassword': _parameters.get('HotspotPassword', dbus.String('abcdefgh')), 'HotspotAuth': _parameters.get('HotspotAuth', dbus.String('wpa-psk')), 'VpnConnections': _parameters.get('VpnConnections', dbus.Array([], signature='o')), 'MobileDataEnabled': _parameters.get('MobileDataEnabled', dbus.Boolean(False)), 'SimForMobileData': _parameters.get('SimForMobileData', dbus.ObjectPath('/')), 'Modems': _parameters.get('Modems', dbus.Array([], signature='o')), 'Sims': _parameters.get('Sims', dbus.Array([], signature='o')) }, [('UnlockAllModems', '', '', ''), ('UnlockModem', 's', '', ''), ('SetFlightMode', 'b', '', ''), ('SetWifiEnabled', 'b', '', 'objects["/"].set_wifi_enabled(self, args[0])'), ('SetHotspotSsid', 'ay', '', 'objects["/"].set_hotspot_ssid(self, args[0])'), ('SetHotspotPassword', 's', '', 'objects["/"].set_hotspot_password(self, args[0])'), ('SetHotspotAuth', 's', '', 'objects["/"].set_hotspot_auth(self, args[0])'), ('SetHotspotEnabled', 'b', '', 'objects["/"].set_hotspot_enabled(self, args[0])'), ('SetHotspotMode', 's', '', ''), ('AddVpnConnection', 'u', 'o', 'ret = objects["/"].add_vpn_connection(self, args[0])'), ('RemoveVpnConnection', 'o', '', 'objects["/"].remove_vpn_connection(self, args[0])')])
def path_to_value(path): return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8"))
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( f'Access point with SSID [{ssid_name}] could not be found', name=MANAGER_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( f'Connection {connection_name} on device {dev_path} already exists', name=MANAGER_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, { '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])'), ]) self.object_manager_emit_added(connection_path) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate 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]) # pylint: disable=undefined-loop-variable return connection_path
def session(self) -> Optional[str]: if not self._session: secrets = self.bus.get_object(self.BUS_NAME, '/org/freedesktop/secrets') iface = dbus.Interface(secrets, 'org.freedesktop.Secret.Service') if not self.crypto.active: _output, session_path = iface.OpenSession('plain', '') else: server_pubkey, session_path = iface.OpenSession('dh-ietf1024-sha256-aes128-cbc-pkcs7', dbus.ByteArray(self.crypto.pubkey_as_bytes())) self.crypto.set_server_public_key(server_pubkey) self._session = session_path return self._session
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))
import dbus, sys, time, os our_uuid = '2b0d0f1d-b79d-43af-bde1-71744625642e' s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'autoconnect': False, 'uuid': our_uuid, 'id': 'Test Hotspot', 'interface-name': 'wlan0' }) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray(os.environ['PP_SSID'].encode("utf-8")), 'mac-address-randomization': dbus.UInt32(0), 'mode': "ap", 'band': "bg" }) s_wsec = dbus.Dictionary({'key-mgmt': 'wpa-psk', 'psk': '6rsprinter'}) s_ip4 = dbus.Dictionary({'method': 'shared'}) s_ip6 = dbus.Dictionary({'method': 'ignore'}) con = dbus.Dictionary({ 'connection': s_con,
def __add_connection(self, ssid): debug("Adding connection: " + ssid) server_alt_subject_name_list = dbus.Array(Config.servers) server_name = Config.server_match if self.nm_version == "0.9" or self.nm_version == "1.0": match_key = 'altsubject-matches' match_value = server_alt_subject_name_list else: match_key = 'subject-match' match_value = server_name s_8021x_data = { 'eap': [Config.eap_outer.lower()], 'identity': self.user_data.username, 'ca-cert': dbus.ByteArray("file://{0}\0".format( self.cacert_file).encode('utf8')), match_key: match_value } if Config.eap_outer == 'PEAP' or Config.eap_outer == 'TTLS': s_8021x_data['password'] = self.user_data.password s_8021x_data['phase2-auth'] = Config.eap_inner.lower() if Config.anonymous_identity != '': s_8021x_data['anonymous-identity'] = Config.anonymous_identity s_8021x_data['password-flags'] = 0 if Config.eap_outer == 'TLS': s_8021x_data['client-cert'] = dbus.ByteArray("file://{0}\0".format( self.pfx_file).encode('utf8')) s_8021x_data['private-key'] = dbus.ByteArray("file://{0}\0".format( self.pfx_file).encode('utf8')) s_8021x_data['private-key-password'] = self.user_data.password s_8021x_data['private-key-password-flags'] = 0 s_con = dbus.Dictionary({ 'type': '802-11-wireless', 'uuid': str(uuid.uuid4()), 'permissions': ['user:'******'USER')], 'id': ssid }) s_wifi = dbus.Dictionary({ 'ssid': dbus.ByteArray(ssid.encode('utf8')), 'security': '802-11-wireless-security' }) s_wsec = dbus.Dictionary({ 'key-mgmt': 'wpa-eap', 'proto': ['rsn'], 'pairwise': ['ccmp'], 'group': ['ccmp', 'tkip'] }) s_8021x = dbus.Dictionary(s_8021x_data) s_ip4 = dbus.Dictionary({'method': 'auto'}) s_ip6 = dbus.Dictionary({'method': 'auto'}) con = dbus.Dictionary({ 'connection': s_con, '802-11-wireless': s_wifi, '802-11-wireless-security': s_wsec, '802-1x': s_8021x, 'ipv4': s_ip4, 'ipv6': s_ip6 }) self.settings.AddConnection(con)
def test_keyfile(q, bus, mc, how_old='5.12'): simulated_cm = SimulatedConnectionManager(q, bus) if how_old == '5.12': # This is not actually ~/.mission-control, but it uses the same # code paths. dot_mission_control = os.environ['MC_ACCOUNT_DIR'] old_key_file_name = os.path.join(dot_mission_control, 'accounts.cfg') os.makedirs(dot_mission_control + '/fakecm/fakeprotocol/dontdivert1_40example_2ecom0') avatar_bin = open( dot_mission_control + '/fakecm/fakeprotocol/dontdivert1_40example_2ecom0/avatar.bin', 'w') avatar_bin.write('hello, world') avatar_bin.close() elif how_old == '5.14': # Same format, different location. old_key_file_name = os.path.join(os.environ['XDG_DATA_HOME'], 'telepathy', 'mission-control', 'accounts.cfg') # exercise override of an avatar in XDG_DATA_DIRS avatar_dir = (os.environ['XDG_DATA_DIRS'].split(':')[0] + '/telepathy/mission-control') os.makedirs(avatar_dir) avatar_bin = open( avatar_dir + '/fakecm-fakeprotocol-dontdivert1_40example_2ecom0.avatar', 'w') avatar_bin.write('hello, world') avatar_bin.close() else: raise AssertionError('Unsupported value for how_old') a1_new_variant_file_name = os.path.join( os.environ['XDG_DATA_HOME'], 'telepathy', 'mission-control', 'fakecm-fakeprotocol-dontdivert1_40example_2ecom0.account') a1_tail = 'fakecm/fakeprotocol/dontdivert1_40example_2ecom0' a2_new_variant_file_name = os.path.join( os.environ['XDG_DATA_HOME'], 'telepathy', 'mission-control', 'fakecm-fakeprotocol-dontdivert2_40example_2ecom0.account') a2_tail = 'fakecm/fakeprotocol/dontdivert2_40example_2ecom0' try: os.makedirs(os.path.dirname(old_key_file_name), 0700) except OSError as e: if e.errno != errno.EEXIST: raise open(old_key_file_name, 'w').write(r"""# Telepathy accounts [%s] manager=fakecm protocol=fakeprotocol [email protected] param-password=1 DisplayName=First among equals AutomaticPresence=2;available;; AvatarMime=text/plain avatar_token=hello, world [%s] manager=fakecm protocol=fakeprotocol [email protected] param-password=2 DisplayName=Second to none AutomaticPresence=2;available;; """ % (a1_tail, a2_tail)) mc = MC(q, bus) account_manager, properties, interfaces = connect_to_mc(q, bus, mc) # During MC startup, it moved the old keyfile's contents into # variant-based files, and deleted the old keyfile. assert not os.path.exists(old_key_file_name) assert os.path.exists(a1_new_variant_file_name) assert os.path.exists(a2_new_variant_file_name) assertEquals( "'First among equals'", account_store('get', 'variant-file', 'DisplayName', account=a1_tail)) assertEquals( "'Second to none'", account_store('get', 'variant-file', 'DisplayName', account=a2_tail)) # Because the CM is installed, we can work out the right types # for the parameters, too. assertEquals( "'*****@*****.**'", account_store('get', 'variant-file', 'param-account', account=a1_tail)) assertEquals( "'*****@*****.**'", account_store('get', 'variant-file', 'param-account', account=a2_tail)) # Also, MC has both accounts in memory... assertContains(cs.ACCOUNT_PATH_PREFIX + a1_tail, properties['ValidAccounts']) account = get_fakecm_account(bus, mc, cs.ACCOUNT_PATH_PREFIX + a1_tail) assertEquals('*****@*****.**', account.Properties.Get(cs.ACCOUNT, 'Parameters')['account']) assertEquals('First among equals', account.Properties.Get(cs.ACCOUNT, 'DisplayName')) assertEquals((dbus.ByteArray('hello, world'), 'text/plain'), account.Properties.Get(cs.ACCOUNT_IFACE_AVATAR, 'Avatar', byte_arrays=True)) assertContains(cs.ACCOUNT_PATH_PREFIX + a2_tail, properties['ValidAccounts']) account = get_fakecm_account(bus, mc, cs.ACCOUNT_PATH_PREFIX + a2_tail) assertEquals('*****@*****.**', account.Properties.Get(cs.ACCOUNT, 'Parameters')['account']) assertEquals('Second to none', account.Properties.Get(cs.ACCOUNT, 'DisplayName')) # ... and no other accounts. assertLength(2, properties['ValidAccounts'])