static void handleMethodCall(GDBusConnection       *connection,
							 const gchar           *sender,
							 const gchar           *object_path,
							 const gchar           *interface_name,
							 const gchar           *method_name,
							 GVariant              *parameters,
							 GDBusMethodInvocation *invocation,
							 gpointer               user_data)
{

	AutomotiveManager* manager = static_cast<AutomotiveManager*>(user_data);

	std::string method = method_name;

	uint pid = getPid(sender);

	if(DebugOut::getDebugThreshhold() >= 6)
	{
		DebugOut(6)<<"DBus method call from: "<<sender<< " pid: " <<pid<< " interface: "<<interface_name<<" method: "<<method<<endl;
		DebugOut(6)<<"DBus method call path: "<<object_path<<endl;
	}

	if(method == "FindObject")
	{
		gchar* arg;

		g_variant_get(parameters,"(s)",&arg);

		std::string objectToFind = arg;

		if(objectToFind == "")
		{
			g_dbus_method_invocation_return_error(invocation,G_DBUS_ERROR,G_DBUS_ERROR_INVALID_ARGS, "Invalid argument.");
			return;
		}

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(objectToFind);

		if(!interfaces.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Object not found");
			return;
		}

		GVariantBuilder params;
		g_variant_builder_init(&params, G_VARIANT_TYPE_ARRAY);

		bool hasItems = false;

		for(auto itr = interfaces.begin(); itr != interfaces.end(); itr++)
		{
			AbstractDBusInterface* t = *itr;
			if(!t->isSupported())
				continue;

			hasItems = true;

			if(!t->isRegistered())
				t->registerObject();

			std::list<std::string> processes = manager->subscribedProcesses[t];

			if(!contains(processes,sender))
			{
				DebugOut()<<"Referencing "<<t->objectPath()<<" with sender: "<<sender<<endl;
				manager->subscribedProcesses[t].push_back(sender);
			}

			GVariant *newvar = g_variant_new("o",t->objectPath().c_str());
			g_variant_builder_add_value(&params, newvar);
		}

		if(hasItems)
			g_dbus_method_invocation_return_value(invocation, g_variant_new("(ao)",&params));
		else
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Property not found");

	}

	else if(method == "FindObjectForZone")
	{
		gchar* arg;
		int zone;

		g_variant_get(parameters,"(si)", &arg, &zone);

		std::string propertyToFind = arg;

		if(propertyToFind == "")
		{
			g_dbus_method_invocation_return_error(invocation,G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid argument.");
			return;
		}

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(propertyToFind);

		if(!interfaces.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation, "org.automotive.Manager.ObjectNotFound", "Property not found");
			return;
		}



		for(auto itr = interfaces.begin(); itr != interfaces.end(); itr++)
		{
			AbstractDBusInterface* t = *itr;

			if(t->zone() == (Zone::Type)zone)
			{
				if(!t->isRegistered())
					t->registerObject();

				std::list<std::string> processes = manager->subscribedProcesses[t];

				if(!contains(processes,sender))
				{
					DebugOut()<<"Referencing "<<t->objectPath()<<" with sender: "<<sender<<endl;
					manager->subscribedProcesses[t].push_back(sender);
				}

				g_dbus_method_invocation_return_value(invocation,g_variant_new("(o)", t->objectPath().c_str()));
				return;
			}
		}

		g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.InvalidZone", "zone not found");
	}

	else if (method == "ZonesForObjectName")
	{
		gchar* arg;

		g_variant_get(parameters,"(s)",&arg);

		std::string propertyToFind = arg;

		if(propertyToFind == "")
		{
			g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid argument.");
			return;
		}

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(propertyToFind);

		if(!interfaces.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Property not found");
			return;
		}

		GVariantBuilder params;
		g_variant_builder_init(&params, G_VARIANT_TYPE_ARRAY);

		for(auto itr = interfaces.begin(); itr != interfaces.end(); itr++)
		{
			AbstractDBusInterface* t = *itr;
			GVariant *newvar = g_variant_new("i",t->zone());
			g_variant_builder_add_value(&params, newvar);

		}

		g_dbus_method_invocation_return_value(invocation,g_variant_new("(ai)",&params));
	}

	else if(method == "List")
	{
		std::list<AbstractDBusInterface*> list = AbstractDBusInterface::interfaces();

		if(!list.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.Error", "No supported objects");
			return;
		}

		GVariantBuilder builder;
		g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);


		for(auto itr = list.begin(); itr != list.end(); itr++)
		{
			if(!(*itr)->isSupported())
				continue;

			std::string objectName = (*itr)->objectName();

			g_variant_builder_add(&builder, "s", objectName.c_str());
		}


		g_dbus_method_invocation_return_value(invocation,g_variant_new("(as)",&builder));
	}
	else if(method == "SourcesForObjectName")
	{
		gchar* arg;

		g_variant_get(parameters,"(s)",&arg);

		std::string propertyToFind = arg;

		if(propertyToFind == "")
		{
			g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid argument.");
			return;
		}

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(propertyToFind);

		if(!interfaces.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Property not found");
			return;
		}

		GVariantBuilder params;
		g_variant_builder_init(&params, G_VARIANT_TYPE_ARRAY);

		for(auto itr = interfaces.begin(); itr != interfaces.end(); itr++)
		{
			AbstractDBusInterface* t = *itr;
			string source = t->source();
			boost::algorithm::erase_all(source, "-");
			GVariant *newvar = g_variant_new("s", source.c_str());
			g_variant_builder_add_value(&params, newvar);

		}

		g_dbus_method_invocation_return_value(invocation,g_variant_new("(as)",&params));
	}
	else if(method == "FindObjectForSourceZone")
	{
		gchar* arg;
		gchar* arg2;
		int zone;

		g_variant_get(parameters,"(ssi)", &arg, &arg2, &zone);

		std::string propertyToFind = arg;
		std::string source = arg2;

		if(propertyToFind == "" || source == "")
		{
			g_dbus_method_invocation_return_error(invocation,G_DBUS_ERROR,G_DBUS_ERROR_INVALID_ARGS, "Invalid argument.");
			return;
		}

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(propertyToFind);

		if(!interfaces.size())
		{
			g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Property not found");
			return;
		}

		for(auto itr = interfaces.begin(); itr != interfaces.end(); itr++)
		{
			AbstractDBusInterface* t = *itr;
			string targetSource = t->source();
			boost::algorithm::erase_all(targetSource, "-");
			if(t->zone() == (Zone::Type)zone && source == targetSource)
			{
				if(!t->isRegistered())
					t->registerObject();

				std::list<std::string> processes = manager->subscribedProcesses[t];

				if(!contains(processes,sender))
				{
					DebugOut()<<"Referencing "<<t->objectPath()<<" with sender: "<<sender<<endl;
					manager->subscribedProcesses[t].push_back(sender);
				}

				g_dbus_method_invocation_return_value(invocation,g_variant_new("(o)", t->objectPath().c_str()));
				return;
			}
		}

		g_dbus_method_invocation_return_dbus_error(invocation,"org.automotive.Manager.ObjectNotFound", "Property not found");
	}
	else if(method == "SupportsProperty")
	{
		gchar* objectName;
		gchar* propertyToFindStr;

		g_variant_get(parameters,"(ss)",&objectName, &propertyToFindStr);

		auto objectNamePtr = amb::make_super(objectName);
		auto propertyToFindStrPtr = amb::make_super(propertyToFindStr);

		DebugOut(6) << "Checking " << objectNamePtr.get() << " for member: " << propertyToFindStrPtr.get() << endl;

		std::list<AbstractDBusInterface*> interfaces = AbstractDBusInterface::getObjectsForProperty(objectNamePtr.get());

		for(auto i : interfaces)
		{
			if(i->hasPropertyDBus(propertyToFindStrPtr.get()))
			{
				DebugOut(6) << "member " << propertyToFindStrPtr.get() << " of " << objectNamePtr.get() << " was found!!" << endl;
				g_dbus_method_invocation_return_value(invocation, g_variant_new("(b)", true));
				return;
			}
		}
		DebugOut(6) << "member " << propertyToFindStrPtr.get() << " of " << objectNamePtr.get() << " was not found." << endl;
		g_dbus_method_invocation_return_value(invocation,g_variant_new("(b)", false));
	}
	else
	{
		g_dbus_method_invocation_return_error(invocation,G_DBUS_ERROR,G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method.");
	}
}
static GVariant *
rpmostreed_deployment_gpg_results (OstreeRepo *repo,
                                   const gchar *origin_refspec,
                                   const gchar *csum,
                                   gboolean *out_enabled)
{
    GError *error = NULL;
    GVariant *ret = NULL;

    g_autofree gchar *remote = NULL;
    glnx_unref_object OstreeGpgVerifyResult *result = NULL;

    guint n_sigs, i;
    gboolean gpg_verify;
    GVariantBuilder builder;

    g_variant_builder_init (&builder, G_VARIANT_TYPE ("av"));

    if (!ostree_parse_refspec (origin_refspec, &remote, NULL, &error))
        goto out;

    if (remote)
    {
        if (!ostree_repo_remote_get_gpg_verify (repo, remote, &gpg_verify, &error))
            goto out;
    }
    else
    {
        gpg_verify = FALSE;
    }

    *out_enabled = gpg_verify;
    if (!gpg_verify)
        goto out;


    result = ostree_repo_verify_commit_ext (repo, csum, NULL, NULL,
                                            NULL, &error);
    if (!result)
        goto out;

    n_sigs = ostree_gpg_verify_result_count_all (result);
    if (n_sigs < 1)
        goto out;

    for (i = 0; i < n_sigs; i++)
    {
        g_variant_builder_add (&builder, "v",
                               ostree_gpg_verify_result_get_all (result, i));
    }

    ret = g_variant_builder_end (&builder);

out:

    /* NOT_FOUND just means the commit is not signed. */
    if (error && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
        g_warning ("error loading gpg verify result %s", error->message);

    g_clear_error (&error);
    return ret;
}
void
ccsGSettingsIntegratedSettingWriteValue (CCSIntegratedSetting *setting, CCSSettingValue *v, CCSSettingType type)
{
    CCSGSettingsIntegratedSettingPrivate *priv = (CCSGSettingsIntegratedSettingPrivate *) ccsObjectGetPrivate (setting);
    const char			     *gnomeKeyName = ccsGNOMEIntegratedSettingInfoGetGNOMEName ((CCSGNOMEIntegratedSettingInfo *) setting);
    char			     *gsettingsTranslatedName = ccsGSettingsIntegratedSettingsTranslateOldGNOMEKeyForGSettings (gnomeKeyName);

    GVariant           *variant = ccsGSettingsWrapperGetValue (priv->wrapper, gsettingsTranslatedName);
    const GVariantType *variantType = g_variant_get_type (variant);
    GVariant           *newVariant = NULL;

    if (!variant)
    {
	ccsError ("NULL encountered while reading GSettings value");
	free (gsettingsTranslatedName);
	return;
    }

    switch (type)
    {
	case TypeInt:
	    {
		if (!g_variant_type_equal (variantType, G_VARIANT_TYPE_INT32))
		    ccsError ("Expected integer value");
		else
		{
		    int currentValue = readIntFromVariant (variant);

		    if ((currentValue != v->value.asInt))
			writeIntToVariant (v->value.asInt, &newVariant);
		}
	    }
	    break;
	case TypeBool:
	    {
		if (!g_variant_type_equal (variantType, G_VARIANT_TYPE_BOOLEAN))
		    ccsError ("Expected boolean value");
		else
		{
		    gboolean currentValue = readBoolFromVariant (variant);

		    if ((currentValue != v->value.asBool))
			writeBoolToVariant (v->value.asBool, &newVariant);
		}
	    }
	    break;
	case TypeString:
	    {
		if (!g_variant_type_equal (variantType, G_VARIANT_TYPE_STRING))
		    ccsError ("Expected string value");
		else
		{
		    const char  *defaultValue = "";
		    const char  *newValue = v->value.asString ? v->value.asString : defaultValue;
		    gsize len = 0;
		    const gchar *currentValue = g_variant_get_string (variant, &len);

		    if (currentValue)
		    {
			if (strcmp (currentValue, newValue) != 0)
			    writeStringToVariant (newValue, &newVariant);
		    }
		}
	    }
	    break;
	case TypeKey:
	    {
		if (!g_variant_type_equal (variantType, G_VARIANT_TYPE ("as")))
		    ccsError ("Expected array-of-string value");
		else
		{
		    const char  *defaultValue = "";
		    GVariantBuilder strvBuilder;

		    g_variant_builder_init (&strvBuilder, G_VARIANT_TYPE ("as"));
		    g_variant_builder_add (&strvBuilder, "s", v->value.asString ? v->value.asString :  defaultValue);
		    newVariant = g_variant_builder_end (&strvBuilder);
		}
	    }
	    break;
	default:
	    g_assert_not_reached ();
	    break;
    }

    /* g_settings_set_value consumes the reference */
    if (newVariant)
	ccsGSettingsWrapperSetValue (priv->wrapper, gsettingsTranslatedName, newVariant);

    g_variant_unref (variant);
    free (gsettingsTranslatedName);
}
Пример #4
0
  static GVariant *BuildRecording(const cRecording *recording)
  {
    GVariantBuilder *struc = g_variant_builder_new(G_VARIANT_TYPE("(ia(sv))"));
    GVariantBuilder *array = g_variant_builder_new(G_VARIANT_TYPE("a(sv)"));
    if (recording == NULL)
       g_variant_builder_add(struc, "i", -1);
    else {
       g_variant_builder_add(struc, "i", recording->Index() + 1);
       cString s;
       const char *c;
       gboolean b;
       guint64 tu64;
       int i;
       gdouble d;

       c = recording->FileName();
       if (c != NULL)
          cDBusHelper::AddKeyValue(array, "Path", "s", (void**)&c);
       c = recording->Name();
       if (c != NULL)
          cDBusHelper::AddKeyValue(array, "Name", "s", (void**)&c);
       c = recording->Title();
       if (c != NULL)
          cDBusHelper::AddKeyValue(array, "Title", "s", (void**)&c);
       tu64 = recording->Start();
       if (tu64 > 0)
          cDBusHelper::AddKeyValue(array, "Start", "t", (void**)&tu64);
       tu64 = recording->Deleted();
       if (tu64 > 0)
          cDBusHelper::AddKeyValue(array, "Deleted", "t", (void**)&tu64);
       i = recording->Priority();
       cDBusHelper::AddKeyValue(array, "Priority", "i", (void**)&i);
       i = recording->Lifetime();
       cDBusHelper::AddKeyValue(array, "Lifetime", "i", (void**)&i);
       i = recording->HierarchyLevels();
       cDBusHelper::AddKeyValue(array, "HierarchyLevels", "i", (void**)&i);
       d = recording->FramesPerSecond();
       cDBusHelper::AddKeyValue(array, "FramesPerSecond", "d", (void**)&d);
       i = recording->NumFrames();
       cDBusHelper::AddKeyValue(array, "NumFrames", "i", (void**)&i);
       i = recording->LengthInSeconds();
       cDBusHelper::AddKeyValue(array, "LengthInSeconds", "i", (void**)&i);
       i = recording->FileSizeMB();
       cDBusHelper::AddKeyValue(array, "FileSizeMB", "i", (void**)&i);
       b = recording->IsPesRecording() ? TRUE : FALSE;
       cDBusHelper::AddKeyValue(array, "IsPesRecording", "b", (void**)&b);
       b = recording->IsNew() ? TRUE : FALSE;
       cDBusHelper::AddKeyValue(array, "IsNew", "b", (void**)&b);
       b = recording->IsEdited() ? TRUE : FALSE;
       cDBusHelper::AddKeyValue(array, "IsEdited", "b", (void**)&b);
       const cRecordingInfo *info = recording->Info();
       if (info != NULL) {
          s = info->ChannelID().ToString();
          c = *s;
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/ChannelID", "s", (void**)&c);
          c = info->ChannelName();
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/ChannelName", "s", (void**)&c);
          c = info->Title();
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/Title", "s", (void**)&c);
          c = info->ShortText();
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/ShortText", "s", (void**)&c);
          c = info->Description();
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/Description", "s", (void**)&c);
          c = info->Aux();
          if (c != NULL)
             cDBusHelper::AddKeyValue(array, "Info/Aux", "s", (void**)&c);
          d = info->FramesPerSecond();
          cDBusHelper::AddKeyValue(array, "Info/FramesPerSecond", "d", (void**)&d);
          const cComponents *components = info->Components();
          if ((components != NULL) && (components->NumComponents() > 0)) {
             for (int comp = 0; comp < components->NumComponents(); comp++) {
                 tComponent *component = components->Component(comp);
                 if (component != NULL) {
                    s = cString::sprintf("Info/Component/%d/stream", comp);
                    i = component->stream;
                    cDBusHelper::AddKeyValue(array, *s, "i", (void**)&i);
                    s = cString::sprintf("Info/Component/%d/type", comp);
                    i = component->type;
                    cDBusHelper::AddKeyValue(array, *s, "i", (void**)&i);
                    if (component->language[0] != 0) {
                       s = cString::sprintf("Info/Component/%d/language", comp);
                       c = component->language;
                       cDBusHelper::AddKeyValue(array, *s, "s", (void**)&c);
                       }
                    if (component->description != NULL) {
                       s = cString::sprintf("Info/Component/%d/description", comp);
                       cDBusHelper::AddKeyValue(array, *s, "s", (void**)&component->description);
                       }
                    }
                 }
             }
          }
       }

    g_variant_builder_add_value(struc, g_variant_builder_end(array));
    GVariant *ret = g_variant_builder_end(struc);
    g_variant_builder_unref(array);
    g_variant_builder_unref(struc);
    return ret;
  };
Пример #5
0
/**
 * fwupd_remote_to_variant:
 * @self: A #FwupdRemote
 *
 * Creates a GVariant from the remote data.
 *
 * Returns: the GVariant, or %NULL for error
 *
 * Since: 1.0.0
 **/
GVariant *
fwupd_remote_to_variant (FwupdRemote *self)
{
	FwupdRemotePrivate *priv = GET_PRIVATE (self);
	GVariantBuilder builder;

	g_return_val_if_fail (FWUPD_IS_REMOTE (self), NULL);

	/* create an array with all the metadata in */
	g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
	if (priv->id != NULL) {
		g_variant_builder_add (&builder, "{sv}", FWUPD_RESULT_KEY_REMOTE_ID,
				       g_variant_new_string (priv->id));
	}
	if (priv->username != NULL) {
		g_variant_builder_add (&builder, "{sv}", "Username",
				       g_variant_new_string (priv->username));
	}
	if (priv->password != NULL) {
		g_variant_builder_add (&builder, "{sv}", "Password",
				       g_variant_new_string (priv->password));
	}
	if (priv->title != NULL) {
		g_variant_builder_add (&builder, "{sv}", "Title",
				       g_variant_new_string (priv->title));
	}
	if (priv->agreement != NULL) {
		g_variant_builder_add (&builder, "{sv}", "Agreement",
				       g_variant_new_string (priv->agreement));
	}
	if (priv->checksum != NULL) {
		g_variant_builder_add (&builder, "{sv}", FWUPD_RESULT_KEY_CHECKSUM,
				       g_variant_new_string (priv->checksum));
	}
	if (priv->metadata_uri != NULL) {
		g_variant_builder_add (&builder, "{sv}", FWUPD_RESULT_KEY_URI,
				       g_variant_new_string (priv->metadata_uri));
	}
	if (priv->report_uri != NULL) {
		g_variant_builder_add (&builder, "{sv}", "ReportUri",
				       g_variant_new_string (priv->report_uri));
	}
	if (priv->firmware_base_uri != NULL) {
		g_variant_builder_add (&builder, "{sv}", "FirmwareBaseUri",
				       g_variant_new_string (priv->firmware_base_uri));
	}
	if (priv->priority != 0) {
		g_variant_builder_add (&builder, "{sv}", "Priority",
				       g_variant_new_int32 (priv->priority));
	}
	if (priv->kind != FWUPD_REMOTE_KIND_UNKNOWN) {
		g_variant_builder_add (&builder, "{sv}", "Type",
				       g_variant_new_uint32 (priv->kind));
	}
	if (priv->keyring_kind != FWUPD_KEYRING_KIND_UNKNOWN) {
		g_variant_builder_add (&builder, "{sv}", "Keyring",
				       g_variant_new_uint32 (priv->keyring_kind));
	}
	if (priv->mtime != 0) {
		g_variant_builder_add (&builder, "{sv}", "ModificationTime",
				       g_variant_new_uint64 (priv->mtime));
	}
	if (priv->filename_cache != NULL) {
		g_variant_builder_add (&builder, "{sv}", "FilenameCache",
				       g_variant_new_string (priv->filename_cache));
	}
	if (priv->filename_source != NULL) {
		g_variant_builder_add (&builder, "{sv}", "FilenameSource",
				       g_variant_new_string (priv->filename_source));
	}
	g_variant_builder_add (&builder, "{sv}", "Enabled",
			       g_variant_new_boolean (priv->enabled));
	g_variant_builder_add (&builder, "{sv}", "ApprovalRequired",
			       g_variant_new_boolean (priv->approval_required));
	return g_variant_new ("a{sv}", &builder);
}
static void
add_connection (GDBusProxy *proxy, const char *con_name)
{
	GVariantBuilder connection_builder;
	GVariantBuilder setting_builder;
	char *uuid;
	const char *new_con_path;
	GVariant *ret;
	GError *error = NULL;

	/* Initialize connection GVariantBuilder */
	g_variant_builder_init (&connection_builder, G_VARIANT_TYPE ("a{sa{sv}}"));

	/* Build up the 'connection' Setting */
	g_variant_builder_init (&setting_builder, G_VARIANT_TYPE ("a{sv}"));

	uuid = nm_utils_uuid_generate ();
	g_variant_builder_add (&setting_builder, "{sv}",
	                       NM_SETTING_CONNECTION_UUID,
	                       g_variant_new_string (uuid));
	g_free (uuid);

	g_variant_builder_add (&setting_builder, "{sv}",
	                       NM_SETTING_CONNECTION_ID,
	                       g_variant_new_string (con_name));
	g_variant_builder_add (&setting_builder, "{sv}",
	                       NM_SETTING_CONNECTION_TYPE,
	                       g_variant_new_string (NM_SETTING_WIRED_SETTING_NAME));

	g_variant_builder_add (&connection_builder, "{sa{sv}}",
	                       NM_SETTING_CONNECTION_SETTING_NAME,
	                       &setting_builder);

	/* Add the (empty) 'wired' Setting */
	g_variant_builder_init (&setting_builder, G_VARIANT_TYPE ("a{sv}"));
	g_variant_builder_add (&connection_builder, "{sa{sv}}",
	                       NM_SETTING_WIRED_SETTING_NAME,
	                       &setting_builder);

	/* Build up the 'ipv4' Setting */
	g_variant_builder_init (&setting_builder, G_VARIANT_TYPE ("a{sv}"));
	g_variant_builder_add (&setting_builder, "{sv}",
	                       NM_SETTING_IP_CONFIG_METHOD,
	                       g_variant_new_string (NM_SETTING_IP4_CONFIG_METHOD_AUTO));
	g_variant_builder_add (&connection_builder, "{sa{sv}}",
	                       NM_SETTING_IP4_CONFIG_SETTING_NAME,
	                       &setting_builder);

	/* Call AddConnection with the connection dictionary as argument.
	 * (g_variant_new() will consume the floating GVariant returned from
	 * &connection_builder, and g_dbus_proxy_call_sync() will consume the
	 * floating variant returned from g_variant_new(), so no cleanup is needed.
	 */
	ret = g_dbus_proxy_call_sync (proxy,
	                              "AddConnection",
	                              g_variant_new ("(a{sa{sv}})", &connection_builder),
	                              G_DBUS_CALL_FLAGS_NONE, -1,
	                              NULL, &error);
	if (ret) {
		g_variant_get (ret, "(&o)", &new_con_path);
		g_print ("Added: %s\n", new_con_path);
		g_variant_unref (ret);
	} else {
		g_dbus_error_strip_remote_error (error);
		g_print ("Error adding connection: %s\n", error->message);
		g_clear_error (&error);
	}
}
static gboolean on_call_get_status_all(TelephonyCall *call, GDBusMethodInvocation *invocation, gpointer user_data )
{
	struct custom_data *ctx = user_data;
	TcorePlugin *plugin = 0;
	GSList *list = 0;
	CoreObject *o = 0;
	CallObject *co = 0;

	GVariant *gv = 0;
	GVariantBuilder b;

	gint call_id;
	gchar call_number[MAX_CALL_NUMBER_LEN];
	gint call_type;
	gboolean call_direction;
	gint call_status;
	gboolean call_multiparty_state;

	int len, i;

	plugin = tcore_server_find_plugin(ctx->server, TCORE_PLUGIN_DEFAULT);
	if ( !plugin ) {
		dbg("[ error ] plugin : 0");
		return FALSE;
	}

	list = tcore_plugin_get_core_objects_bytype(plugin, CORE_OBJECT_TYPE_CALL);
	if ( !list ) {
		dbg("[ error ] co_list : 0");
		return FALSE;
	}

	o = (CoreObject *)list->data;
	g_slist_free(list);

	g_variant_builder_init(&b, G_VARIANT_TYPE("aa{sv}"));

#define MAX_CALL_STATUS_NUM 7
	for ( i=0; i<MAX_CALL_STATUS_NUM; i++ ) {
		list = tcore_call_object_find_by_status( o, i );

		if ( list ) {

			GSList *tmp = 0;
			tmp = list;

			dbg("[ check ] there is a call on state (0x%x)", i);

			while ( tmp ) {

				co = (CallObject*)list->data;
				if ( !co ) {
					dbg("[ error ] call object : 0");
					tmp = tmp->next;
					continue;
				}

				call_id = tcore_call_object_get_id( co );
				len = tcore_call_object_get_number( co, call_number );
				if ( !len ) {
					dbg("[ check ] no number : (0x%d)", call_id);
				}

				call_type = tcore_call_object_get_type( co );
				call_direction = tcore_call_object_get_direction( co );

				if ( call_direction == TCORE_CALL_DIRECTION_OUTGOING ) {
					call_direction = TRUE;
				} else {
					call_direction = FALSE;
				}

				call_status = tcore_call_object_get_status( co );
				call_multiparty_state = tcore_call_object_get_multiparty_state( co );

				g_variant_builder_open(&b, G_VARIANT_TYPE("a{sv}"));
				g_variant_builder_add(&b, "{sv}", "call_id", g_variant_new_int32( call_id ));
				g_variant_builder_add(&b, "{sv}", "call_number", g_variant_new_string( call_number ));
				g_variant_builder_add(&b, "{sv}", "call_type", g_variant_new_int32( call_type ));
				g_variant_builder_add(&b, "{sv}", "call_direction", g_variant_new_boolean( call_direction ));
				g_variant_builder_add(&b, "{sv}", "call_state", g_variant_new_int32( call_status ));
				g_variant_builder_add(&b, "{sv}", "call_multiparty_state", g_variant_new_boolean( call_multiparty_state ));
				g_variant_builder_close(&b);

				tmp = g_slist_next( tmp );
			}

		} else {
			dbg("[ check ] there is no call on state (0x%x)", i);

		}

	}

	gv = g_variant_builder_end(&b);

	telephony_call_complete_get_status_all(call, invocation, gv);

	g_variant_unref(gv);

	return TRUE;
}
Пример #8
0
static void
name_lost_cb (GDBusConnection *connection,
              const char *name,
              gpointer user_data)
{
	OwnData *data = (OwnData *) user_data;
	GError *error = NULL;
	char **envv;
	int i;
	GVariantBuilder builder;
	GVariant *value;
	GString *string;
	char *s;
	gsize len;

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Lost the name %s on the session bus\n", name);

	/* Couldn't get the connection? No way to continue! */
	if (connection == NULL)
	{
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
		return;
	}

	if (data->options == NULL)
	{
		/* Already handled */
		data->exit_code = EXIT_SUCCESS;
		gtk_main_quit ();
		return;
	}

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Forwarding arguments to existing instance\n");

    g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ayayayayiay)"));
    
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->default_working_dir));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->display_name));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->startup_id));

	string = g_string_new (NULL);
	envv = g_get_environ ();
	for (i = 0; envv[i]; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');

		g_string_append (string, envv[i]);
	}
	g_strfreev (envv);

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

    g_variant_builder_add (&builder, "@i", g_variant_new_int32 (data->options->initial_workspace));

	string = g_string_new (NULL);

	for (i = 0; i < data->argc; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');
		g_string_append (string, data->argv[i]);
	}

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

	value = g_dbus_connection_call_sync (connection,
	                                     data->factory_name,
	                                     TERMINAL_FACTORY_SERVICE_PATH,
	                                     TERMINAL_FACTORY_INTERFACE_NAME,
	                                     "HandleArguments",
	                                     g_variant_builder_end (&builder),
	                                     G_VARIANT_TYPE ("()"),
	                                     G_DBUS_CALL_FLAGS_NONE,
	                                     -1,
	                                     NULL,
	                                     &error);
	if (value == NULL)
	{
		g_printerr ("Failed to forward arguments: %s\n", error->message);
		g_error_free (error);
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
	}
	else
	{
		g_variant_unref (value);
		data->exit_code = EXIT_SUCCESS;
	}

	terminal_options_free (data->options);
	data->options = NULL;

	gtk_main_quit ();
}
static gboolean
get_result_metas_cb (GcalShellSearchProvider  *search_provider,
                     GDBusMethodInvocation    *invocation,
                     gchar                   **results,
                     GcalShellSearchProvider2 *skel)
{
  GcalShellSearchProviderPrivate *priv;
  gint i;
  gchar *uuid, *desc;
  const gchar* location;

  g_autoptr(GTimeZone) tz;
  g_autoptr (GDateTime) datetime;
  g_autoptr (GDateTime) local_datetime;
  ECalComponentDateTime dtstart;
  gchar *start_date;

  ECalComponentText summary;
  GdkRGBA color;
  GVariantBuilder abuilder, builder;
  GVariant *icon_variant;
  GcalEventData *data;
  GdkPixbuf *gicon;

  priv = search_provider->priv;

  g_variant_builder_init (&abuilder, G_VARIANT_TYPE ("aa{sv}"));
  for (i = 0; i < g_strv_length (results); i++)
    {
      uuid = results[i];
      data = g_hash_table_lookup (priv->events, uuid);

      g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
      g_variant_builder_add (&builder, "{sv}", "id", g_variant_new_string (uuid));

      e_cal_component_get_summary (data->event_component, &summary);
      g_variant_builder_add (&builder, "{sv}", "name", g_variant_new_string (summary.value));

      get_color_name_from_source (data->source, &color);
      gicon = get_circle_pixbuf_from_color (&color, 128);
      icon_variant = g_icon_serialize (G_ICON (gicon));
      g_variant_builder_add (&builder, "{sv}", "icon", icon_variant);
      g_object_unref (gicon);
      g_variant_unref (icon_variant);

      e_cal_component_get_dtstart (data->event_component, &dtstart);

      if (dtstart.tzid != NULL)
        tz = g_time_zone_new (dtstart.tzid);
      else if (dtstart.value->zone != NULL)
        tz = g_time_zone_new (icaltimezone_get_tzid ((icaltimezone*) dtstart.value->zone));
      else
        tz = g_time_zone_new_local ();

      datetime = g_date_time_new (tz,
                                  dtstart.value->year, dtstart.value->month, dtstart.value->day,
                                  dtstart.value->hour, dtstart.value->minute, dtstart.value->second);
      local_datetime = g_date_time_to_local (datetime);

      /* FIXME: respect 24h time format */
      start_date = g_date_time_format (local_datetime,
                                       (dtstart.value->is_date == 1) ? "%x" : "%c");
      e_cal_component_free_datetime (&dtstart);

      e_cal_component_get_location (data->event_component, &location);
      if (location != NULL)
        desc = g_strconcat (start_date, ". ", location, NULL);
      else
        desc = g_strdup (start_date);

      g_variant_builder_add (&builder, "{sv}", "description", g_variant_new_string (desc));
      g_free (start_date);
      g_free (desc);

      g_variant_builder_add_value (&abuilder, g_variant_builder_end (&builder));
    }
  g_dbus_method_invocation_return_value (invocation, g_variant_new ("(aa{sv})", &abuilder));

  return TRUE;
}
Пример #10
0
static gboolean
ot_static_delta_builtin_generate (int argc, char **argv, GCancellable *cancellable, GError **error)
{
    gboolean ret = FALSE;
    GOptionContext *context;
    glnx_unref_object OstreeRepo *repo = NULL;

    context = g_option_context_new ("Generate static delta files");
    if (!ostree_option_context_parse (context, generate_options, &argc, &argv, OSTREE_BUILTIN_FLAG_NONE, &repo, cancellable, error))
        goto out;

    if (!ostree_ensure_repo_writable (repo, error))
        goto out;

    if (argc >= 3 && opt_to_rev == NULL)
        opt_to_rev = argv[2];

    if (argc < 3 && opt_to_rev == NULL)
    {
        g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                             "TO revision must be specified");
        goto out;
    }
    else
    {
        const char *from_source;
        g_autofree char *from_resolved = NULL;
        g_autofree char *to_resolved = NULL;
        g_autofree char *from_parent_str = NULL;
        g_autoptr(GVariantBuilder) parambuilder = NULL;

        g_assert (opt_to_rev);

        if (opt_empty)
        {
            if (opt_from_rev)
            {
                g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                     "Cannot specify both --empty and --from=REV");
                goto out;
            }
            from_source = NULL;
        }
        else if (opt_from_rev == NULL)
        {
            from_parent_str = g_strconcat (opt_to_rev, "^", NULL);
            from_source = from_parent_str;
        }
        else
        {
            from_source = opt_from_rev;
        }

        if (from_source)
        {
            if (!ostree_repo_resolve_rev (repo, from_source, FALSE, &from_resolved, error))
                goto out;
        }
        if (!ostree_repo_resolve_rev (repo, opt_to_rev, FALSE, &to_resolved, error))
            goto out;

        parambuilder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
        if (opt_min_fallback_size)
            g_variant_builder_add (parambuilder, "{sv}",
                                   "min-fallback-size", g_variant_new_uint32 (g_ascii_strtoull (opt_min_fallback_size, NULL, 10)));
        if (opt_max_chunk_size)
            g_variant_builder_add (parambuilder, "{sv}",
                                   "max-chunk-size", g_variant_new_uint32 (g_ascii_strtoull (opt_max_chunk_size, NULL, 10)));
        if (opt_disable_bsdiff)
            g_variant_builder_add (parambuilder, "{sv}",
                                   "bsdiff-enabled", g_variant_new_boolean (FALSE));

        g_variant_builder_add (parambuilder, "{sv}", "verbose", g_variant_new_boolean (TRUE));

        g_print ("Generating static delta:\n");
        g_print ("  From: %s\n", from_resolved ? from_resolved : "empty");
        g_print ("  To:   %s\n", to_resolved);
        if (!ostree_repo_static_delta_generate (repo, OSTREE_STATIC_DELTA_GENERATE_OPT_MAJOR,
                                                from_resolved, to_resolved, NULL,
                                                g_variant_builder_end (parambuilder),
                                                cancellable, error))
            goto out;

    }

    ret = TRUE;
out:
    if (context)
        g_option_context_free (context);
    return ret;
}
int
rpmostree_compose_builtin_tree (int             argc,
                                char          **argv,
                                GCancellable   *cancellable,
                                GError        **error)
{
  int exit_status = EXIT_FAILURE;
  GError *temp_error = NULL;
  GOptionContext *context = g_option_context_new ("TREEFILE - Run yum and commit the result to an OSTree repository");
  RpmOstreeTreeComposeContext selfdata = { NULL, };
  RpmOstreeTreeComposeContext *self = &selfdata;
  JsonNode *treefile_rootval = NULL;
  JsonObject *treefile = NULL;
  g_autofree char *cachekey = NULL;
  g_autofree char *new_inputhash = NULL;
  g_autoptr(GFile) previous_root = NULL;
  g_autofree char *previous_checksum = NULL;
  g_autoptr(GFile) yumroot = NULL;
  g_autoptr(GFile) yumroot_varcache = NULL;
  glnx_fd_close int rootfs_fd = -1;
  glnx_unref_object OstreeRepo *repo = NULL;
  g_autoptr(GPtrArray) bootstrap_packages = NULL;
  g_autoptr(GPtrArray) packages = NULL;
  g_autoptr(GFile) treefile_path = NULL;
  g_autoptr(GFile) treefile_dirpath = NULL;
  g_autoptr(GFile) repo_path = NULL;
  glnx_unref_object JsonParser *treefile_parser = NULL;
  gs_unref_variant_builder GVariantBuilder *metadata_builder = 
    g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
  g_autoptr(RpmOstreeContext) corectx = NULL;
  g_autoptr(GHashTable) varsubsts = NULL;
  gboolean workdir_is_tmp = FALSE;
  g_autofree char *next_version = NULL;

  self->treefile_context_dirs = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);
  
  if (!rpmostree_option_context_parse (context,
                                       option_entries,
                                       &argc, &argv,
                                       RPM_OSTREE_BUILTIN_FLAG_LOCAL_CMD,
                                       cancellable,
                                       NULL,
                                       error))
    goto out;

  if (argc < 2)
    {
      rpmostree_usage_error (context, "TREEFILE must be specified", error);
      goto out;
    }
  
  if (!opt_repo)
    {
      rpmostree_usage_error (context, "--repo must be specified", error);
      goto out;
    }

  if (getuid () != 0)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "compose tree must presently be run as uid 0 (root)");
      goto out;
    }

  /* Test whether or not bwrap is going to work - we will fail inside e.g. a Docker
   * container without --privileged or userns exposed.
   */
  if (!rpmostree_bwrap_selftest (error))
    goto out;

  repo_path = g_file_new_for_path (opt_repo);
  repo = self->repo = ostree_repo_new (repo_path);
  if (!ostree_repo_open (repo, cancellable, error))
    goto out;

  treefile_path = g_file_new_for_path (argv[1]);

  if (opt_workdir)
    {
      self->workdir = g_file_new_for_path (opt_workdir);
    }
  else
    {
      g_autofree char *tmpd = NULL;

      if (!rpmostree_mkdtemp ("/var/tmp/rpm-ostree.XXXXXX", &tmpd, NULL, error))
        goto out;

      self->workdir = g_file_new_for_path (tmpd);
      workdir_is_tmp = TRUE;

      if (opt_workdir_tmpfs)
        {
          if (mount ("tmpfs", tmpd, "tmpfs", 0, (const void*)"mode=755") != 0)
            {
              _rpmostree_set_prefix_error_from_errno (error, errno,
                                                      "mount(tmpfs): ");
              goto out;
            }
        }
    }

  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (self->workdir),
                       FALSE, &self->workdir_dfd, error))
    goto out;

  if (opt_cachedir)
    {
      if (!glnx_opendirat (AT_FDCWD, opt_cachedir, TRUE, &self->cachedir_dfd, error))
        {
          g_prefix_error (error, "Opening cachedir '%s': ", opt_cachedir);
          goto out;
        }
    }
  else
    {
      self->cachedir_dfd = fcntl (self->workdir_dfd, F_DUPFD_CLOEXEC, 3);
      if (self->cachedir_dfd < 0)
        {
          glnx_set_error_from_errno (error);
          goto out;
        }
    }

  if (opt_metadata_strings)
    {
      if (!parse_keyvalue_strings (opt_metadata_strings,
                                   metadata_builder, error))
        goto out;
    }

  if (fchdir (self->workdir_dfd) != 0)
    {
      glnx_set_error_from_errno (error);
      goto out;
    }

  corectx = rpmostree_context_new_compose (self->cachedir_dfd, cancellable, error);
  if (!corectx)
    goto out;

  varsubsts = rpmostree_context_get_varsubsts (corectx);

  treefile_parser = json_parser_new ();
  if (!json_parser_load_from_file (treefile_parser,
                                   gs_file_get_path_cached (treefile_path),
                                   error))
    goto out;

  treefile_rootval = json_parser_get_root (treefile_parser);
  if (!JSON_NODE_HOLDS_OBJECT (treefile_rootval))
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Treefile root is not an object");
      goto out;
    }
  treefile = json_node_get_object (treefile_rootval);

  if (!process_includes (self, treefile_path, 0, treefile,
                         cancellable, error))
    goto out;

  if (opt_print_only)
    {
      glnx_unref_object JsonGenerator *generator = json_generator_new ();
      g_autoptr(GOutputStream) stdout = g_unix_output_stream_new (1, FALSE);

      json_generator_set_pretty (generator, TRUE);
      json_generator_set_root (generator, treefile_rootval);
      (void) json_generator_to_stream (generator, stdout, NULL, NULL);

      exit_status = EXIT_SUCCESS;
      goto out;
    }

  { const char *input_ref = _rpmostree_jsonutil_object_require_string_member (treefile, "ref", error);
    if (!input_ref)
      goto out;
    self->ref = _rpmostree_varsubst_string (input_ref, varsubsts, error);
    if (!self->ref)
      goto out;
  }

  if (!ostree_repo_read_commit (repo, self->ref, &previous_root, &previous_checksum,
                                cancellable, &temp_error))
    {
      if (g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
        { 
          g_clear_error (&temp_error);
          g_print ("No previous commit for %s\n", self->ref);
        }
      else
        {
          g_propagate_error (error, temp_error);
          goto out;
        }
    }
  else
    g_print ("Previous commit: %s\n", previous_checksum);

  self->previous_checksum = previous_checksum;

  yumroot = g_file_get_child (self->workdir, "rootfs.tmp");
  if (!glnx_shutil_rm_rf_at (self->workdir_dfd, "rootfs.tmp", cancellable, error))
    goto out;

  if (json_object_has_member (treefile, "automatic_version_prefix") &&
      !compose_strv_contains_prefix (opt_metadata_strings, "version="))
    {
      g_autoptr(GVariant) variant = NULL;
      g_autofree char *last_version = NULL;
      const char *ver_prefix;

      ver_prefix = _rpmostree_jsonutil_object_require_string_member (treefile,
                                                                     "automatic_version_prefix",
                                                                     error);
      if (!ver_prefix)
          goto out;

      if (previous_checksum)
        {
          if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT,
                                         previous_checksum, &variant, error))
            goto out;

          last_version = checksum_version (variant);
        }

      next_version = _rpmostree_util_next_version (ver_prefix, last_version);
      g_variant_builder_add (metadata_builder, "{sv}", "version",
                             g_variant_new_string (next_version));
    }

  bootstrap_packages = g_ptr_array_new ();
  packages = g_ptr_array_new ();

  if (json_object_has_member (treefile, "bootstrap_packages"))
    {
      if (!_rpmostree_jsonutil_append_string_array_to (treefile, "bootstrap_packages", packages, error))
        goto out;
    }
  if (!_rpmostree_jsonutil_append_string_array_to (treefile, "packages", packages, error))
    goto out;

  { g_autofree char *thisarch_packages = g_strconcat ("packages-", dnf_context_get_base_arch (rpmostree_context_get_hif (corectx)), NULL);

    if (json_object_has_member (treefile, thisarch_packages))
      {
        if (!_rpmostree_jsonutil_append_string_array_to (treefile, thisarch_packages, packages, error))
          goto out;
      }
  }
  g_ptr_array_add (packages, NULL);

  { glnx_unref_object JsonGenerator *generator = json_generator_new ();
    char *treefile_buf = NULL;
    gsize len;

    json_generator_set_root (generator, treefile_rootval);
    json_generator_set_pretty (generator, TRUE);
    treefile_buf = json_generator_to_data (generator, &len);

    self->serialized_treefile = g_bytes_new_take (treefile_buf, len);
  }

  treefile_dirpath = g_file_get_parent (treefile_path);
  if (TRUE)
    {
      gboolean generate_from_previous = TRUE;

      if (!_rpmostree_jsonutil_object_get_optional_boolean_member (treefile,
                                                                   "preserve-passwd",
                                                                   &generate_from_previous,
                                                                   error))
        goto out;

      if (generate_from_previous)
        {
          if (!rpmostree_generate_passwd_from_previous (repo, yumroot,
                                                        treefile_dirpath,
                                                        previous_root, treefile,
                                                        cancellable, error))
            goto out;
        }
    }

  { gboolean unmodified = FALSE;

    if (!install_packages_in_root (self, corectx, treefile, yumroot,
                                   (char**)packages->pdata,
                                   opt_force_nocache ? NULL : &unmodified,
                                   &new_inputhash,
                                   cancellable, error))
      goto out;

    if (unmodified)
      {
        g_print ("No apparent changes since previous commit; use --force-nocache to override\n");
        exit_status = EXIT_SUCCESS;
        goto out;
      }
    else if (opt_dry_run)
      {
        g_print ("--dry-run complete, exiting\n");
        exit_status = EXIT_SUCCESS;
        goto out;
      }
  }

  if (g_strcmp0 (g_getenv ("RPM_OSTREE_BREAK"), "post-yum") == 0)
    goto out;

  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (yumroot), TRUE,
                       &rootfs_fd, error))
    goto out;

  if (!rpmostree_treefile_postprocessing (rootfs_fd, self->treefile_context_dirs->pdata[0],
                                          self->serialized_treefile, treefile,
                                          next_version, cancellable, error))
    goto out;

  if (!rpmostree_prepare_rootfs_for_commit (yumroot, treefile, cancellable, error))
    goto out;

  /* Reopen since the prepare renamed */
  (void) close (rootfs_fd);
  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (yumroot), TRUE,
                       &rootfs_fd, error))
    goto out;

  if (!rpmostree_copy_additional_files (yumroot, self->treefile_context_dirs->pdata[0], treefile, cancellable, error))
    goto out;

  if (!rpmostree_check_passwd (repo, yumroot, treefile_dirpath, treefile,
                               previous_checksum,
                               cancellable, error))
    goto out;

  if (!rpmostree_check_groups (repo, yumroot, treefile_dirpath, treefile,
                               previous_checksum,
                               cancellable, error))
    goto out;

  {
    const char *gpgkey;
    gboolean selinux = TRUE;
    g_autoptr(GVariant) metadata = NULL;

    g_variant_builder_add (metadata_builder, "{sv}",
                           "rpmostree.inputhash",
                           g_variant_new_string (new_inputhash));

    metadata = g_variant_ref_sink (g_variant_builder_end (metadata_builder));

    if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "gpg_key", &gpgkey, error))
      goto out;

    if (!_rpmostree_jsonutil_object_get_optional_boolean_member (treefile,
                                                                 "selinux",
                                                                 &selinux,
                                                                 error))
      goto out;

    { g_autofree char *new_revision = NULL;

      if (!rpmostree_commit (rootfs_fd, repo, self->ref, metadata, gpgkey, selinux, NULL,
                             &new_revision,
                             cancellable, error))
        goto out;

      g_print ("%s => %s\n", self->ref, new_revision);

    }
  }

  if (opt_touch_if_changed)
    {
      gs_fd_close int fd = open (opt_touch_if_changed, O_CREAT|O_WRONLY|O_NOCTTY, 0644);
      if (fd == -1)
        {
          gs_set_error_from_errno (error, errno);
          g_prefix_error (error, "Updating '%s': ", opt_touch_if_changed);
          goto out;
        }
      if (futimens (fd, NULL) == -1)
        {
          gs_set_error_from_errno (error, errno);
          goto out;
        }
    }

  exit_status = EXIT_SUCCESS;

 out:
  /* Explicitly close this one now as it may have references to files
   * we delete below.
   */
  g_clear_object (&corectx);
  
  /* Move back out of the workding directory to ensure unmount works */
  (void )chdir ("/");

  if (self->workdir_dfd != -1)
    (void) close (self->workdir_dfd);

  if (workdir_is_tmp)
    {
      if (opt_workdir_tmpfs)
        if (umount (gs_file_get_path_cached (self->workdir)) != 0)
          {
            fprintf (stderr, "warning: umount failed: %m\n");
          }
      (void) gs_shutil_rm_rf (self->workdir, NULL, NULL);
    }
  if (self)
    {
      g_clear_object (&self->workdir);
      g_clear_pointer (&self->serialized_treefile, g_bytes_unref);
      g_ptr_array_unref (self->treefile_context_dirs);
    }

  return exit_status;
}
Пример #12
0
static void CACentralStartDiscoveryImpl(gpointer proxy, gpointer user_data)
{
    assert(proxy != NULL);
    assert(user_data != NULL);

    GDBusProxy * const adapter = G_DBUS_PROXY(proxy);
    CAResult_t * const result  = user_data;

    *result = CA_STATUS_FAILED;

    bool const is_discovering =
        CACentralGetBooleanProperty(adapter, "Discovering");

    if (is_discovering)
    {
        // Nothing to do.  Avoid invoking a method over D-Bus.
        *result = CA_STATUS_OK;
        return;
    }


    // Make sure the adapter is powered on before starting discovery.
    if (!CASetBlueZObjectProperty(adapter,
                                  BLUEZ_ADAPTER_INTERFACE,
                                  "Powered",
                                  g_variant_new_boolean(TRUE)))
    {
        OIC_LOG(ERROR,
                TAG,
                "Unable to power on LE central adapter.");

        return;
    }

    /*
      Only scan for LE peripherals that advertise the OIC Transport
      Profile GATT service UUID by setting a discovery filter on the BlueZ
      org.bluez.Adapter1 object with two parameters:

          (1) "UUIDs": set to an array containing that OIC Transport
                       Profile GATT service UUID
          (2) "Transport": set to "le"

      See the documentation for the SetDiscoveryFilter() method in the
      BlueZ `adapter-api.txt' document for more details.
    */
    GVariantBuilder builder;
    g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));

    static char const * const UUIDs[] =
        {
            CA_GATT_SERVICE_UUID
        };

    g_variant_builder_add(&builder,
                          "{sv}",
                          "UUIDs",
                          g_variant_new_strv(
                              UUIDs,
                              sizeof(UUIDs) / sizeof(UUIDs[0])));

    g_variant_builder_add(&builder,
                          "{sv}",
                          "Transport",
                          g_variant_new_string("le"));

    GVariant * const filter = g_variant_builder_end(&builder);

    /*
      SetDiscoveryFilter() expects a dictionary but it must be packed
      into a tuple for the actual call through the proxy.
    */
    GVariant * const filter_parameters =
        g_variant_new("(@a{sv})", filter);

    GError * error = NULL;

    /*
      This is a synchronous call, but the actually discovery is
      performed asynchronously.  org.bluez.Device1 objects will
      reported through the
      org.freedesktop.DBus.ObjectManager.InterfacesAdded signal as
      peripherals that match our discovery filter criteria are found.
     */
    GVariant * ret =
        g_dbus_proxy_call_sync(adapter,
                               "SetDiscoveryFilter",
                               filter_parameters,
                               G_DBUS_CALL_FLAGS_NONE,
                               -1,    // timeout (default == -1),
                               NULL,  // cancellable
                               &error);

    if (ret == NULL)
    {
        OIC_LOG_V(ERROR,
                  TAG,
                  "SetDiscoveryFilter() call failed: %s",
                  error->message);

        g_error_free(error);

        return;
    }

    g_variant_unref(ret);

    // Start device discovery.
    ret = g_dbus_proxy_call_sync(adapter,
                                 "StartDiscovery",
                                 NULL,  // parameters
                                 G_DBUS_CALL_FLAGS_NONE,
                                 -1,    // timeout (default == -1),
                                 NULL,  // cancellable
                                 &error);

    if (ret == NULL)
    {
        OIC_LOG_V(ERROR,
                  TAG,
                  "StartDiscovery() call failed: %s",
                  error->message);

        g_error_free(error);

        return;
    }

    g_variant_unref(ret);

    *result = CA_STATUS_OK;
}
Пример #13
0
static GHashTable *
parse_resource_file (const gchar *filename,
                     gboolean     collect_data,
                     GHashTable  *files)
{
  GMarkupParser parser = { start_element, end_element, text };
  ParseState state = { 0, };
  GMarkupParseContext *context;
  GError *error = NULL;
  gchar *contents;
  GHashTable *table = NULL;
  gsize size;

  if (!g_file_get_contents (filename, &contents, &size, &error))
    {
      g_printerr ("%s\n", error->message);
      g_clear_error (&error);
      return NULL;
    }

  state.collect_data = collect_data;
  state.table = g_hash_table_ref (files);

  context = g_markup_parse_context_new (&parser,
					G_MARKUP_TREAT_CDATA_AS_TEXT |
					G_MARKUP_PREFIX_ERROR_POSITION,
					&state, NULL);

  if (!g_markup_parse_context_parse (context, contents, size, &error) ||
      !g_markup_parse_context_end_parse (context, &error))
    {
      g_printerr ("%s: %s.\n", filename, error->message);
      g_clear_error (&error);
    }
  else
    {
      GHashTableIter iter;
      const char *key;
      char *mykey;
      gsize key_len;
      FileData *data;
      GVariant *v_data;
      GVariantBuilder builder;
      GvdbItem *item;

      table = gvdb_hash_table_new (NULL, NULL);

      g_hash_table_iter_init (&iter, state.table);
      while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
	{
	  key_len = strlen (key);
	  mykey = g_strdup (key);

	  item = gvdb_hash_table_insert (table, key);
	  gvdb_item_set_parent (item,
				get_parent (table, mykey, key_len));

	  g_free (mykey);

	  g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));

	  g_variant_builder_add (&builder, "u", data->size); /* Size */
	  g_variant_builder_add (&builder, "u", data->flags); /* Flags */

	  v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
					    data->content, data->content_size, TRUE,
					    g_free, data->content);
	  g_variant_builder_add_value (&builder, v_data);
	  data->content = NULL; /* Take ownership */

	  gvdb_item_set_value (item,
			       g_variant_builder_end (&builder));
	}
    }

  g_hash_table_unref (state.table);
  g_markup_parse_context_free (context);
  g_free (contents);

  return table;
}
Пример #14
0
static gboolean
writeback_dispatcher_writeback_file (TrackerMinerFS *fs,
                                     GFile          *file,
                                     GStrv           rdf_types,
                                     GPtrArray      *results,
                                     GCancellable   *cancellable,
                                     gpointer        user_data)
{
	TrackerWritebackDispatcher *self = user_data;
	TrackerWritebackDispatcherPrivate *priv;
	gchar *uri;
	guint i;
	GVariantBuilder builder;
	WritebackFileData *data = g_new (WritebackFileData, 1);

	priv = TRACKER_WRITEBACK_DISPATCHER_GET_PRIVATE (self);

	uri = g_file_get_uri (file);
	g_debug ("Performing write-back for '%s'", uri);

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("(sasaas)"));

	g_variant_builder_add (&builder, "s", uri);

	g_variant_builder_open (&builder, G_VARIANT_TYPE ("as"));
	for (i = 0; rdf_types[i] != NULL; i++) {
		g_variant_builder_add (&builder, "s", rdf_types[i]);
	}
	g_variant_builder_close (&builder);

	g_variant_builder_open (&builder, G_VARIANT_TYPE ("aas"));

	for (i = 0; i< results->len; i++) {
		GStrv row = g_ptr_array_index (results, i);
		guint y;

		g_variant_builder_open (&builder, G_VARIANT_TYPE ("as"));
		for (y = 0; row[y] != NULL; y++) {
			g_variant_builder_add (&builder, "s", row[y]);
		}

		g_variant_builder_close (&builder);
	}

	g_variant_builder_close (&builder);

	data->retries = 0;
	data->retry_timeout = 0;
	data->self = self;
	g_object_weak_ref (G_OBJECT (data->self), self_weak_notify, data);
	data->fs = g_object_ref (fs);
	data->file = g_object_ref (file);
	data->results = g_ptr_array_ref (results);
	data->rdf_types = g_strdupv (rdf_types);
	data->cancellable = g_object_ref (cancellable);
	data->cancel_id = g_cancellable_connect (data->cancellable,
	                                         G_CALLBACK (writeback_cancel_remote_operation),
	                                         data, NULL);

	g_dbus_connection_call (priv->d_connection,
	                        TRACKER_WRITEBACK_SERVICE,
	                        TRACKER_WRITEBACK_PATH,
	                        TRACKER_WRITEBACK_INTERFACE,
	                        "PerformWriteback",
	                        g_variant_builder_end (&builder),
	                        NULL,
	                        G_DBUS_CALL_FLAGS_NONE,
	                        -1,
	                        cancellable,
	                        (GAsyncReadyCallback) writeback_file_finished,
	                        data);

	g_free (uri);

	return TRUE;
}
static gboolean
handle_file (const gchar *filename)
{
  GKeyFile *keyfile;
  MateConfClient *client;
  MateConfValue *value;
  gint i, j;
  gchar *mateconf_key;
  gchar **groups;
  gchar **keys;
  GVariantBuilder *builder;
  GVariant *v;
  const gchar *s;
  gchar *str;
  gint ii;
  GSList *list, *l;
  GSettings *settings;
  GError *error;

  keyfile = g_key_file_new ();

  error = NULL;
  if (!g_key_file_load_from_file (keyfile, filename, 0, &error))
    {
      g_printerr ("%s\n", error->message);
      g_error_free (error);

      g_key_file_free (keyfile);

      return FALSE;
    }

  client = mateconf_client_get_default ();

  groups = g_key_file_get_groups (keyfile, NULL);
  for (i = 0; groups[i]; i++)
    {
      gchar **schema_path;

      schema_path = g_strsplit (groups[i], ":", 2);

      if (verbose)
        {
          g_print ("collecting settings for schema '%s'\n", schema_path[0]);
          if (schema_path[1])
            g_print ("for storage at '%s'\n", schema_path[1]);
        }

      if (schema_path[1] != NULL)
        settings = g_settings_new_with_path (schema_path[0], schema_path[1]);
      else
        settings = g_settings_new (schema_path[0]);

      g_settings_delay (settings);

      error = NULL;
      if ((keys = g_key_file_get_keys (keyfile, groups[i], NULL, &error)) == NULL)
        {
          g_printerr ("%s", error->message);
          g_error_free (error);

          continue;
        }

      for (j = 0; keys[j]; j++)
        {
          if (strchr (keys[j], '/') != 0)
            {
              g_printerr ("Key '%s' contains a '/'\n", keys[j]);

              continue;
            }

          error = NULL;
          if ((mateconf_key = g_key_file_get_string (keyfile, groups[i], keys[j], &error)) ==  NULL)
            {
              g_printerr ("%s", error->message);
              g_error_free (error);

              continue;
            }

          error = NULL;
          if ((value = mateconf_client_get_without_default (client, mateconf_key, &error)) == NULL)
            {
              if (error)
                {
                  g_printerr ("Failed to get MateConf key '%s': %s\n",
                              mateconf_key, error->message);
                  g_error_free (error);
                }
              else
                {
                  if (verbose)
                    g_print ("Skipping MateConf key '%s', no user value\n",
                             mateconf_key);
                }

              g_free (mateconf_key);

              continue;
            }

          switch (value->type)
            {
            case MATECONF_VALUE_STRING:
              if (dry_run)
                g_print ("set key '%s' to string '%s'\n", keys[j],
                         mateconf_value_get_string (value));
              else
                g_settings_set (settings, keys[j], "s",
                                mateconf_value_get_string (value));
              break;

            case MATECONF_VALUE_INT:
              if (dry_run)
                g_print ("set key '%s' to integer '%d'\n",
                         keys[j], mateconf_value_get_int (value));
              else
                g_settings_set (settings, keys[j], "i",
                                mateconf_value_get_int (value));
              break;

            case MATECONF_VALUE_BOOL:
              if (dry_run)
                g_print ("set key '%s' to boolean '%d'\n",
                         keys[j], mateconf_value_get_bool (value));
              else
                g_settings_set (settings, keys[j], "b",
                                mateconf_value_get_bool (value));
              break;

            case MATECONF_VALUE_FLOAT:
              if (dry_run)
                g_print ("set key '%s' to double '%g'\n",
                         keys[j], mateconf_value_get_float (value));
              else
                g_settings_set (settings, keys[j], "d",
                                mateconf_value_get_float (value));
              break;

            case MATECONF_VALUE_LIST:
              switch (mateconf_value_get_list_type (value))
                {
                case MATECONF_VALUE_STRING:
                  builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
                  list = mateconf_value_get_list (value);
                  if (list != NULL)
                    {
                      for (l = list; l; l = l->next)
                        {
                          MateConfValue *lv = l->data;
                          s = mateconf_value_get_string (lv);
                          g_variant_builder_add (builder, "s", s);
                        }
                      v = g_variant_new ("as", builder);
                    }
                  else
                    v = g_variant_new_array (G_VARIANT_TYPE_STRING, NULL, 0);
                  g_variant_ref_sink (v);

                  if (dry_run)
                    {
                      str = g_variant_print (v, FALSE);
                      g_print ("set key '%s' to a list of strings: %s\n",
                               keys[j], str);
                      g_free (str);
                    }
                  else
                    g_settings_set_value (settings, keys[j], v);

                  g_variant_unref (v);
                  g_variant_builder_unref (builder);
                  break;

                case MATECONF_VALUE_INT:
                  builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
                  list = mateconf_value_get_list (value);
                  if (list != NULL)
                    {
                      for (l = list; l; l = l->next)
                        {
                          MateConfValue *lv = l->data;
                          ii = mateconf_value_get_int (lv);
                          g_variant_builder_add (builder, "i", ii);
                        }
                      v = g_variant_new ("ai", builder);
                    }
                  else
                    v = g_variant_new_array (G_VARIANT_TYPE_INT32, NULL, 0);
                  g_variant_ref_sink (v);

                  if (dry_run)
                    {
                      str = g_variant_print (v, FALSE);
                      g_print ("set key '%s' to a list of integers: %s\n",
                               keys[j], str);
                      g_free (str);
                    }
                  else
                    g_settings_set_value (settings, keys[j], v);

                  g_variant_unref (v);
                  g_variant_builder_unref (builder);
                  break;

                default:
                  g_printerr ("Keys of type 'list of %s' not handled yet\n",
                              mateconf_value_type_to_string (mateconf_value_get_list_type (value)));
                  break;
                }
              break;

            default:
              g_printerr ("Keys of type %s not handled yet\n",
                          mateconf_value_type_to_string (value->type));
              break;
            }

          mateconf_value_free (value);
          g_free (mateconf_key);
        }

      g_strfreev (keys);

      if (!dry_run)
        g_settings_apply (settings);

      g_object_unref (settings);
      g_strfreev (schema_path);
    }

  g_strfreev (groups);

  g_object_unref (client);

  return TRUE;
}
OCEntityHandlerResult icd_ioty_ocprocess_req_handler(OCEntityHandlerFlag flag,
		OCEntityHandlerRequest *request, void *user_data)
{
	FN_CALL;
	int ret;
	int64_t signal_number;
	char *query_str, *query_key, *query_value;
	char *token, *save_ptr1, *save_ptr2;
	char *bus_name = NULL;
	struct icd_req_context *req_ctx;

	RETV_IF(NULL == request, OC_EH_ERROR);

	req_ctx = calloc(1, sizeof(struct icd_req_context));
	if (NULL == req_ctx) {
		ERR("calloc() Fail(%d)", errno);
		return OC_EH_ERROR;
	}

	/* handle */
	req_ctx->request_h = request->requestHandle;
	req_ctx->resource_h = request->resource;

	ret = icd_dbus_client_list_get_resource_info(req_ctx->resource_h, &signal_number,
			&bus_name);
	if (IOTCON_ERROR_NONE != ret) {
		ERR("icd_dbus_client_list_get_resource_info() Fail(%d)", ret);
		free(req_ctx);
		return OC_EH_ERROR;
	}

	/* signal number & bus_name */
	req_ctx->signal_number = signal_number;
	req_ctx->bus_name = bus_name;

	memcpy(&req_ctx->dev_addr, &request->devAddr, sizeof(OCDevAddr));

	/* request type */
	if (OC_REQUEST_FLAG & flag) {
		switch (request->method) {
		case OC_REST_GET:
			req_ctx->request_type = IOTCON_REQUEST_GET;
			req_ctx->payload = NULL;
			break;
		case OC_REST_PUT:
			req_ctx->request_type = IOTCON_REQUEST_PUT;
			req_ctx->payload = icd_payload_to_gvariant(request->payload);
			break;
		case OC_REST_POST:
			req_ctx->request_type = IOTCON_REQUEST_POST;
			req_ctx->payload = icd_payload_to_gvariant(request->payload);
			break;
		case OC_REST_DELETE:
			req_ctx->request_type = IOTCON_REQUEST_DELETE;
			req_ctx->payload = NULL;
			break;
		default:
			free(req_ctx->bus_name);
			free(req_ctx);
			return OC_EH_ERROR;
		}
	}

	if (OC_OBSERVE_FLAG & flag) {
		/* observation info*/
		req_ctx->observe_id = request->obsInfo.obsId;
		req_ctx->observe_type = _ioty_oic_action_to_ioty_action(request->obsInfo.action);
	} else {
		req_ctx->observe_type = IOTCON_OBSERVE_NO_TYPE;
	}

	/* header options */
	req_ctx->options = _ocprocess_parse_header_options(
			request->rcvdVendorSpecificHeaderOptions,
			request->numRcvdVendorSpecificHeaderOptions);

	/* query */
	req_ctx->query = g_variant_builder_new(G_VARIANT_TYPE("a(ss)"));
	query_str = request->query;
	while ((token = strtok_r(query_str, "&;", &save_ptr1))) {
		while ((query_key = strtok_r(token, "=", &save_ptr2))) {
			token = NULL;
			query_value = strtok_r(token, "=", &save_ptr2);
			if (NULL == query_value)
				break;

			g_variant_builder_add(req_ctx->query, "(ss)", query_key, query_value);
		}
		query_str = NULL;
	}

	ret = _ocprocess_worker_start(_worker_req_handler, req_ctx, _icd_req_context_free);
	if (IOTCON_ERROR_NONE != ret) {
		ERR("_ocprocess_worker_start() Fail(%d)", ret);
		_icd_req_context_free(req_ctx);
		return OC_EH_ERROR;
	}

	/* DO NOT FREE req_ctx. It MUST be freed in the _worker_req_handler func */

	return OC_EH_OK;
}
Пример #17
0
GVariant *
g_settings_set_mapping (const GValue       *value,
                        const GVariantType *expected_type,
                        gpointer            user_data)
{
  gchar *type_string;

  if (G_VALUE_HOLDS_BOOLEAN (value))
    {
      if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_BOOLEAN))
        return g_variant_new_boolean (g_value_get_boolean (value));
    }

  else if (G_VALUE_HOLDS_CHAR (value)  ||
           G_VALUE_HOLDS_UCHAR (value))
    {
      if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_BYTE))
        {
          if (G_VALUE_HOLDS_CHAR (value))
            return g_variant_new_byte (g_value_get_char (value));
          else
            return g_variant_new_byte (g_value_get_uchar (value));
        }
    }

  else if (G_VALUE_HOLDS_INT (value)   ||
           G_VALUE_HOLDS_INT64 (value))
    return g_settings_set_mapping_int (value, expected_type);

  else if (G_VALUE_HOLDS_DOUBLE (value))
    return g_settings_set_mapping_float (value, expected_type);

  else if (G_VALUE_HOLDS_UINT (value)  ||
           G_VALUE_HOLDS_UINT64 (value))
    return g_settings_set_mapping_unsigned_int (value, expected_type);

  else if (G_VALUE_HOLDS_STRING (value))
    {
      if (g_value_get_string (value) == NULL)
        return NULL;
      else if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_STRING))
        return g_variant_new_string (g_value_get_string (value));
      else if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_BYTESTRING))
        return g_variant_new_bytestring (g_value_get_string (value));
      else if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_OBJECT_PATH))
        return g_variant_new_object_path (g_value_get_string (value));
      else if (g_variant_type_equal (expected_type, G_VARIANT_TYPE_SIGNATURE))
        return g_variant_new_signature (g_value_get_string (value));
    }

  else if (G_VALUE_HOLDS (value, G_TYPE_STRV))
    {
      if (g_value_get_boxed (value) == NULL)
        return NULL;
      return g_variant_new_strv ((const gchar **) g_value_get_boxed (value),
                                 -1);
    }

  else if (G_VALUE_HOLDS_ENUM (value))
    {
      GEnumValue *enumval;
      GEnumClass *eclass;

      /* GParamSpecEnum holds a ref on the class so we just peek... */
      eclass = g_type_class_peek (G_VALUE_TYPE (value));
      enumval = g_enum_get_value (eclass, g_value_get_enum (value));

      if (enumval)
        return g_variant_new_string (enumval->value_nick);
      else
        return NULL;
    }

  else if (G_VALUE_HOLDS_FLAGS (value))
    {
      GVariantBuilder builder;
      GFlagsValue *flagsval;
      GFlagsClass *fclass;
      guint flags;

      fclass = g_type_class_peek (G_VALUE_TYPE (value));
      flags = g_value_get_flags (value);

      g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
      while (flags)
        {
          flagsval = g_flags_get_first_value (fclass, flags);

          if (flagsval == NULL)
            {
              g_variant_builder_clear (&builder);
              return NULL;
            }

          g_variant_builder_add (&builder, "s", flagsval->value_nick);
          flags &= ~flagsval->value;
        }

      return g_variant_builder_end (&builder);
    }

  type_string = g_variant_type_dup_string (expected_type);
  g_critical ("No GSettings bind handler for type \"%s\".", type_string);
  g_free (type_string);

  return NULL;
}
Пример #18
0
int
main (int argc,
      char *argv[])
{
  MetaTree *tree;
  GError *error = NULL;
  GOptionContext *context;
  MetaLookupCache *lookup;
  struct stat statbuf;
  const char *path, *key;
  const char *metatreefile;
  char *tree_path;
  GVfsMetadata *proxy;
  
  g_type_init();
  
  context = g_option_context_new ("<path> <key> <value> - set metadata");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("option parsing failed: %s\n", error->message);
      return 1;
    }

  if (argc < 2)
    {
      g_printerr ("no path specified\n");
      return 1;
    }
  path = argv[1];

  if (argc < 3)
    {
      g_printerr ("no key specified\n");
      return 1;
    }
  key = argv[2];

  if (!list && !unset && argc != 4)
    {
      g_print ("No value specified\n");
      return 1;
    }

  if (treename)
    {
      tree = meta_tree_lookup_by_name (treename, TRUE);
      if (tree)
	tree_path = g_strdup (path);

      if (tree == NULL)
	{
	  g_printerr ("can't open metadata tree %s\n", path);
	  return 1;
	}
    }
  else
    {
      lookup = meta_lookup_cache_new ();
      if (g_lstat (path, &statbuf) != 0)
	{
	  g_printerr ("can't find file %s\n", path);
	  return 1;
	}
      tree = meta_lookup_cache_lookup_path (lookup,
					    path,
					    statbuf.st_dev,
					    TRUE,
					    &tree_path);
      meta_lookup_cache_free (lookup);

      if (tree == NULL)
	{
	  g_printerr ("can't open metadata tree for file %s\n", path);
	  return 1;
	}
    }

  proxy = NULL;
  if (use_dbus)
    {
      proxy = gvfs_metadata_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                                    G_DBUS_PROXY_FLAGS_NONE,
                                                    G_VFS_DBUS_METADATA_NAME,
                                                    G_VFS_DBUS_METADATA_PATH,
                                                    NULL,
                                                    &error);
      
      if (proxy == NULL)
	{
	  g_printerr ("Unable to connect to dbus: %s (%s, %d)\n",
                      error->message, g_quark_to_string (error->domain), error->code);
	  g_error_free (error);
	  return 1;
	}
      
      g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (proxy), 1000*30);
    }

  if (unset)
    {
      if (use_dbus)
	{
          metatreefile = meta_tree_get_filename (tree);

          if (! gvfs_metadata_call_unset_sync (proxy,
                                               metatreefile,
                                               tree_path,
                                               key,
                                               NULL,
                                               &error))
	    {
	      g_printerr ("Unset error: %s (%s, %d)\n",
                           error->message, g_quark_to_string (error->domain), error->code);
	      return 1;
	    }
	}
      else
	{
	  if (!meta_tree_unset (tree, tree_path, key))
	    {
	      g_printerr ("Unable to unset key\n");
	      return 1;
	    }
	}
    }
  else if (list)
    {
      if (use_dbus)
	{
	  char **strv;
	  GVariantBuilder *builder;

          metatreefile = meta_tree_get_filename (tree);
          strv = &argv[3];

          builder = g_variant_builder_new (G_VARIANT_TYPE_VARDICT);
          g_variant_builder_add (builder, "{sv}", key, g_variant_new_strv ((const gchar * const  *) strv, -1));

          if (! gvfs_metadata_call_set_sync (proxy,
                                             metatreefile,
                                             tree_path,
                                             g_variant_builder_end (builder),
                                             NULL,
                                             &error))
            {
              g_printerr ("SetStringv error: %s (%s, %d)\n",
                           error->message, g_quark_to_string (error->domain), error->code);
              return 1;
            }
          
          g_variant_builder_unref (builder);
	}
      else
	{
	  if (!meta_tree_set_stringv (tree, tree_path, key, &argv[3]))
	    {
	      g_printerr ("Unable to set key\n");
	      return 1;
	    }
	}
    }
  else
    {
      if (use_dbus)
	{
          GVariantBuilder *builder;

          metatreefile = meta_tree_get_filename (tree);
          
          builder = g_variant_builder_new (G_VARIANT_TYPE_VARDICT);
          g_variant_builder_add (builder, "{sv}", key, g_variant_new_string (argv[3]));

          if (! gvfs_metadata_call_set_sync (proxy,
                                             metatreefile,
                                             tree_path,
                                             g_variant_builder_end (builder),
                                             NULL,
                                             &error))
            {
              g_printerr ("SetString error: %s (%s, %d)\n",
                           error->message, g_quark_to_string (error->domain), error->code);
              return 1;
            }
          
          g_variant_builder_unref (builder);
	}
      else
	{
	  if (!meta_tree_set_string (tree, tree_path, key, argv[3]))
	    {
	      g_printerr ("Unable to set key\n");
	      return 1;
	    }
	}
    }

  if (proxy)
    g_object_unref (proxy);
    
  return 0;
}
int
main (int argc, char *argv[])
{
	GDBusProxy *proxy;
	GVariantBuilder builder, ip4builder, ip6builder;
	GVariant *ip4config, *ip6config;
	char *tmp;
	GVariant *val;
	int i;
	GError *err = NULL;
	GPtrArray *dns4_list, *dns6_list;
	GPtrArray *nbns_list;
	GPtrArray *dns_domains;
	struct in_addr temp_addr;
	int tapdev = -1;
	char **iter;
	int shift = 0;
	gboolean is_restart;
	gboolean has_ip4_prefix = FALSE;
	gboolean has_ip4_address = FALSE;
	gboolean has_ip6_address = FALSE;
	gchar *bus_name = NM_DBUS_SERVICE_OPENVPN;

#if !GLIB_CHECK_VERSION (2, 35, 0)
	g_type_init ();
#endif

	for (i = 1; i < argc; i++) {
		if (!strcmp (argv[i], "--")) {
			i++;
			break;
		}
		if (nm_streq (argv[i], "--debug")) {
			if (i + 2 >= argc) {
				g_printerr ("Missing debug arguments (requires <LEVEL> <PREFIX_TOKEN>)\n");
				exit (1);
			}
			gl.log_level = _nm_utils_ascii_str_to_int64 (argv[++i], 10, 0, LOG_DEBUG, 0);
			gl.log_prefix_token = argv[++i];
		} else if (!strcmp (argv[i], "--tun"))
			tapdev = 0;
		else if (!strcmp (argv[i], "--tap"))
			tapdev = 1;
		else if (!strcmp (argv[i], "--bus-name")) {
			if (++i == argc) {
				g_printerr ("Missing bus name argument\n");
				exit (1);
			}
			if (!g_dbus_is_name (argv[i])) {
				g_printerr ("Invalid bus name\n");
				exit (1);
			}
			bus_name = argv[i];
		} else
			break;
	}
	shift = i - 1;

	if (_LOGD_enabled ()) {
		GString *args;

		args = g_string_new (NULL);
		for (i = 0; i < argc; i++) {
			if (i > 0)
				g_string_append_c (args, ' ');
			if (shift && 1 + shift == i)
				g_string_append (args, "  ");
			tmp = g_strescape (argv[i], NULL);
			g_string_append_printf (args, "\"%s\"", tmp);
			g_free (tmp);
		}

		_LOGD ("command line: %s", args->str);
		g_string_free (args, TRUE);

		for (iter = environ; iter && *iter; iter++)
			_LOGD ("environment: %s", *iter);
	}

	/* shift the arguments to the right leaving only those provided by openvpn */
	argv[shift] = argv[0];
	argv += shift;
	argc -= shift;

	is_restart = argc >= 7 && !g_strcmp0 (argv[6], "restart");

	proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
	                                       G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
	                                       NULL,
	                                       bus_name,
	                                       NM_VPN_DBUS_PLUGIN_PATH,
	                                       NM_VPN_DBUS_PLUGIN_INTERFACE,
	                                       NULL, &err);
	if (!proxy) {
		_LOGW ("Could not create a D-Bus proxy: %s", err->message);
		g_error_free (err);
		exit (1);
	}

	g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
	g_variant_builder_init (&ip4builder, G_VARIANT_TYPE_VARDICT);
	g_variant_builder_init (&ip6builder, G_VARIANT_TYPE_VARDICT);

	/* External world-visible VPN gateway */
	val = trusted_remote_to_gvariant ();
	if (val)
		g_variant_builder_add (&builder, "{sv}", NM_VPN_PLUGIN_CONFIG_EXT_GATEWAY, val);
	else
		helper_failed (proxy, "VPN Gateway");

	/* Internal VPN subnet gateway */
	tmp = getenv ("route_vpn_gateway");
	val = addr4_to_gvariant (tmp);
	if (val)
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_INT_GATEWAY, val);
	else {
		val = addr6_to_gvariant (tmp);
		if (val)
			g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_INT_GATEWAY, val);
	}

	/* VPN device */
	tmp = getenv ("dev");
	val = str_to_gvariant (tmp, FALSE);
	if (val)
		g_variant_builder_add (&builder, "{sv}", NM_VPN_PLUGIN_CONFIG_TUNDEV, val);
	else
		helper_failed (proxy, "Tunnel Device");

	if (tapdev == -1)
		tapdev = strncmp (tmp, "tap", 3) == 0;

	/* IPv4 address */
	tmp = getenv ("ifconfig_local");
	if (!tmp && is_restart)
		tmp = argv[4];
	if (tmp && strlen (tmp)) {
		val = addr4_to_gvariant (tmp);
		if (val) {
			has_ip4_address = TRUE;
			g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_ADDRESS, val);
		} else
			helper_failed (proxy, "IP4 Address");
	}

	/* PTP address; for vpnc PTP address == internal IP4 address */
	tmp = getenv ("ifconfig_remote");
	if (!tmp && is_restart)
		tmp = argv[5];
	val = addr4_to_gvariant (tmp);
	if (val) {
		/* Sigh.  Openvpn added 'topology' stuff in 2.1 that changes the meaning
		 * of the ifconfig bits without actually telling you what they are
		 * supposed to mean; basically relying on specific 'ifconfig' behavior.
		 */
		if (tmp && !strncmp (tmp, "255.", 4)) {
			guint32 addr;

			/* probably a netmask, not a PTP address; topology == subnet */
			addr = g_variant_get_uint32 (val);
			g_variant_unref (val);
			val = g_variant_new_uint32 (nm_utils_ip4_netmask_to_prefix (addr));
			g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_PREFIX, val);
			has_ip4_prefix = TRUE;
		} else
			g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_PTP, val);
	}

	/* Netmask
	 *
	 * Either TAP or TUN modes can have an arbitrary netmask in newer versions
	 * of openvpn, while in older versions only TAP mode would.  So accept a
	 * netmask if passed, otherwise default to /32 for TUN devices since they
	 * are usually point-to-point.
	 */
	tmp = getenv ("ifconfig_netmask");
	if (tmp && inet_pton (AF_INET, tmp, &temp_addr) > 0) {
		val = g_variant_new_uint32 (nm_utils_ip4_netmask_to_prefix (temp_addr.s_addr));
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_PREFIX, val);
	} else if (!tapdev) {
		if (has_ip4_address && !has_ip4_prefix) {
			val = g_variant_new_uint32 (32);
			g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_PREFIX, val);
		}
	} else
		_LOGW ("No IP4 netmask/prefix (missing or invalid 'ifconfig_netmask')");

	val = get_ip4_routes ();
	if (val)
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_ROUTES, val);
	else if (is_restart) {
		g_variant_builder_add (&ip4builder, "{sv}",
		                       NM_VPN_PLUGIN_IP4_CONFIG_PRESERVE_ROUTES,
		                       g_variant_new_boolean (TRUE));
	}

	/* IPv6 address */
	tmp = getenv ("ifconfig_ipv6_local");
	if (tmp && strlen (tmp)) {
		val = addr6_to_gvariant (tmp);
		if (val) {
			g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_ADDRESS, val);
			has_ip6_address = TRUE;
		} else
			helper_failed (proxy, "IP6 Address");
	}

	/* IPv6 remote address */
	tmp = getenv ("ifconfig_ipv6_remote");
	if (tmp && strlen (tmp)) {
		val = addr6_to_gvariant (tmp);
		if (val)
			g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_PTP, val);
		else
			helper_failed (proxy, "IP6 PTP Address");
	}

	/* IPv6 netbits */
	tmp = getenv ("ifconfig_ipv6_netbits");
	if (tmp && strlen (tmp)) {
		long int netbits;

		errno = 0;
		netbits = strtol (tmp, NULL, 10);
		if (errno || netbits < 0 || netbits > 128) {
			_LOGW ("Ignoring invalid prefix '%s'", tmp);
		} else {
			val = g_variant_new_uint32 ((guint32) netbits);
			g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_PREFIX, val);
		}
	}

	val = get_ip6_routes ();
	if (val)
		g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_ROUTES, val);
	else if (is_restart) {
		g_variant_builder_add (&ip6builder, "{sv}",
		                       NM_VPN_PLUGIN_IP6_CONFIG_PRESERVE_ROUTES,
		                       g_variant_new_boolean (TRUE));
	}

	/* DNS and WINS servers */
	dns_domains = g_ptr_array_sized_new (3);
	dns4_list = g_ptr_array_new ();
	dns6_list = g_ptr_array_new ();
	nbns_list = g_ptr_array_new ();

	for (i = 1; i < 256; i++) {
		char *env_name;

		env_name = g_strdup_printf ("foreign_option_%d", i);
		tmp = getenv (env_name);
		g_free (env_name);

		if (!tmp || strlen (tmp) < 1)
			break;

		if (!g_str_has_prefix (tmp, "dhcp-option "))
			continue;

		tmp += 12; /* strlen ("dhcp-option ") */

		if (g_str_has_prefix (tmp, "DNS "))
			parse_addr_list (dns4_list, dns6_list, tmp + 4);
		else if (g_str_has_prefix (tmp, "WINS "))
			parse_addr_list (nbns_list, NULL, tmp + 5);
		else if (g_str_has_prefix (tmp, "DOMAIN ") && is_domain_valid (tmp + 7))
			g_ptr_array_add (dns_domains, tmp + 7);
	}

	if (dns4_list->len) {
		val = g_variant_new_array (G_VARIANT_TYPE_UINT32, (GVariant **) dns4_list->pdata, dns4_list->len);
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_DNS, val);
	}

	if (has_ip6_address && dns6_list->len) {
		val = g_variant_new_array (G_VARIANT_TYPE ("ay"), (GVariant **) dns6_list->pdata, dns6_list->len);
		g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_DNS, val);
	}

	if (nbns_list->len) {
		val = g_variant_new_array (G_VARIANT_TYPE_UINT32, (GVariant **) nbns_list->pdata, nbns_list->len);
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_NBNS, val);
	}

	if (dns_domains->len) {
		val = g_variant_new_strv ((const gchar **) dns_domains->pdata, dns_domains->len);
		g_variant_builder_add (&ip4builder, "{sv}", NM_VPN_PLUGIN_IP4_CONFIG_DOMAINS, val);

		/* Domains apply to both IPv4 and IPv6 configurations */
		if (has_ip6_address) {
			val = g_variant_new_strv ((const gchar **) dns_domains->pdata, dns_domains->len);
			g_variant_builder_add (&ip6builder, "{sv}", NM_VPN_PLUGIN_IP6_CONFIG_DOMAINS, val);
		}
	}

	g_ptr_array_unref (dns4_list);
	g_ptr_array_unref (dns6_list);
	g_ptr_array_unref (nbns_list);
	g_ptr_array_unref (dns_domains);

	/* Tunnel MTU */
	tmp = getenv ("tun_mtu");
	if (tmp && strlen (tmp)) {
		long int mtu;

		errno = 0;
		mtu = strtol (tmp, NULL, 10);
		if (errno || mtu < 0 || mtu > 20000) {
			_LOGW ("Ignoring invalid tunnel MTU '%s'", tmp);
		} else {
			val = g_variant_new_uint32 ((guint32) mtu);
			g_variant_builder_add (&builder, "{sv}", NM_VPN_PLUGIN_CONFIG_MTU, val);
		}
	}

	ip4config = g_variant_builder_end (&ip4builder);

	if (g_variant_n_children (ip4config)) {
		val = g_variant_new_boolean (TRUE);
		g_variant_builder_add (&builder, "{sv}", NM_VPN_PLUGIN_CONFIG_HAS_IP4, val);
	} else {
		g_variant_unref (ip4config);
		ip4config = NULL;
	}

	ip6config = g_variant_builder_end (&ip6builder);

	if (g_variant_n_children (ip6config)) {
		val = g_variant_new_boolean (TRUE);
		g_variant_builder_add (&builder, "{sv}", NM_VPN_PLUGIN_CONFIG_HAS_IP6, val);
	} else {
		g_variant_unref (ip6config);
		ip6config = NULL;
	}

	if (!ip4config && !ip6config)
		helper_failed (proxy, "IPv4 or IPv6 configuration");

	/* Send the config info to nm-openvpn-service */
	send_config (proxy, g_variant_builder_end (&builder), ip4config, ip6config);

	g_object_unref (proxy);

	return 0;
}
Пример #20
0
gboolean
ot_admin_builtin_set_origin (int argc, char **argv, GCancellable *cancellable, GError **error)
{
    gboolean ret = FALSE;
    g_autoptr(GOptionContext) context = NULL;
    const char *remotename = NULL;
    const char *url = NULL;
    const char *branch = NULL;
    glnx_unref_object OstreeRepo *repo = NULL;
    glnx_unref_object OstreeSysroot *sysroot = NULL;
    glnx_unref_object OstreeDeployment *target_deployment = NULL;

    context = g_option_context_new ("REMOTENAME URL [BRANCH]");

    if (!ostree_admin_option_context_parse (context, options, &argc, &argv,
                                            OSTREE_ADMIN_BUILTIN_FLAG_SUPERUSER,
                                            &sysroot, cancellable, error))
        goto out;

    if (argc < 3)
    {
        ot_util_usage_error (context, "REMOTENAME and URL must be specified", error);
        goto out;
    }

    remotename = argv[1];
    url = argv[2];
    if (argc > 3)
        branch = argv[3];

    if (!ostree_sysroot_load (sysroot, cancellable, error))
        goto out;

    if (!ostree_sysroot_get_repo (sysroot, &repo, cancellable, error))
        goto out;

    if (opt_index == -1)
    {
        target_deployment = ostree_sysroot_get_booted_deployment (sysroot);
        if (target_deployment == NULL)
        {
            g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                 "Not currently booted into an OSTree system");
            goto out;
        }
        /* To match the below */
        target_deployment = g_object_ref (target_deployment);
    }
    else
    {
        target_deployment = ot_admin_get_indexed_deployment (sysroot, opt_index, error);
        if (!target_deployment)
            goto out;
    }

    {   char **iter;
        g_autoptr(GVariantBuilder) optbuilder =
            g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
        g_autoptr(GVariant) options = NULL;

        for (iter = opt_set; iter && *iter; iter++)
        {
            const char *keyvalue = *iter;
            g_autofree char *subkey = NULL;
            g_autofree char *subvalue = NULL;

            if (!ot_parse_keyvalue (keyvalue, &subkey, &subvalue, error))
                goto out;

            g_variant_builder_add (optbuilder, "{s@v}",
                                   subkey, g_variant_new_variant (g_variant_new_string (subvalue)));
        }

        options = g_variant_ref_sink (g_variant_builder_end (optbuilder));

        if (!ostree_repo_remote_change (repo, NULL,
                                        OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS,
                                        remotename, url,
                                        options,
                                        cancellable, error))
            goto out;
    }

    {   GKeyFile *old_origin = ostree_deployment_get_origin (target_deployment);
        g_autofree char *origin_refspec = g_key_file_get_string (old_origin, "origin", "refspec", NULL);
        g_autofree char *origin_remote = NULL;
        g_autofree char *origin_ref = NULL;

        if (!ostree_parse_refspec (origin_refspec, &origin_remote, &origin_ref, error))
            goto out;

        {   g_autofree char *new_refspec = g_strconcat (remotename, ":", branch ? branch : origin_ref, NULL);
            g_autoptr(GKeyFile) new_origin = NULL;

            new_origin = ostree_sysroot_origin_new_from_refspec (sysroot, new_refspec);

            if (!ostree_sysroot_write_origin_file (sysroot, target_deployment, new_origin,
                                                   cancellable, error))
                goto out;
        }
    }

    ret = TRUE;
out:
    return ret;
}
gboolean dbus_plugin_call_response(struct custom_data *ctx, UserRequest *ur, struct dbus_request_info *dbus_info, enum tcore_response_command command, unsigned int data_len, const void *data)
{
	int i = 0;
	GSList *co_list;
	CoreObject *co_call;
	char *modem_name = NULL;
	TcorePlugin *p = NULL;

	modem_name = tcore_user_request_get_modem_name(ur);
	if (!modem_name)
		return FALSE;

	p = tcore_server_find_plugin(ctx->server, modem_name);
	free(modem_name);
	if (!p)
		return FALSE;

	co_list = tcore_plugin_get_core_objects_bytype(p, CORE_OBJECT_TYPE_NETWORK);
	if (!co_list) {
		return FALSE;
	}

	co_call = (CoreObject *)co_list->data;
	g_slist_free(co_list);

	if (!co_call) {
		return FALSE;
	}

	switch (command) {
		case TRESP_CALL_DIAL: {
			struct tresp_call_dial *resp = (struct tresp_call_dial*)data;

			dbg("receive TRESP_CALL_DIAL");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_dial(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_ANSWER: {
			struct tresp_call_answer *resp = (struct tresp_call_answer*)data;

			dbg("receive TRESP_CALL_ANSWER");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_answer(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_END: {
			struct tresp_call_end *resp = (struct tresp_call_end*)data;

			dbg("receive TRESP_CALL_END");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->err);
			dbg("resp->type : [%d]", resp->type);

			telephony_call_complete_end(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id, resp->type );

		} break;

		case TRESP_CALL_HOLD: {
			struct tresp_call_hold *resp = (struct tresp_call_hold*)data;

			dbg("receive TRESP_CALL_HOLD");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_hold(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_ACTIVE: {
			struct tresp_call_active *resp = (struct tresp_call_active*)data;

			dbg("receive TRESP_CALL_ACTIVE");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_active(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_SWAP: {
			struct tresp_call_swap *resp = (struct tresp_call_swap*)data;

			dbg("receive TRESP_CALL_SWAP");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_swap(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_JOIN: {
			struct tresp_call_join *resp = (struct tresp_call_join*)data;

			dbg("receive TRESP_CALL_JOIN");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_join(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;


		case TRESP_CALL_SPLIT: {
			struct tresp_call_split *resp = (struct tresp_call_split*)data;

			dbg("receive TRESP_CALL_SPLIT");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_split(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_DEFLECT: {
			struct tresp_call_deflect *resp = (struct tresp_call_deflect*)data;

			dbg("receive TRESP_CALL_DEFLECT");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_deflect(dbus_info->interface_object, dbus_info->invocation, resp->err );

		} break;

		case TRESP_CALL_TRANSFER: {
			struct tresp_call_transfer *resp = (struct tresp_call_transfer*)data;

			dbg("receive TRESP_CALL_TRANSFER");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->id : [%d]", resp->id);

			telephony_call_complete_transfer(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->id );

		} break;

		case TRESP_CALL_SEND_DTMF: {
			struct tresp_call_dtmf *resp = (struct tresp_call_dtmf*)data;

			dbg("receive TRESP_CALL_SEND_DTMF");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_dtmf(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_SET_SOUND_PATH: {
			struct tresp_call_sound_set_path *resp = (struct tresp_call_sound_set_path*)data;

			dbg("receive TRESP_CALL_SET_SOUND_PATH");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_set_sound_path(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_SET_SOUND_VOLUME_LEVEL: {
			struct tresp_call_sound_set_volume_level *resp = (struct tresp_call_sound_set_volume_level*)data;

			dbg("receive TRESP_CALL_SET_SOUND_VOLUME_LEVEL");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_set_volume(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_GET_SOUND_VOLUME_LEVEL: {
			struct tresp_call_sound_get_volume_level *resp = (struct tresp_call_sound_get_volume_level*)data;
			GVariant *result = 0;
			GVariantBuilder b;

			dbg("receive TRESP_CALL_GET_SOUND_VOLUME_LEVEL");

			g_variant_builder_init(&b, G_VARIANT_TYPE("aa{sv}"));

			g_variant_builder_open(&b, G_VARIANT_TYPE("a{sv}"));

			dbg("resp->err : [%d]", resp->err);

			g_variant_builder_add(&b, "{sv}", "err", g_variant_new_int32(resp->err));

			if ( !resp->err ) {

				dbg("resp->record_num : [%d]", resp->record_num);

				for ( i=0; i<resp->record_num; i++ ) {
					dbg("resp->type : [%d]", resp->record[i].sound);
					dbg("resp->level : [%d]", resp->record[i].volume);

					g_variant_builder_add(&b, "{sv}", "type", g_variant_new_int32(resp->record[i].sound));
					g_variant_builder_add(&b, "{sv}", "level", g_variant_new_int32(resp->record[i].volume));
				} 

			}

			g_variant_builder_close(&b);

			result = g_variant_builder_end(&b);

			telephony_call_complete_get_volume(dbus_info->interface_object, dbus_info->invocation, resp->err, result );

			g_variant_unref(result);

		} break;

		case TRESP_CALL_MUTE: {
			struct tresp_call_mute *resp = (struct tresp_call_mute*)data;

			dbg("receive TRESP_CALL_MUTE");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_mute(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_UNMUTE: {
			struct tresp_call_unmute *resp = (struct tresp_call_unmute*)data;

			dbg("receive TRESP_CALL_UNMUTE");
			dbg("resp->err : [%d]", resp->err);

			telephony_call_complete_unmute(dbus_info->interface_object, dbus_info->invocation, resp->err);
		} break;

		case TRESP_CALL_GET_MUTE_STATUS: {
			struct tresp_call_get_mute_status *resp = (struct tresp_call_get_mute_status*)data;

			dbg("receive TRESP_CALL_GET_MUTE_STATUS");
			dbg("resp->err : [%d]", resp->err);
			dbg("resp->status : [%d]", resp->status);

			telephony_call_complete_get_mute_status(dbus_info->interface_object, dbus_info->invocation, resp->err, resp->status );

		} break;

		case TRESP_CALL_SET_SOUND_RECORDING: {
			struct tresp_call_sound_set_recording *resp = (struct tresp_call_sound_set_recording*)data;
			telephony_call_complete_set_sound_recording(dbus_info->interface_object, dbus_info->invocation, resp->err );

		} break;

		case TRESP_CALL_SET_SOUND_EQUALIZATION: {
			struct tresp_call_sound_set_equalization *resp = (struct tresp_call_sound_set_equalization*)data;
			telephony_call_complete_set_sound_equalization(dbus_info->interface_object, dbus_info->invocation, resp->err );

		} break;

		case TRESP_CALL_SET_SOUND_NOISE_REDUCTION: {
			struct tresp_call_sound_set_noise_reduction *resp = (struct tresp_call_sound_set_noise_reduction*)data;
			telephony_call_complete_set_sound_noise_reduction(dbus_info->interface_object, dbus_info->invocation, resp->err );

		} break;

		default:
			dbg("not handled command[%d]", command);
		break;

	}

	return TRUE;
}
static GoaObject *
add_account (GoaProvider    *provider,
             GoaClient      *client,
             GtkDialog      *dialog,
             GtkBox         *vbox,
             GError        **error)
{
  AddAccountData data;
  GVariantBuilder credentials;
  GVariantBuilder details;
  GoaEwsClient *ews_client;
  GoaObject *ret;
  gboolean accept_ssl_errors;
  const gchar *email_address;
  const gchar *server;
  const gchar *password;
  const gchar *username;
  const gchar *provider_type;
  gint response;

  ews_client = NULL;
  accept_ssl_errors = FALSE;

  ret = NULL;

  memset (&data, 0, sizeof (AddAccountData));
  data.loop = g_main_loop_new (NULL, FALSE);
  data.dialog = dialog;
  data.error = NULL;

  create_account_details_ui (provider, dialog, vbox, TRUE, &data);
  gtk_widget_show_all (GTK_WIDGET (vbox));

  ews_client = goa_ews_client_new ();

 ews_again:
  response = gtk_dialog_run (dialog);
  if (response != GTK_RESPONSE_OK)
    {
      g_set_error (&data.error,
                   GOA_ERROR,
                   GOA_ERROR_DIALOG_DISMISSED,
                   _("Dialog was dismissed"));
      goto out;
    }

  email_address = gtk_entry_get_text (GTK_ENTRY (data.email_address));
  password = gtk_entry_get_text (GTK_ENTRY (data.password));
  username = gtk_entry_get_text (GTK_ENTRY (data.username));
  server = gtk_entry_get_text (GTK_ENTRY (data.server));

  /* See if there's already an account of this type with the
   * given identity
   */
  provider_type = goa_provider_get_provider_type (provider);
  if (!goa_utils_check_duplicate (client,
                                  username,
                                  provider_type,
                                  (GoaPeekInterfaceFunc) goa_object_peek_password_based,
                                  &data.error))
    goto out;

  goa_ews_client_autodiscover (ews_client,
                               email_address,
                               password,
                               username,
                               server,
                               accept_ssl_errors,
                               NULL,
                               autodiscover_cb,
                               &data);
  goa_spinner_button_start (GOA_SPINNER_BUTTON (data.spinner_button));
  g_main_loop_run (data.loop);

  if (data.error != NULL)
    {
      gchar *markup;

      if (data.error->code == GOA_ERROR_SSL)
        {
          goa_spinner_button_set_label (GOA_SPINNER_BUTTON (data.spinner_button), _("_Ignore"));
          accept_ssl_errors = TRUE;
        }
      else
        {
          goa_spinner_button_set_label (GOA_SPINNER_BUTTON (data.spinner_button), _("_Try Again"));
          accept_ssl_errors = FALSE;
        }

      markup = g_strdup_printf ("<b>%s:</b> %s",
                                _("Error connecting to Microsoft Exchange server"),
                                data.error->message);
      g_clear_error (&data.error);

      gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
      g_free (markup);

      gtk_expander_set_expanded (GTK_EXPANDER (data.expander), TRUE);
      gtk_widget_set_no_show_all (data.cluebar, FALSE);
      gtk_widget_show_all (data.cluebar);
      goto ews_again;
    }

  gtk_widget_hide (GTK_WIDGET (dialog));

  g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT);
  g_variant_builder_add (&credentials, "{sv}", "password", g_variant_new_string (password));

  g_variant_builder_init (&details, G_VARIANT_TYPE ("a{ss}"));
  g_variant_builder_add (&details, "{ss}", "MailEnabled", "true");
  g_variant_builder_add (&details, "{ss}", "CalendarEnabled", "true");
  g_variant_builder_add (&details, "{ss}", "ContactsEnabled", "true");
  g_variant_builder_add (&details, "{ss}", "Host", server);
  g_variant_builder_add (&details, "{ss}", "AcceptSslErrors", (accept_ssl_errors) ? "true" : "false");

  /* OK, everything is dandy, add the account */
  /* we want the GoaClient to update before this method returns (so it
   * can create a proxy for the new object) so run the mainloop while
   * waiting for this to complete
   */
  goa_manager_call_add_account (goa_client_get_manager (client),
                                goa_provider_get_provider_type (provider),
                                username,
                                email_address,
                                g_variant_builder_end (&credentials),
                                g_variant_builder_end (&details),
                                NULL, /* GCancellable* */
                                (GAsyncReadyCallback) add_account_cb,
                                &data);
  g_main_loop_run (data.loop);
  if (data.error != NULL)
    goto out;

  ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client),
                                                      data.account_object_path));

 out:
  /* We might have an object even when data.error is set.
   * eg., if we failed to store the credentials in the keyring.
   */
  if (data.error != NULL)
    g_propagate_error (error, data.error);
  else
    g_assert (ret != NULL);

  g_free (data.account_object_path);
  if (data.loop != NULL)
    g_main_loop_unref (data.loop);
  if (ews_client != NULL)
    g_object_unref (ews_client);
  return ret;
}
Пример #23
0
static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
                       const struct sr_channel_group *cg)
{
    struct sr_channel *ch;
    GVariant *gvar;
    GVariantBuilder gvb;

    if (key == SR_CONF_SCAN_OPTIONS) {
        *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                          scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
        return SR_OK;
    }

    if (key == SR_CONF_DEVICE_OPTIONS && !sdi) {
        *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                          drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
        return SR_OK;
    }

    if (!sdi)
        return SR_ERR_ARG;

    if (!cg) {
        switch (key) {
        case SR_CONF_DEVICE_OPTIONS:
            *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                              devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
            break;
        case SR_CONF_SAMPLERATE:
            g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
            gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates,
                                             ARRAY_SIZE(samplerates), sizeof(uint64_t));
            g_variant_builder_add(&gvb, "{sv}", "samplerate-steps", gvar);
            *data = g_variant_builder_end(&gvb);
            break;
        default:
            return SR_ERR_NA;
        }
    } else {
        ch = cg->channels->data;
        switch (key) {
        case SR_CONF_DEVICE_OPTIONS:
            if (ch->type == SR_CHANNEL_LOGIC)
                *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                                  devopts_cg_logic, ARRAY_SIZE(devopts_cg_logic),
                                                  sizeof(uint32_t));
            else if (ch->type == SR_CHANNEL_ANALOG) {
                if (strcmp(cg->name, "Analog") == 0)
                    *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                                      devopts_cg_analog_group, ARRAY_SIZE(devopts_cg_analog_group),
                                                      sizeof(uint32_t));
                else
                    *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
                                                      devopts_cg_analog_channel, ARRAY_SIZE(devopts_cg_analog_channel),
                                                      sizeof(uint32_t));
            }
            else
                return SR_ERR_BUG;
            break;
        case SR_CONF_PATTERN_MODE:
            /* The analog group (with all 4 channels) shall not have a pattern property. */
            if (strcmp(cg->name, "Analog") == 0)
                return SR_ERR_NA;

            if (ch->type == SR_CHANNEL_LOGIC)
                *data = g_variant_new_strv(logic_pattern_str,
                                           ARRAY_SIZE(logic_pattern_str));
            else if (ch->type == SR_CHANNEL_ANALOG)
                *data = g_variant_new_strv(analog_pattern_str,
                                           ARRAY_SIZE(analog_pattern_str));
            else
                return SR_ERR_BUG;
            break;
        default:
            return SR_ERR_NA;
        }
    }

    return SR_OK;
}
static gboolean
refresh_account (GoaProvider    *provider,
                 GoaClient      *client,
                 GoaObject      *object,
                 GtkWindow      *parent,
                 GError        **error)
{
  AddAccountData data;
  GVariantBuilder builder;
  GoaAccount *account;
  GoaEwsClient *ews_client;
  GoaExchange *exchange;
  GtkWidget *dialog;
  GtkWidget *vbox;
  gboolean accept_ssl_errors;
  gboolean ret;
  const gchar *email_address;
  const gchar *server;
  const gchar *password;
  const gchar *username;
  gint response;

  g_return_val_if_fail (GOA_IS_EXCHANGE_PROVIDER (provider), FALSE);
  g_return_val_if_fail (GOA_IS_CLIENT (client), FALSE);
  g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);
  g_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  ews_client = NULL;
  ret = FALSE;

  dialog = gtk_dialog_new_with_buttons (NULL,
                                        parent,
                                        GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                        NULL);
  gtk_container_set_border_width (GTK_CONTAINER (dialog), 12);
  gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
  gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);

  vbox = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
  gtk_box_set_spacing (GTK_BOX (vbox), 12);

  memset (&data, 0, sizeof (AddAccountData));
  data.loop = g_main_loop_new (NULL, FALSE);
  data.dialog = GTK_DIALOG (dialog);
  data.error = NULL;

  create_account_details_ui (provider, GTK_DIALOG (dialog), GTK_BOX (vbox), FALSE, &data);

  account = goa_object_peek_account (object);
  email_address = goa_account_get_presentation_identity (account);
  gtk_entry_set_text (GTK_ENTRY (data.email_address), email_address);
  gtk_editable_set_editable (GTK_EDITABLE (data.email_address), FALSE);

  gtk_widget_show_all (dialog);

  ews_client = goa_ews_client_new ();

 ews_again:
  response = gtk_dialog_run (GTK_DIALOG (dialog));
  if (response != GTK_RESPONSE_OK)
    {
      g_set_error (error,
                   GOA_ERROR,
                   GOA_ERROR_DIALOG_DISMISSED,
                   _("Dialog was dismissed"));
      goto out;
    }

  password = gtk_entry_get_text (GTK_ENTRY (data.password));
  username = goa_account_get_identity (account);

  exchange = goa_object_peek_exchange (object);
  accept_ssl_errors = goa_util_lookup_keyfile_boolean (object, "AcceptSslErrors");
  server = goa_exchange_get_host (exchange);

  goa_ews_client_autodiscover (ews_client,
                               email_address,
                               password,
                               username,
                               server,
                               accept_ssl_errors,
                               NULL,
                               autodiscover_cb,
                               &data);
  goa_spinner_button_start (GOA_SPINNER_BUTTON (data.spinner_button));
  g_main_loop_run (data.loop);

  if (data.error != NULL)
    {
      GtkWidget *button;
      gchar *markup;

      markup = g_strdup_printf ("<b>%s:</b> %s",
                                _("Error connecting to Microsoft Exchange server"),
                                data.error->message);
      g_clear_error (&data.error);

      gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
      g_free (markup);

      button = gtk_dialog_get_widget_for_response (data.dialog, GTK_RESPONSE_OK);
      gtk_button_set_label (GTK_BUTTON (button), _("_Try Again"));
      gtk_widget_set_no_show_all (data.cluebar, FALSE);
      gtk_widget_show_all (data.cluebar);
      goto ews_again;
    }

  /* TODO: run in worker thread */
  g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
  g_variant_builder_add (&builder, "{sv}", "password", g_variant_new_string (password));

  if (!goa_utils_store_credentials_for_object_sync (provider,
                                                    object,
                                                    g_variant_builder_end (&builder),
                                                    NULL, /* GCancellable */
                                                    error))
    goto out;

  goa_account_call_ensure_credentials (account,
                                       NULL, /* GCancellable */
                                       NULL, NULL); /* callback, user_data */

  ret = TRUE;

 out:
  gtk_widget_destroy (dialog);
  if (data.loop != NULL)
    g_main_loop_unref (data.loop);
  if (ews_client != NULL)
    g_object_unref (ews_client);
  return ret;
}
Пример #25
0
static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
		const struct sr_channel_group *cg)
{
	GVariant *tuple, *rational[2];
	GVariantBuilder gvb;
	unsigned int i;
	GVariant *gvar;
	struct dev_context *devc = NULL;

	if (key == SR_CONF_SCAN_OPTIONS) {
		*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
			scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
		return SR_OK;
	} else if (key == SR_CONF_DEVICE_OPTIONS && !sdi) {
		*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
			drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
		return SR_OK;
	}

	if (sdi)
		devc = sdi->priv;

	if (!cg) {
		switch (key) {
		case SR_CONF_DEVICE_OPTIONS:
			*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
				devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
			break;
		case SR_CONF_SAMPLERATE:
			g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
			gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"),
				samplerates, ARRAY_SIZE(samplerates),
				sizeof(uint64_t));
			g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
			*data = g_variant_builder_end(&gvb);
			break;
		default:
			return SR_ERR_NA;
		}
	} else {
		switch (key) {
		case SR_CONF_DEVICE_OPTIONS:
			*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
				devopts_cg, ARRAY_SIZE(devopts_cg), sizeof(uint32_t));
			break;
		case SR_CONF_COUPLING:
			if (!devc)
				return SR_ERR_NA;
			*data = g_variant_new_strv(devc->coupling_vals, devc->coupling_tab_size);
			break;
		case SR_CONF_VDIV:
			g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
			for (i = 0; i < ARRAY_SIZE(vdivs); i++) {
				rational[0] = g_variant_new_uint64(vdivs[i][0]);
				rational[1] = g_variant_new_uint64(vdivs[i][1]);
				tuple = g_variant_new_tuple(rational, 2);
				g_variant_builder_add_value(&gvb, tuple);
			}
			*data = g_variant_builder_end(&gvb);
			break;
		default:
			return SR_ERR_NA;
		}
	}

	return SR_OK;
}
Пример #26
0
static void
on_get_all_done_for_info (GObject *object,
                          GAsyncResult *res,
                          gpointer user_data)
{
  GetServiceInfoData *data = user_data;
  GError *error = NULL;
  cleanup_unref_variant GVariant *reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION (object), res, &error);

  if (error)
    {
      end_invocation_take_gerror (data->invocation, error);
      g_free (data);
      return;
    }

  cleanup_unref_variant GVariant *props;
  g_variant_get (reply, "(@a{sv})", &props);

  GVariantBuilder bob;
  g_variant_builder_init (&bob, G_VARIANT_TYPE("a{sv}"));

  copy_entry (&bob, props, "Id");
  copy_entry (&bob, props, "Description");
  copy_entry (&bob, props, "LoadState");
  copy_entry (&bob, props, "ActiveState");
  copy_entry (&bob, props, "SubState");
  copy_entry (&bob, props, "UnitFileState");
  copy_entry (&bob, props, "ExecMainStartTimestamp");
  copy_entry (&bob, props, "ExecMainExitTimestamp");
  copy_entry (&bob, props, "ActiveEnterTimestamp");
  copy_entry (&bob, props, "ActiveExitTimestamp");
  copy_entry (&bob, props, "InactiveEnterTimestamp");
  copy_entry (&bob, props, "InactiveExitTimestamp");
  copy_entry (&bob, props, "ConditionTimestamp");
  copy_entry (&bob, props, "SourcePath");
  copy_entry (&bob, props, "FragmentPath");
  copy_entry (&bob, props, "LoadError");
  copy_entry (&bob, props, "ConditionResult");
  copy_entry (&bob, props, "StatusText");
  copy_entry (&bob, props, "DefaultControlGroup");

  const gchar *id = NULL, *cgroup = NULL;
  uint32_t main_pid = 0, exec_main_pid = 0, control_pid = 0;

  g_variant_lookup (props, "Id", "&s", &id);
  g_variant_lookup (props, "DefaultControlGroup", "&s", &cgroup);
  g_variant_lookup (props, "ExecMainPid", "u", &exec_main_pid);
  g_variant_lookup (props, "MainPid", "u", &main_pid);
  g_variant_lookup (props, "ControlPid", "u", &control_pid);

  if (cgroup)
    {
      pid_t extra_pids[3];
      int n_extra_pids = 0;
      if (main_pid > 0)
        extra_pids[n_extra_pids++] = main_pid;
      if (exec_main_pid > 0)
        extra_pids[n_extra_pids++] = exec_main_pid;
      if (control_pid > 0)
        extra_pids[n_extra_pids++] = control_pid;

      GVariant *c = collect_cgroup_and_extra_by_spec (cgroup, FALSE, TRUE, extra_pids, n_extra_pids);
      if (c)
        g_variant_builder_add (&bob, "{sv}", "Processes", c);
    }

  cockpit_services_complete_get_service_info (COCKPIT_SERVICES (data->services), data->invocation,
                                              g_variant_builder_end (&bob));
  g_free (data);
}
void settings_manager_add_interested (SettingsManager* self, const gchar* app_desktop_name) {
	static const char key[] = "interested-media-players";
	GVariantType* _tmp0_;
	GVariantType* _tmp1_;
	GVariantBuilder* _tmp2_;
	GVariantBuilder* _tmp3_;
	GVariantBuilder* players;
	GSettings* _tmp4_;
	gchar** _tmp5_;
	gchar** _tmp6_ = NULL;
	GVariantBuilder* _tmp12_;
	const gchar* _tmp13_;
	GSettings* _tmp14_;
	GVariantBuilder* _tmp15_;
	GVariant* _tmp16_ = NULL;
	GVariant* _tmp17_;
	GSettings* _tmp18_;
	g_return_if_fail (self != NULL);
	g_return_if_fail (app_desktop_name != NULL);
	_tmp0_ = g_variant_type_new ("as");
	_tmp1_ = _tmp0_;
	_tmp2_ = g_variant_builder_new (_tmp1_);
	_tmp3_ = _tmp2_;
	_g_variant_type_free0 (_tmp1_);
	players = _tmp3_;
	_tmp4_ = self->priv->settings;
	_tmp6_ = _tmp5_ = g_settings_get_strv (_tmp4_, key);
	{
		gchar** player_collection = NULL;
		gint player_collection_length1 = 0;
		gint _player_collection_size_ = 0;
		gint player_it = 0;
		player_collection = _tmp6_;
		player_collection_length1 = _vala_array_length (_tmp5_);
		for (player_it = 0; player_it < _vala_array_length (_tmp5_); player_it = player_it + 1) {
			gchar* _tmp7_;
			gchar* player = NULL;
			_tmp7_ = g_strdup (player_collection[player_it]);
			player = _tmp7_;
			{
				const gchar* _tmp8_;
				const gchar* _tmp9_;
				GVariantBuilder* _tmp10_;
				const gchar* _tmp11_;
				_tmp8_ = player;
				_tmp9_ = app_desktop_name;
				if (g_strcmp0 (_tmp8_, _tmp9_) == 0) {
					_g_free0 (player);
					player_collection = (_vala_array_free (player_collection, player_collection_length1, (GDestroyNotify) g_free), NULL);
					_g_variant_builder_unref0 (players);
					return;
				}
				_tmp10_ = players;
				_tmp11_ = player;
				g_variant_builder_add (_tmp10_, "s", _tmp11_, NULL);
				_g_free0 (player);
			}
		}
		player_collection = (_vala_array_free (player_collection, player_collection_length1, (GDestroyNotify) g_free), NULL);
	}
	_tmp12_ = players;
	_tmp13_ = app_desktop_name;
	g_variant_builder_add (_tmp12_, "s", _tmp13_, NULL);
	_tmp14_ = self->priv->settings;
	_tmp15_ = players;
	_tmp16_ = g_variant_builder_end (_tmp15_);
	g_variant_ref_sink (_tmp16_);
	_tmp17_ = _tmp16_;
	g_settings_set_value (_tmp14_, key, _tmp17_);
	_g_variant_unref0 (_tmp17_);
	_tmp18_ = self->priv->settings;
	g_settings_apply (_tmp18_);
	_g_variant_builder_unref0 (players);
}
Пример #28
0
static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
		const struct sr_channel_group *cg)
{
	GVariantBuilder gvb;
	GVariant *gvar, *rational[2];
	GSList *l;
	int i;

	switch (key) {
		case SR_CONF_SCAN_OPTIONS:
	case SR_CONF_DEVICE_OPTIONS:
		break;
	case SR_CONF_SAMPLERATE:
	case SR_CONF_TRIGGER_SOURCE:
	case SR_CONF_TRIGGER_SLOPE:
	case SR_CONF_BUFFERSIZE:
		if (!sdi || cg)
			return SR_ERR_NA;
		break;
	case SR_CONF_VDIV:
	case SR_CONF_COUPLING:
		if (!sdi)
			return SR_ERR_NA;
		if (!cg)
			return SR_ERR_CHANNEL_GROUP;
		l = g_slist_find(sdi->channel_groups, cg);
		if (!l)
			return SR_ERR_ARG;
		break;
	default:
		return SR_ERR_NA;
	}

	switch (key) {
	case SR_CONF_SCAN_OPTIONS:
		*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
				scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
		break;
	case SR_CONF_DEVICE_OPTIONS:
		if (!sdi)
			*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
					drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
		else if (!cg)
			*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
					devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
		else
			*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
					cgopts, ARRAY_SIZE(cgopts), sizeof(uint32_t));
		break;
	case SR_CONF_SAMPLERATE:
		g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
		gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"),
				samplerates, ARRAY_SIZE(samplerates), sizeof(uint64_t));
		g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
		*data = g_variant_builder_end(&gvb);
		break;
	case SR_CONF_TRIGGER_SOURCE:
		*data = g_variant_new_strv(trigger_sources, ARRAY_SIZE(trigger_sources));
		break;
	case SR_CONF_TRIGGER_SLOPE:
		*data = g_variant_new_strv(trigger_slopes, ARRAY_SIZE(trigger_slopes));
		break;
	case SR_CONF_BUFFERSIZE:
		*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
				buffersizes, ARRAY_SIZE(buffersizes), sizeof(uint64_t));
		break;
	case SR_CONF_VDIV:
		g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
		for (i = 0; i < (int)ARRAY_SIZE(vdivs); i++) {
			rational[0] = g_variant_new_uint64(vdivs[i][0]);
			rational[1] = g_variant_new_uint64(vdivs[i][1]);
			gvar = g_variant_new_tuple(rational, 2);
			g_variant_builder_add_value(&gvb, gvar);
		}
		*data = g_variant_builder_end(&gvb);
		break;
	case SR_CONF_COUPLING:
		*data = g_variant_new_strv(coupling, ARRAY_SIZE(coupling));
		break;
	}

	return SR_OK;
}
Пример #29
0
/* the logind documentation says: "ListSeats() returns an array with all
 * currently available seats. The structure in the array consists of the
 * following fields: seat id, seat object path.". however, ConsoleKit's
 * GetSeats method returns only the object path, so we have to call
 * GetId for each seat */
static gboolean on_handle_list_seats(LoginKitManager *interface,
                                     GDBusMethodInvocation *invocation,
                                     gpointer user_data)
{
	GVariantIter iter;
	GVariant *reply;
	GError *error = NULL;
	GDBusConnection *bus;
	GVariantBuilder *builder;
	GVariant *ret;
	GVariant *seats;
	char *seat;
	char *id;

	g_log(G_LOG_DOMAIN, G_LOG_LEVEL_INFO, "listing available seats");

	bus = bus_get();
	if (NULL == bus)
		return FALSE;

	/* list all seats */
	reply = g_dbus_connection_call_sync(bus,
	                                    "org.freedesktop.ConsoleKit",
	                                    "/org/freedesktop/ConsoleKit/Manager",
	                                    "org.freedesktop.ConsoleKit.Manager",
	                                    "GetSeats",
	                                    NULL,
	                                    G_VARIANT_TYPE("(ao)"),
	                                    G_DBUS_CALL_FLAGS_NONE,
	                                    -1,
	                                    NULL,
	                                    &error);
	if (NULL == reply) {
		if (NULL != error)
			g_error_free(error);
		return FALSE;
	}

	seats = g_variant_get_child_value(reply, 0);
	g_variant_iter_init(&iter, seats);

	/* create a builder object, to initialize an array */
	builder = g_variant_builder_new(G_VARIANT_TYPE("a(so)"));

	/* do a best-effort attempt to enumerate all seats */
	while (TRUE == g_variant_iter_loop(&iter, "o", &seat, NULL)) {
		id = get_seat_id(bus, seat);
		if (NULL == id)
			continue;
		g_variant_builder_add(builder, "(so)", id, seat);
	}

	g_variant_unref(reply);
	g_variant_unref(seats);

	ret = g_variant_new("a(so)", builder);
	g_variant_builder_unref(builder);

	login_kit_manager_complete_list_seats(interface, invocation, ret);

	return TRUE;
}
Пример #30
0
/**
 * fwupd_result_to_data:
 * @result: A #FwupdResult
 * @type_string: The Gvariant type string, e.g. "{sa{sv}}" or "(a{sv})"
 *
 * Creates a GVariant from the result data.
 *
 * Returns: the GVariant, or %NULL for error
 *
 * Since: 0.7.0
 **/
GVariant *
fwupd_result_to_data (FwupdResult *result, const gchar *type_string)
{
	FwupdResultPrivate *priv = GET_PRIVATE (result);
	GVariantBuilder builder;

	g_return_val_if_fail (FWUPD_IS_RESULT (result), NULL);
	g_return_val_if_fail (type_string != NULL, NULL);

	/* create an array with all the metadata in */
	g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
	if (priv->guid != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_GUID,
				       g_variant_new_string (priv->guid));
	}
	if (priv->device_name != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_NAME,
				       g_variant_new_string (priv->device_name));
	}
	if (priv->device_vendor != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_VENDOR,
				       g_variant_new_string (priv->device_vendor));
	}
	if (priv->device_flags > 0) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_FLAGS,
				       g_variant_new_uint64 (priv->device_flags));
	}
	if (priv->device_created > 0) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_CREATED,
				       g_variant_new_uint64 (priv->device_created));
	}
	if (priv->device_modified > 0) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_MODIFIED,
				       g_variant_new_uint64 (priv->device_modified));
	}

	if (priv->update_id != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_ID,
				       g_variant_new_string (priv->update_id));
	}
	if (priv->device_description != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_DESCRIPTION,
				       g_variant_new_string (priv->device_description));
	}
	if (priv->update_filename != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_FILENAME,
				       g_variant_new_string (priv->update_filename));
	}
	if (priv->device_checksum != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_CHECKSUM,
				       g_variant_new_string (priv->device_checksum));
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_CHECKSUM_KIND,
				       g_variant_new_uint32 (priv->device_checksum_kind));
	}
	if (priv->update_license != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_LICENSE,
				       g_variant_new_string (priv->update_license));
	}
	if (priv->update_name != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_NAME,
				       g_variant_new_string (priv->update_name));
	}
	if (priv->update_error != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_ERROR,
				       g_variant_new_string (priv->update_error));
	}
	if (priv->update_state != FWUPD_UPDATE_STATE_UNKNOWN) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_STATE,
				       g_variant_new_uint32 (priv->update_state));
	}
	if (priv->device_provider != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_PROVIDER,
				       g_variant_new_string (priv->device_provider));
	}
	if (priv->update_size != 0) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_SIZE,
				       g_variant_new_uint64 (priv->update_size));
	}
	if (priv->update_trust_flags != 0) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_TRUST_FLAGS,
				       g_variant_new_uint64 (priv->update_trust_flags));
	}
	if (priv->update_summary != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_SUMMARY,
				       g_variant_new_string (priv->update_summary));
	}
	if (priv->update_description != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_DESCRIPTION,
				       g_variant_new_string (priv->update_description));
	}
	if (priv->update_checksum != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_CHECKSUM,
				       g_variant_new_string (priv->update_checksum));
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_CHECKSUM_KIND,
				       g_variant_new_uint32 (priv->update_checksum_kind));
	}
	if (priv->update_uri != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_URI,
				       g_variant_new_string (priv->update_uri));
	}
	if (priv->update_homepage != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_HOMEPAGE,
				       g_variant_new_string (priv->update_homepage));
	}
	if (priv->update_version != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_VERSION,
				       g_variant_new_string (priv->update_version));
	}
	if (priv->update_vendor != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_UPDATE_VENDOR,
				       g_variant_new_string (priv->update_vendor));
	}
	if (priv->device_version != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_VERSION,
				       g_variant_new_string (priv->device_version));
	}
	if (priv->device_version_lowest != NULL) {
		g_variant_builder_add (&builder, "{sv}",
				       FWUPD_RESULT_KEY_DEVICE_VERSION_LOWEST,
				       g_variant_new_string (priv->device_version_lowest));
	}

	/* supported types */
	if (g_strcmp0 (type_string, "{sa{sv}}") == 0)
		return g_variant_new ("{sa{sv}}", priv->device_id, &builder);
	if (g_strcmp0 (type_string, "(a{sv})") == 0)
		return g_variant_new ("(a{sv})", &builder);
	return NULL;
}