/** * g_cancellable_connect: * @cancellable: A #GCancellable. * @callback: The #GCallback to connect. * @data: Data to pass to @callback. * @data_destroy_func: (allow-none): Free function for @data or %NULL. * * Convenience function to connect to the #GCancellable::cancelled * signal. Also handles the race condition that may happen * if the cancellable is cancelled right before connecting. * * @callback is called at most once, either directly at the * time of the connect if @cancellable is already cancelled, * or when @cancellable is cancelled in some thread. * * @data_destroy_func will be called when the handler is * disconnected, or immediately if the cancellable is already * cancelled. * * See #GCancellable::cancelled for details on how to use this. * * Returns: The id of the signal handler or 0 if @cancellable has already * been cancelled. * * Since: 2.22 */ gulong g_cancellable_connect (GCancellable *cancellable, GCallback callback, gpointer data, GDestroyNotify data_destroy_func) { gulong id; g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0); g_mutex_lock (&cancellable_mutex); if (cancellable->priv->cancelled) { void (*_callback) (GCancellable *cancellable, gpointer user_data); _callback = (void *)callback; id = 0; _callback (cancellable, data); if (data_destroy_func) data_destroy_func (data); } else { id = g_signal_connect_data (cancellable, "cancelled", callback, data, (GClosureNotify) data_destroy_func, 0); } g_mutex_unlock (&cancellable_mutex); return id; }
static void ide_gettext_diagnostic_provider_diagnose_async (IdeDiagnosticProvider *provider, IdeFile *file, IdeBuffer *buffer, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { IdeGettextDiagnosticProvider *self = (IdeGettextDiagnosticProvider *)provider; g_autoptr(IdeUnsavedFile) unsaved_file = NULL; IdeGettextDiagnostics *cached; g_autoptr(GTask) task = NULL; g_return_if_fail (IDE_IS_GETTEXT_DIAGNOSTIC_PROVIDER (self)); g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable)); task = g_task_new (self, cancellable, callback, user_data); g_task_set_source_tag (task, ide_gettext_diagnostic_provider_diagnose_async); if (NULL != (cached = dzl_task_cache_peek (self->diagnostics_cache, file))) { unsaved_file = get_unsaved_file (self, file); if (unsaved_file == NULL || (cached->sequence >= ide_unsaved_file_get_sequence (unsaved_file))) { g_task_return_pointer (task, g_object_ref (cached), g_object_unref); return; } } dzl_task_cache_get_async (self->diagnostics_cache, file, TRUE, cancellable, get_diagnostics_cb, g_steal_pointer (&task)); }
/** * empathy_tp_file_accept: * @self: an incoming #EmpathyTpFile * @offset: the offset of @gfile where we should start writing * @gfile: the destination #GFile for the transfer * @cancellable: a #GCancellable * @progress_callback: function to callback with progress information * @progress_user_data: user_data to pass to @progress_callback * @op_callback: function to callback when the transfer ends * @op_user_data: user_data to pass to @op_callback * * Accepts an incoming file transfer, saving the result into @gfile. * The callback @op_callback will be called both when the transfer is * successful and in case of an error. Note that cancelling @cancellable, * closes the socket of the file operation in progress, but doesn't * guarantee that the transfer channel will be closed as well. Thus, * empathy_tp_file_cancel() or empathy_tp_file_close() should be used to * actually cancel an ongoing #EmpathyTpFile. */ void empathy_tp_file_accept (EmpathyTpFile *self, guint64 offset, GFile *gfile, GCancellable *cancellable, EmpathyTpFileProgressCallback progress_callback, gpointer progress_user_data, EmpathyTpFileOperationCallback op_callback, gpointer op_user_data) { g_return_if_fail (EMPATHY_IS_TP_FILE (self)); g_return_if_fail (G_IS_FILE (gfile)); g_return_if_fail (G_IS_CANCELLABLE (cancellable)); self->priv->cancellable = g_object_ref (cancellable); self->priv->progress_callback = progress_callback; self->priv->progress_user_data = progress_user_data; self->priv->op_callback = op_callback; self->priv->op_user_data = op_user_data; self->priv->offset = offset; g_file_replace_async (gfile, NULL, FALSE, G_FILE_CREATE_NONE, G_PRIORITY_DEFAULT, cancellable, file_replace_async_cb, self); }
gboolean gimp_output_stream_vprintf (GOutputStream *stream, gsize *bytes_written, GCancellable *cancellable, GError **error, const gchar *format, va_list args) { gchar *text; gboolean success; g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (stream), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_return_val_if_fail (format != NULL, FALSE); text = g_strdup_vprintf (format, args); success = g_output_stream_write_all (stream, text, strlen (text), bytes_written, cancellable, error); g_free (text); return success; }
void seahorse_progress_show_with_notice (GCancellable *cancellable, const gchar *title, const gchar *notice, gboolean delayed) { TrackedTask *task; g_return_if_fail (title != NULL && title[0] != '\0'); if (!cancellable) return; g_return_if_fail (G_IS_CANCELLABLE (cancellable)); task = progress_lookup_or_create_task (cancellable); /* Perhaps already cancelled? */ if (task == NULL) return; if (task->showing) { g_warning ("caller is trying to show progress for a task which already has displayed progress"); return; } g_free (task->title); task->title = g_strdup (title); task->notice = g_strdup (notice); task->showing = TRUE; if (delayed) g_timeout_add_seconds (2, on_timeout_show_progress, cancellable); else on_timeout_show_progress (cancellable); }
static void ide_autotools_build_system_get_local_makefile_async (IdeAutotoolsBuildSystem *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { IdeContext *context; g_autoptr(IdeConfiguration) configuration = NULL; g_autoptr(GTask) task = NULL; g_autoptr(IdeBuilder) builder = NULL; g_autoptr(GFile) build_directory = NULL; g_autoptr(GFile) makefile = NULL; GError *error = NULL; g_return_if_fail (IDE_IS_AUTOTOOLS_BUILD_SYSTEM (self)); g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable)); task = g_task_new (self, cancellable, callback, user_data); context = ide_object_get_context (IDE_OBJECT (self)); configuration = ide_configuration_new (context, "autotools-bootstrap", "local", "host"); builder = ide_autotools_build_system_get_builder (IDE_BUILD_SYSTEM (self), configuration, &error); if (builder == NULL) { g_task_return_error (task, error); return; } build_directory = ide_autotools_builder_get_build_directory (IDE_AUTOTOOLS_BUILDER (builder)); makefile = g_file_get_child (build_directory, "Makefile"); g_task_return_pointer (task, g_object_ref (makefile), g_object_unref); }
void ide_git_clone_widget_clone_async (IdeGitCloneWidget *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_autoptr(GTask) task = NULL; g_autoptr(GFile) location = NULL; g_autoptr(GFile) child = NULL; CloneRequest *req; const gchar *uri; const gchar *child_name; g_return_if_fail (IDE_IS_GIT_CLONE_WIDGET (self)); g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable)); gtk_label_set_label (self->clone_error_label, NULL); uri = gtk_entry_get_text (self->clone_uri_entry); child_name = gtk_entry_get_text (self->clone_location_entry); location = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (self->clone_location_button)); if (child_name != NULL) { child = g_file_get_child (location, child_name); req = clone_request_new (uri, child); } else { req = clone_request_new (uri, location); } task = g_task_new (self, cancellable, callback, user_data); g_task_set_task_data (task, req, clone_request_free); g_task_run_in_thread (task, ide_git_clone_widget_worker); }
static void gbp_git_buffer_addin_settle_async (IdeBufferAddin *addin, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GbpGitBufferAddin *self = (GbpGitBufferAddin *)addin; g_autoptr(IdeTask) task = NULL; g_assert (IDE_IS_MAIN_THREAD ()); g_assert (IDE_IS_BUFFER_ADDIN (self)); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); task = ide_task_new (self, cancellable, callback, user_data); ide_task_set_source_tag (task, gbp_git_buffer_addin_settle_async); if (self->monitor == NULL) ide_task_return_boolean (task, TRUE); else gbp_git_buffer_change_monitor_wait_async (GBP_GIT_BUFFER_CHANGE_MONITOR (self->monitor), cancellable, gbp_git_buffer_addin_settle_cb, g_steal_pointer (&task)); }
static void ide_rename_provider_real_rename_async (IdeRenameProvider *self, IdeSourceLocation *location, const gchar *new_name, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_autoptr(GTask) task = NULL; g_assert (IDE_IS_RENAME_PROVIDER (self)); g_assert (location != NULL); g_assert (new_name != NULL); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); task = g_task_new (self, cancellable, callback, user_data); g_task_set_source_tag (task, ide_rename_provider_real_rename_async); g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "%s has not implemented rename_async", G_OBJECT_TYPE_NAME (self)); }
/** * g_cancellable_release_fd: * @cancellable: a #GCancellable * * Releases a resources previously allocated by g_cancellable_get_fd() * or g_cancellable_make_pollfd(). * * For compatibility reasons with older releases, calling this function * is not strictly required, the resources will be automatically freed * when the @cancellable is finalized. However, the @cancellable will * block scarce file descriptors until it is finalized if this function * is not called. This can cause the application to run out of file * descriptors when many #GCancellables are used at the same time. * * Since: 2.22 **/ void g_cancellable_release_fd (GCancellable *cancellable) { GCancellablePrivate *priv; if (cancellable == NULL) return; g_return_if_fail (G_IS_CANCELLABLE (cancellable)); g_return_if_fail (cancellable->priv->fd_refcount > 0); priv = cancellable->priv; g_mutex_lock (&cancellable_mutex); priv->fd_refcount--; if (priv->fd_refcount == 0) { GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup); priv->wakeup = NULL; } g_mutex_unlock (&cancellable_mutex); }
void um_realm_login (UmRealmObject *realm, const gchar *user, const gchar *password, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GTask *task; LoginClosure *login; UmRealmKerberos *kerberos; g_return_if_fail (UM_REALM_IS_OBJECT (realm)); g_return_if_fail (user != NULL); g_return_if_fail (password != NULL); g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); kerberos = um_realm_object_get_kerberos (realm); g_return_if_fail (kerberos != NULL); task = g_task_new (realm, cancellable, callback, user_data); login = g_slice_new0 (LoginClosure); login->domain = g_strdup (um_realm_kerberos_get_domain_name (kerberos)); login->realm = g_strdup (um_realm_kerberos_get_realm_name (kerberos)); login->user = g_strdup (user); login->password = g_strdup (password); g_task_set_task_data (task, login, login_closure_free); g_task_set_check_cancellable (task, TRUE); g_task_set_return_on_cancel (task, TRUE); g_task_run_in_thread (task, kinit_thread_func); g_object_unref (task); g_object_unref (kerberos); }
static void jpeg_thumbnailer_create (TumblerAbstractThumbnailer *thumbnailer, GCancellable *cancellable, TumblerFileInfo *info) { TumblerThumbnailFlavor *flavor; TumblerImageData data; TumblerThumbnail *thumbnail; struct stat statb; const gchar *uri; GdkPixbuf *pixbuf = NULL; gboolean streaming_needed = TRUE; JOCTET *content; GError *error = NULL; GFile *file; gchar *path; gsize length; gint fd; gint height; gint width; gint size; g_return_if_fail (IS_JPEG_THUMBNAILER (thumbnailer)); g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); g_return_if_fail (TUMBLER_IS_FILE_INFO (info)); /* do nothing if cancelled */ if (g_cancellable_is_cancelled (cancellable)) return; uri = tumbler_file_info_get_uri (info); /* try to open the source file for reading */ file = g_file_new_for_uri (uri); thumbnail = tumbler_file_info_get_thumbnail (info); g_assert (thumbnail != NULL); flavor = tumbler_thumbnail_get_flavor (thumbnail); g_assert (flavor != NULL); tumbler_thumbnail_flavor_get_size (flavor, &width, &height); size = MIN (width, height); #ifdef HAVE_MMAP if (g_file_is_native (file)) { path = g_file_get_path (file); /* try to open the file at the given path */ fd = open (path, O_RDONLY); if (G_LIKELY (fd >= 0)) { /* determine the status of the file */ if (G_LIKELY (fstat (fd, &statb) == 0 && statb.st_size > 0)) { /* try to mmap the file */ content = (JOCTET *) mmap (NULL, statb.st_size, PROT_READ, MAP_SHARED, fd, 0); /* verify whether the mmap was successful */ if (G_LIKELY (content != (JOCTET *) MAP_FAILED)) { /* try to load the embedded thumbnail first */ pixbuf = tvtj_jpeg_load_thumbnail (content, statb.st_size, size); if (pixbuf == NULL) { /* fall back to loading and scaling the image itself */ pixbuf = tvtj_jpeg_load (content, statb.st_size, size); if (pixbuf == NULL) { g_set_error (&error, TUMBLER_ERROR, TUMBLER_ERROR_INVALID_FORMAT, _("Thumbnail could not be inferred from file contents")); } } /* we have successfully mmapped the file. we may not have * a thumbnail but trying to read the image from a stream * won't help us here, so we don't need to attempt streaming * as a fallback */ streaming_needed = FALSE; } /* unmap the file content */ munmap ((void *) content, statb.st_size); } /* close the file */ close (fd); } g_free (path); } #endif if (streaming_needed) { g_file_load_contents (file, cancellable, (gchar **)&content, &length, NULL, &error); if (error == NULL) { pixbuf = tvtj_jpeg_load_thumbnail (content, length, size); if (pixbuf == NULL) { pixbuf = tvtj_jpeg_load (content, length, size); if (pixbuf == NULL) { g_set_error (&error, TUMBLER_ERROR, TUMBLER_ERROR_INVALID_FORMAT, _("Thumbnail could not be inferred from file contents")); } } } } /* either we have an error now or we have a valid thumbnail pixbuf */ g_assert (error != NULL || pixbuf != NULL); if (pixbuf != NULL) { data.data = gdk_pixbuf_get_pixels (pixbuf); data.has_alpha = gdk_pixbuf_get_has_alpha (pixbuf); data.bits_per_sample = gdk_pixbuf_get_bits_per_sample (pixbuf); data.width = gdk_pixbuf_get_width (pixbuf); data.height = gdk_pixbuf_get_height (pixbuf); data.rowstride = gdk_pixbuf_get_rowstride (pixbuf); data.colorspace = (TumblerColorspace) gdk_pixbuf_get_colorspace (pixbuf); tumbler_thumbnail_save_image_data (thumbnail, &data, tumbler_file_info_get_mtime (info), NULL, &error); g_object_unref (pixbuf); } if (error != NULL) { g_signal_emit_by_name (thumbnailer, "error", uri, error->code, error->message); g_error_free (error); } else { g_signal_emit_by_name (thumbnailer, "ready", uri); } g_object_unref (flavor); g_object_unref (thumbnail); g_object_unref (file); }
gboolean xdg_cache_cache_read_thumbnail_info (const gchar *filename, gchar **uri, guint64 *mtime, GCancellable *cancellable, GError **error) { png_structp png_ptr; png_infop info_ptr; png_textp text_ptr; gboolean has_uri = FALSE; gboolean has_mtime = FALSE; FILE *png; gint num_text; gint i; g_return_val_if_fail (filename != NULL, FALSE); g_return_val_if_fail (uri != NULL, FALSE); g_return_val_if_fail (mtime != NULL, FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); *uri = NULL; *mtime = 0; if (g_cancellable_set_error_if_cancelled (cancellable, error)) return FALSE; if ((png = g_fopen (filename, "r")) != NULL) { /* initialize the PNG reader */ png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr) { /* initialize the info structure */ info_ptr = png_create_info_struct (png_ptr); if (info_ptr) { #ifdef PNG_SETJMP_SUPPORTED if (setjmp (png_jmpbuf (png_ptr))) { /* finalize the PNG reader */ png_destroy_read_struct (&png_ptr, &info_ptr, NULL); /* close the PNG file handle */ fclose (png); return FALSE; } #endif /* initialize reading from the file and read the file info */ png_init_io (png_ptr, png); png_read_info (png_ptr, info_ptr); /* check if there is embedded text information */ if (png_get_text (png_ptr, info_ptr, &text_ptr, &num_text) > 0) { /* iterate over all text keys */ for (i = 0; !(has_uri && has_mtime) && i < num_text; ++i) { if (!text_ptr[i].key) continue; if (strcmp ("Thumb::URI", text_ptr[i].key) == 0) { /* remember the Thumb::URI value */ *uri = g_strdup (text_ptr[i].text); has_uri = TRUE; } else if (strcmp ("Thumb::MTime", text_ptr[i].key) == 0) { /* remember the Thumb::MTime value */ if (text_ptr[i].text != NULL) { *mtime = atol (text_ptr[i].text); has_mtime = TRUE; } } } } } /* finalize the PNG reader */ png_destroy_read_struct (&png_ptr, &info_ptr, NULL); } /* close the PNG file handle */ fclose (png); } return TRUE; }
static void ide_build_system_real_get_build_flags_async (IdeBuildSystem *self, GFile *file, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_autoptr(IdeContext) context = NULL; g_autoptr(IdeTask) task = NULL; g_autoptr(GError) error = NULL; g_auto(GStrv) parsed_flags = NULL; IdeBuildManager *build_manager; IdeEnvironment *env; const gchar *flags = NULL; const gchar *path; IdePipeline *pipeline; IdeConfig *config; g_assert (IDE_IS_MAIN_THREAD ()); g_assert (IDE_IS_BUILD_SYSTEM (self)); g_assert (G_IS_FILE (file)); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); task = ide_task_new (self, cancellable, callback, user_data); ide_task_set_source_tag (task, ide_build_system_real_get_build_flags_async); /* Avoid work immediately if we can */ if (ide_task_return_error_if_cancelled (task)) return; if (!g_file_is_native (file) || !(path = g_file_peek_path (file))) { ide_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Cannot get build flags for non-native file"); return; } if (!(context = ide_object_ref_context (IDE_OBJECT (self))) || !ide_context_has_project (context) || !(build_manager = ide_build_manager_from_context (context)) || !(pipeline = ide_build_manager_get_pipeline (build_manager)) || !(config = ide_pipeline_get_config (pipeline)) || !(env = ide_config_get_environment (config))) { ide_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED, "Cannot access build flags without build config"); return; } if (ide_path_is_cpp_like (path)) { flags = ide_environment_getenv (env, "CXXFLAGS"); } else if (ide_path_is_c_like (path)) { if (!(flags = ide_environment_getenv (env, "CFLAGS"))) flags = ide_environment_getenv (env, "CXXFLAGS"); } else { ide_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Cannot extract build flags for unknown file type: \"%s\"", path); return; } if (flags == NULL) { ide_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "No CFLAGS or CXXFLAGS environment variables were specified"); return; } if (!g_shell_parse_argv (flags, NULL, &parsed_flags, &error)) ide_task_return_error (task, g_steal_pointer (&error)); else ide_task_return_pointer (task, g_steal_pointer (&parsed_flags), g_strfreev); }
/** * gvir_storage_pool_refresh: * @pool: the storage pool * @cancellable: (allow-none)(transfer none): cancellation object */ gboolean gvir_storage_pool_refresh(GVirStoragePool *pool, GCancellable *cancellable, GError **err) { GVirStoragePoolPrivate *priv; GHashTable *vol_hash; gchar **volumes = NULL; gint nvolumes = 0; gboolean ret = FALSE; gint i; virStoragePoolPtr vpool = NULL; GError *lerr = NULL; g_return_val_if_fail(GVIR_IS_STORAGE_POOL(pool), FALSE); g_return_val_if_fail((cancellable == NULL) || G_IS_CANCELLABLE(cancellable), FALSE); g_return_val_if_fail(err == NULL || *err == NULL, FALSE); priv = pool->priv; vpool = priv->handle; if (virStoragePoolRefresh(vpool, 0) < 0) { gvir_set_error_literal(err, GVIR_STORAGE_POOL_ERROR, 0, "Unable to refresh storage pool"); goto cleanup; } volumes = fetch_list(vpool, "Storage Volumes", virStoragePoolNumOfVolumes, virStoragePoolListVolumes, cancellable, &nvolumes, &lerr); if (lerr) { g_propagate_error(err, lerr); lerr = NULL; goto cleanup; } if (g_cancellable_set_error_if_cancelled(cancellable, err)) goto cleanup; vol_hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_object_unref); for (i = 0 ; i < nvolumes ; i++) { if (g_cancellable_set_error_if_cancelled(cancellable, err)) goto cleanup; virStorageVolPtr vvolume; GVirStorageVol *volume; vvolume = virStorageVolLookupByName(vpool, volumes[i]); if (!vvolume) continue; volume = GVIR_STORAGE_VOL(g_object_new(GVIR_TYPE_STORAGE_VOL, "handle", vvolume, "pool", pool, NULL)); virStorageVolFree(vvolume); g_hash_table_insert(vol_hash, g_strdup(volumes[i]), volume); } g_mutex_lock(priv->lock); if (priv->volumes) g_hash_table_unref(priv->volumes); priv->volumes = vol_hash; g_mutex_unlock(priv->lock); ret = TRUE; cleanup: for (i = 0 ; i < nvolumes ; i++) g_free(volumes[i]); g_free(volumes); return ret; }
void mongo_cursor_foreach_async (MongoCursor *cursor, MongoCursorCallback foreach_func, gpointer foreach_data, GDestroyNotify foreach_notify, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { MongoCursorPrivate *priv; GSimpleAsyncResult *simple; gchar *db_and_collection; ENTRY; g_return_if_fail(MONGO_IS_CURSOR(cursor)); g_return_if_fail(foreach_func); g_return_if_fail(!cancellable || G_IS_CANCELLABLE(cancellable)); g_return_if_fail(callback); priv = cursor->priv; if (!priv->connection) { g_simple_async_report_error_in_idle(G_OBJECT(cursor), callback, user_data, MONGO_CONNECTION_ERROR, MONGO_CONNECTION_ERROR_NOT_CONNECTED, _("Not currently connected.")); GOTO(failure); } simple = g_simple_async_result_new(G_OBJECT(cursor), callback, user_data, mongo_cursor_foreach_async); g_simple_async_result_set_check_cancellable(simple, cancellable); if (cancellable) { g_object_set_data_full(G_OBJECT(simple), "cancellable", cancellable, (GDestroyNotify)g_object_unref); } g_object_set_data(G_OBJECT(simple), "foreach-func", foreach_func); if (foreach_notify) { g_object_set_data_full(G_OBJECT(simple), "foreach-data", foreach_data, foreach_notify); } else { g_object_set_data(G_OBJECT(simple), "foreach-data", foreach_data); } db_and_collection = g_strdup_printf("%s.%s", priv->database, priv->collection); mongo_connection_query_async(priv->connection, db_and_collection, priv->flags, priv->skip, priv->limit, priv->query, priv->fields, cancellable, mongo_cursor_foreach_query_cb, simple); g_free(db_and_collection); failure: EXIT; }
/** * secret_prompt_perform: * @self: a prompt * @window_id: XWindow id for parent window to be transient for * @return_type: the variant type of the prompt result * @cancellable: optional cancellation object * @callback: called when the operation completes * @user_data: data to be passed to the callback * * Runs a prompt and performs the prompting. Returns %TRUE if the prompt * was completed and not dismissed. * * If @window_id is non-zero then it is used as an XWindow id. The Secret * Service can make its prompt transient for the window with this id. In some * Secret Service implementations this is not possible, so the behavior * depending on this should degrade gracefully. * * This method will return immediately and complete asynchronously. */ void secret_prompt_perform (SecretPrompt *self, gulong window_id, const GVariantType *return_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; PerformClosure *closure; const gchar *owner_name; const gchar *object_path; gboolean prompted; GDBusProxy *proxy; gchar *window; g_return_if_fail (SECRET_IS_PROMPT (self)); g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); prompted = g_atomic_int_get (&self->pv->prompted); if (prompted) { g_warning ("The prompt object has already had its prompt called."); return; } proxy = G_DBUS_PROXY (self); res = g_simple_async_result_new (G_OBJECT (self), callback, user_data, secret_prompt_perform); closure = g_slice_new0 (PerformClosure); closure->connection = g_object_ref (g_dbus_proxy_get_connection (proxy)); closure->call_cancellable = g_cancellable_new (); closure->async_cancellable = cancellable ? g_object_ref (cancellable) : NULL; closure->return_type = return_type ? g_variant_type_copy (return_type) : NULL; g_simple_async_result_set_op_res_gpointer (res, closure, perform_closure_free); if (window_id == 0) window = g_strdup (""); else window = g_strdup_printf ("%lu", window_id); owner_name = g_dbus_proxy_get_name_owner (proxy); object_path = g_dbus_proxy_get_object_path (proxy); closure->signal = g_dbus_connection_signal_subscribe (closure->connection, owner_name, SECRET_PROMPT_INTERFACE, SECRET_PROMPT_SIGNAL_COMPLETED, object_path, NULL, G_DBUS_SIGNAL_FLAGS_NONE, on_prompt_completed, g_object_ref (res), g_object_unref); closure->watch = g_bus_watch_name_on_connection (closure->connection, owner_name, G_BUS_NAME_WATCHER_FLAGS_NONE, NULL, on_prompt_vanished, g_object_ref (res), g_object_unref); if (closure->async_cancellable) { closure->cancelled_sig = g_cancellable_connect (closure->async_cancellable, G_CALLBACK (on_prompt_cancelled), res, NULL); } g_dbus_proxy_call (proxy, "Prompt", g_variant_new ("(s)", window), G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, closure->call_cancellable, on_prompt_prompted, g_object_ref (res)); g_free (window); g_object_unref (res); }
static void gbp_cmake_toolchain_provider_load_worker (IdeTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { GbpCMakeToolchainProvider *self = source_object; g_autoptr(GPtrArray) toolchains = NULL; IdeContext *context; GPtrArray *files = task_data; g_assert (IDE_IS_TASK (task)); g_assert (GBP_IS_CMAKE_TOOLCHAIN_PROVIDER (self)); g_assert (files != NULL); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); context = ide_object_get_context (IDE_OBJECT (self)); toolchains = g_ptr_array_new_with_free_func (g_object_unref); for (guint i = 0; i < files->len; i++) { GFile *file = g_ptr_array_index (files, i); g_autofree gchar *name = NULL; g_autoptr(GError) file_error = NULL; g_autofree gchar *file_path = NULL; g_autofree gchar *file_contents = NULL; gsize file_contents_len; g_assert (G_IS_FILE (file)); name = g_file_get_basename (file); file_path = g_file_get_path (file); /* Cross-compilation files have .cmake extension, we have to blacklist CMakeSystem.cmake * in case we are looking into a build folder */ if (g_strcmp0 (name, "CMakeSystem.cmake") == 0) continue; /* Cross-compilation files should at least define CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR */ if (g_file_get_contents (file_path, &file_contents, &file_contents_len, &file_error)) { g_autoptr(GbpCMakeToolchain) toolchain = NULL; g_autoptr(GError) load_error = NULL; const gchar *processor_name; const gchar *system_name; system_name = g_strstr_len (file_contents, file_contents_len, "CMAKE_SYSTEM_NAME"); if (system_name == NULL) continue; processor_name = g_strstr_len (file_contents, file_contents_len, "CMAKE_SYSTEM_PROCESSOR"); if (processor_name == NULL) continue; toolchain = gbp_cmake_toolchain_new (context); ide_object_append (IDE_OBJECT (self), IDE_OBJECT (toolchain)); if (!gbp_cmake_toolchain_load (toolchain, file, cancellable, &load_error)) { g_debug ("Error loading %s : %s", file_path, load_error->message); ide_clear_and_destroy_object (&toolchain); continue; } g_ptr_array_add (toolchains, g_steal_pointer (&toolchain)); } } ide_task_return_pointer (task, g_steal_pointer (&toolchains), g_ptr_array_unref); }
gboolean goa_utils_store_credentials_for_id_sync (GoaProvider *provider, const gchar *id, GVariant *credentials, GCancellable *cancellable, GError **error) { gboolean ret; gchar *credentials_str; gchar *password_description; gchar *password_key; GError *sec_error = NULL; g_return_val_if_fail (GOA_IS_PROVIDER (provider), FALSE); g_return_val_if_fail (id != NULL && id[0] != '\0', FALSE); g_return_val_if_fail (credentials != NULL, FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); ret = FALSE; credentials_str = g_variant_print (credentials, TRUE); g_variant_ref_sink (credentials); g_variant_unref (credentials); password_key = g_strdup_printf ("%s:gen%d:%s", goa_provider_get_provider_type (GOA_PROVIDER (provider)), goa_provider_get_credentials_generation (GOA_PROVIDER (provider)), id); /* Translators: The %s is the type of the provider, e.g. 'google' or 'yahoo' */ password_description = g_strdup_printf (_("GOA %s credentials for identity %s"), goa_provider_get_provider_type (GOA_PROVIDER (provider)), id); if (!secret_password_store_sync (&secret_password_schema, SECRET_COLLECTION_DEFAULT, /* default keyring */ password_description, credentials_str, cancellable, &sec_error, "goa-identity", password_key, NULL)) { g_warning ("secret_password_store_sync() failed: %s", sec_error->message); g_set_error_literal (error, GOA_ERROR, GOA_ERROR_FAILED, /* TODO: more specific */ _("Failed to store credentials in the keyring")); g_error_free (sec_error); goto out; } g_debug ("Stored keyring credentials for identity: %s", id); ret = TRUE; out: g_free (credentials_str); g_free (password_key); g_free (password_description); return ret; }
GVariant * goa_utils_lookup_credentials_sync (GoaProvider *provider, GoaObject *object, GCancellable *cancellable, GError **error) { gchar *password_key; GVariant *ret; gchar *password; const gchar *id; GError *sec_error = NULL; g_return_val_if_fail (GOA_IS_PROVIDER (provider), NULL); g_return_val_if_fail (GOA_IS_OBJECT (object) && goa_object_peek_account (object) != NULL, FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); g_return_val_if_fail (error == NULL || *error == NULL, NULL); ret = NULL; password_key = NULL; password = NULL; id = goa_account_get_id (goa_object_peek_account (object)); password_key = g_strdup_printf ("%s:gen%d:%s", goa_provider_get_provider_type (GOA_PROVIDER (provider)), goa_provider_get_credentials_generation (GOA_PROVIDER (provider)), id); password = secret_password_lookup_sync (&secret_password_schema, cancellable, &sec_error, "goa-identity", password_key, NULL); if (sec_error != NULL) { g_warning ("secret_password_lookup_sync() failed: %s", sec_error->message); g_set_error_literal (error, GOA_ERROR, GOA_ERROR_FAILED, /* TODO: more specific */ _("Failed to retrieve credentials from the keyring")); g_error_free (sec_error); goto out; } else if (password == NULL) { g_warning ("secret_password_lookup_sync() returned NULL"); g_set_error_literal (error, GOA_ERROR, GOA_ERROR_FAILED, /* TODO: more specific */ _("No credentials found in the keyring")); goto out; } g_debug ("Retrieved keyring credentials for id: %s", id); ret = g_variant_parse (NULL, /* GVariantType */ password, NULL, /* limit */ NULL, /* endptr */ error); if (ret == NULL) { g_prefix_error (error, _("Error parsing result obtained from the keyring: ")); goto out; } if (g_variant_is_floating (ret)) g_variant_ref_sink (ret); out: g_free (password); g_free (password_key); return ret; }
void e_mail_session_send_to (EMailSession *session, CamelMimeMessage *message, gint io_priority, GCancellable *cancellable, CamelFilterGetFolderFunc get_folder_func, gpointer get_folder_data, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *simple; AsyncContext *context; CamelAddress *from; CamelAddress *recipients; CamelMedium *medium; CamelMessageInfo *info; EAccount *account = NULL; GPtrArray *post_to_uris; struct _camel_header_raw *xev; struct _camel_header_raw *header; const gchar *string; const gchar *resent_from; gchar *transport_uid = NULL; gchar *sent_folder_uri = NULL; GError *error = NULL; g_return_if_fail (E_IS_MAIL_SESSION (session)); g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message)); medium = CAMEL_MEDIUM (message); camel_medium_set_header (medium, "X-Mailer", X_MAILER); xev = mail_tool_remove_xevolution_headers (message); /* Extract directives from X-Evolution headers. */ string = camel_header_raw_find (&xev, "X-Evolution-Account", NULL); if (string != NULL) { gchar *account_uid; account_uid = g_strstrip (g_strdup (string)); account = e_get_account_by_uid (account_uid); g_free (account_uid); } if (account != NULL) { if (account->transport != NULL) { /* XXX Transport UIDs are kludgy right now. We * use the EAccount's regular UID and tack on * "-transport". Will be better soon. */ transport_uid = g_strconcat ( account->uid, "-transport", NULL); /* to reprompt password on sending if needed */ account->transport->get_password_canceled = FALSE; } sent_folder_uri = g_strdup (account->sent_folder_uri); } string = camel_header_raw_find (&xev, "X-Evolution-Fcc", NULL); if (sent_folder_uri == NULL && string != NULL) sent_folder_uri = g_strstrip (g_strdup (string)); string = camel_header_raw_find (&xev, "X-Evolution-Transport", NULL); if (transport_uid == NULL && string != NULL) transport_uid = g_strstrip (g_strdup (string)); post_to_uris = g_ptr_array_new (); for (header = xev; header != NULL; header = header->next) { gchar *folder_uri; if (g_strcmp0 (header->name, "X-Evolution-PostTo") != 0) continue; folder_uri = g_strstrip (g_strdup (header->value)); g_ptr_array_add (post_to_uris, folder_uri); } /* Collect sender and recipients from headers. */ from = (CamelAddress *) camel_internet_address_new (); recipients = (CamelAddress *) camel_internet_address_new (); resent_from = camel_medium_get_header (medium, "Resent-From"); if (resent_from != NULL) { const CamelInternetAddress *addr; const gchar *type; camel_address_decode (from, resent_from); type = CAMEL_RECIPIENT_TYPE_RESENT_TO; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_RESENT_CC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_RESENT_BCC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); } else { const CamelInternetAddress *addr; const gchar *type; addr = camel_mime_message_get_from (message); camel_address_copy (from, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_TO; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_CC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_BCC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); } /* Miscellaneous preparations. */ info = camel_message_info_new (NULL); camel_message_info_set_flags (info, CAMEL_MESSAGE_SEEN, ~0); /* The rest of the processing happens in a thread. */ context = g_slice_new0 (AsyncContext); context->message = g_object_ref (message); context->io_priority = io_priority; context->from = from; context->recipients = recipients; context->message = g_object_ref (message); context->info = info; context->xev = xev; context->post_to_uris = post_to_uris; context->transport_uid = transport_uid; context->sent_folder_uri = sent_folder_uri; if (G_IS_CANCELLABLE (cancellable)) context->cancellable = g_object_ref (cancellable); /* Failure here emits a runtime warning but is non-fatal. */ context->driver = camel_session_get_filter_driver ( CAMEL_SESSION (session), E_FILTER_SOURCE_OUTGOING, &error); if (context->driver != NULL && get_folder_func) camel_filter_driver_set_folder_func ( context->driver, get_folder_func, get_folder_data); if (error != NULL) { g_warn_if_fail (context->driver == NULL); g_warning ("%s", error->message); g_error_free (error); } /* This gets popped in async_context_free(). */ camel_operation_push_message ( context->cancellable, _("Sending message")); simple = g_simple_async_result_new ( G_OBJECT (session), callback, user_data, e_mail_session_send_to); g_simple_async_result_set_op_res_gpointer ( simple, context, (GDestroyNotify) async_context_free); g_simple_async_result_run_in_thread ( simple, (GSimpleAsyncThreadFunc) mail_session_send_to_thread, context->io_priority, context->cancellable); g_object_unref (simple); }
/** * gcr_importer_import: * @importer: the importer * @cancellable: a #GCancellable, or %NULL * @error: the location to place an error on failure, or %NULL * * Import the queued items in the importer. This call will block * until the operation completes. * * Returns: whether the items were imported successfully or not */ gboolean gcr_importer_import (GcrImporter *importer, GCancellable *cancellable, GError **error) { gboolean result; ImportClosure *closure; GcrImporterIface *iface; g_return_val_if_fail (GCR_IS_IMPORTER (importer), FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); iface = GCR_IMPORTER_GET_INTERFACE (importer); if (iface->import_sync) return (iface->import_sync) (importer, cancellable, error); g_return_val_if_fail (iface->import_async != NULL, FALSE); g_return_val_if_fail (iface->import_finish != NULL, FALSE); closure = g_new0 (ImportClosure, 1); closure->cond = g_new (GCond, 1); g_cond_init (closure->cond); closure->mutex = g_new (GMutex, 1); g_mutex_init (closure->mutex); closure->context = g_main_context_get_thread_default (); g_mutex_lock (closure->mutex); (iface->import_async) (importer, cancellable, on_import_async_complete, closure); /* * Handle the case where we've been called from within the main context * or in the case where the main context is not running. This approximates * the behavior of a modal dialog. */ if (g_main_context_acquire (closure->context)) { while (!closure->complete) { g_mutex_unlock (closure->mutex); g_main_context_iteration (closure->context, TRUE); g_mutex_lock (closure->mutex); } g_main_context_release (closure->context); /* * Handle the case where we're in a different thread than the main * context and a main loop is running. */ } else { while (!closure->complete) g_cond_wait (closure->cond, closure->mutex); } g_mutex_unlock (closure->mutex); result = (closure->error == NULL); if (closure->error) g_propagate_error (error, closure->error); g_cond_clear (closure->cond); g_free (closure->cond); g_mutex_clear (closure->mutex); g_free (closure->mutex); g_free (closure); return result; }
void e_mail_session_send_to (EMailSession *session, CamelMimeMessage *message, gint io_priority, GCancellable *cancellable, CamelFilterGetFolderFunc get_folder_func, gpointer get_folder_data, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *simple; AsyncContext *context; CamelAddress *from; CamelAddress *recipients; CamelMedium *medium; CamelMessageInfo *info; CamelService *transport; GPtrArray *post_to_uris; struct _camel_header_raw *xev; struct _camel_header_raw *header; const gchar *resent_from; GError *error = NULL; g_return_if_fail (E_IS_MAIL_SESSION (session)); g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message)); medium = CAMEL_MEDIUM (message); camel_medium_set_header (medium, "X-Mailer", X_MAILER); /* Do this before removing "X-Evolution" headers. */ transport = e_mail_session_ref_transport_for_message ( session, message); xev = mail_tool_remove_xevolution_headers (message); /* Extract directives from X-Evolution headers. */ post_to_uris = g_ptr_array_new (); for (header = xev; header != NULL; header = header->next) { gchar *folder_uri; if (g_strcmp0 (header->name, "X-Evolution-PostTo") != 0) continue; folder_uri = g_strstrip (g_strdup (header->value)); g_ptr_array_add (post_to_uris, folder_uri); } /* Collect sender and recipients from headers. */ from = (CamelAddress *) camel_internet_address_new (); recipients = (CamelAddress *) camel_internet_address_new (); resent_from = camel_medium_get_header (medium, "Resent-From"); if (resent_from != NULL) { const CamelInternetAddress *addr; const gchar *type; camel_address_decode (from, resent_from); type = CAMEL_RECIPIENT_TYPE_RESENT_TO; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_RESENT_CC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_RESENT_BCC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); } else { const CamelInternetAddress *addr; const gchar *type; addr = camel_mime_message_get_from (message); camel_address_copy (from, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_TO; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_CC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); type = CAMEL_RECIPIENT_TYPE_BCC; addr = camel_mime_message_get_recipients (message, type); camel_address_cat (recipients, CAMEL_ADDRESS (addr)); } /* Miscellaneous preparations. */ info = camel_message_info_new_from_header ( NULL, CAMEL_MIME_PART (message)->headers); ((CamelMessageInfoBase *) info)->size = get_message_size (message, cancellable); camel_message_info_set_flags (info, CAMEL_MESSAGE_SEEN, ~0); /* expand, or remove empty, group addresses */ em_utils_expand_groups (CAMEL_INTERNET_ADDRESS (recipients)); /* The rest of the processing happens in a thread. */ context = g_slice_new0 (AsyncContext); context->message = g_object_ref (message); context->io_priority = io_priority; context->from = from; context->recipients = recipients; context->info = info; context->xev = xev; context->post_to_uris = post_to_uris; context->transport = transport; if (G_IS_CANCELLABLE (cancellable)) context->cancellable = g_object_ref (cancellable); /* Failure here emits a runtime warning but is non-fatal. */ context->driver = camel_session_get_filter_driver ( CAMEL_SESSION (session), E_FILTER_SOURCE_OUTGOING, &error); if (context->driver != NULL && get_folder_func) camel_filter_driver_set_folder_func ( context->driver, get_folder_func, get_folder_data); if (error != NULL) { g_warn_if_fail (context->driver == NULL); g_warning ("%s", error->message); g_error_free (error); } /* This gets popped in async_context_free(). */ camel_operation_push_message ( context->cancellable, _("Sending message")); simple = g_simple_async_result_new ( G_OBJECT (session), callback, user_data, e_mail_session_send_to); g_simple_async_result_set_check_cancellable (simple, cancellable); g_simple_async_result_set_op_res_gpointer ( simple, context, (GDestroyNotify) async_context_free); g_simple_async_result_run_in_thread ( simple, (GSimpleAsyncThreadFunc) mail_session_send_to_thread, context->io_priority, context->cancellable); g_object_unref (simple); }
/** * fwupd_remote_load_from_filename: * @self: A #FwupdRemote * @filename: A filename * @cancellable: the #GCancellable, or %NULL * @error: the #GError, or %NULL * * Sets up the remote ready for use. Most other methods call this * for you, and do you only need to call this if you are just watching * the self. * * Returns: %TRUE for success * * Since: 0.9.3 **/ gboolean fwupd_remote_load_from_filename (FwupdRemote *self, const gchar *filename, GCancellable *cancellable, GError **error) { FwupdRemotePrivate *priv = GET_PRIVATE (self); const gchar *group = "fwupd Remote"; g_autofree gchar *firmware_base_uri = NULL; g_autofree gchar *id = NULL; g_autofree gchar *keyring_kind = NULL; g_autofree gchar *metadata_uri = NULL; g_autofree gchar *order_after = NULL; g_autofree gchar *order_before = NULL; g_autofree gchar *report_uri = NULL; g_autoptr(GKeyFile) kf = NULL; g_return_val_if_fail (FWUPD_IS_REMOTE (self), FALSE); g_return_val_if_fail (filename != NULL, FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); /* set ID */ id = g_path_get_basename (filename); fwupd_remote_set_id (self, id); /* load file */ kf = g_key_file_new (); if (!g_key_file_load_from_file (kf, filename, G_KEY_FILE_NONE, error)) return FALSE; /* get verification type, falling back to GPG */ keyring_kind = g_key_file_get_string (kf, group, "Keyring", NULL); if (keyring_kind == NULL) { priv->keyring_kind = FWUPD_KEYRING_KIND_GPG; } else { priv->keyring_kind = fwupd_keyring_kind_from_string (keyring_kind); if (priv->keyring_kind == FWUPD_KEYRING_KIND_UNKNOWN) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse type '%s'", keyring_kind); return FALSE; } } /* all remotes need a URI, even if it's file:// to the cache */ metadata_uri = g_key_file_get_string (kf, group, "MetadataURI", error); if (metadata_uri == NULL) return FALSE; if (g_str_has_prefix (metadata_uri, "file://")) { const gchar *filename_cache = metadata_uri; if (g_str_has_prefix (filename_cache, "file://")) filename_cache += 7; fwupd_remote_set_filename_cache (self, filename_cache); if (g_file_test (filename_cache, G_FILE_TEST_IS_DIR)) priv->kind = FWUPD_REMOTE_KIND_DIRECTORY; else priv->kind = FWUPD_REMOTE_KIND_LOCAL; } else if (g_str_has_prefix (metadata_uri, "http://") || g_str_has_prefix (metadata_uri, "https://")) { priv->kind = FWUPD_REMOTE_KIND_DOWNLOAD; } else { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse MetadataURI type '%s'", metadata_uri); return FALSE; } /* extract data */ priv->enabled = g_key_file_get_boolean (kf, group, "Enabled", NULL); priv->approval_required = g_key_file_get_boolean (kf, group, "ApprovalRequired", NULL); priv->title = g_key_file_get_string (kf, group, "Title", NULL); /* reporting is optional */ report_uri = g_key_file_get_string (kf, group, "ReportURI", NULL); if (report_uri != NULL && report_uri[0] != '\0') fwupd_remote_set_report_uri (self, report_uri); /* DOWNLOAD-type remotes */ if (priv->kind == FWUPD_REMOTE_KIND_DOWNLOAD) { g_autofree gchar *filename_cache = NULL; g_autofree gchar *username = NULL; g_autofree gchar *password = NULL; /* the client has to download this and the signature */ fwupd_remote_set_metadata_uri (self, metadata_uri); /* check the URI was valid */ if (priv->metadata_uri == NULL) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse URI '%s' in %s", metadata_uri, filename); return FALSE; } /* username and password are optional */ username = g_key_file_get_string (kf, group, "Username", NULL); if (username != NULL) fwupd_remote_set_username (self, username); password = g_key_file_get_string (kf, group, "Password", NULL); if (password != NULL) fwupd_remote_set_password (self, password); /* set cache to /var/lib... */ filename_cache = g_build_filename (LOCALSTATEDIR, "lib", "fwupd", "remotes.d", priv->id, "metadata.xml.gz", NULL); fwupd_remote_set_filename_cache (self, filename_cache); } /* load the checksum */ if (priv->filename_cache_sig != NULL && g_file_test (priv->filename_cache_sig, G_FILE_TEST_EXISTS)) { gsize sz = 0; g_autofree gchar *buf = NULL; g_autoptr(GChecksum) checksum = g_checksum_new (G_CHECKSUM_SHA256); if (!g_file_get_contents (priv->filename_cache_sig, &buf, &sz, error)) { g_prefix_error (error, "failed to get checksum: "); return FALSE; } g_checksum_update (checksum, (guchar *) buf, (gssize) sz); fwupd_remote_set_checksum (self, g_checksum_get_string (checksum)); } else { fwupd_remote_set_checksum (self, NULL); } /* the base URI is optional */ firmware_base_uri = g_key_file_get_string (kf, group, "FirmwareBaseURI", NULL); if (firmware_base_uri != NULL) fwupd_remote_set_firmware_base_uri (self, firmware_base_uri); /* some validation around DIRECTORY types */ if (priv->kind == FWUPD_REMOTE_KIND_DIRECTORY) { if (priv->keyring_kind != FWUPD_KEYRING_KIND_NONE) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Keyring kind %s is not supported with directory remote", fwupd_keyring_kind_to_string (priv->keyring_kind)); return FALSE; } if (firmware_base_uri != NULL) { g_set_error_literal (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Directory remotes don't support firmware base URI"); return FALSE; } } /* dep logic */ order_before = g_key_file_get_string (kf, group, "OrderBefore", NULL); if (order_before != NULL) priv->order_before = g_strsplit_set (order_before, ",:;", -1); order_after = g_key_file_get_string (kf, group, "OrderAfter", NULL); if (order_after != NULL) priv->order_after = g_strsplit_set (order_after, ",:;", -1); /* success */ fwupd_remote_set_filename_source (self, filename); return TRUE; }
static void ide_lsp_formatter_format_range_async (IdeFormatter *formatter, IdeBuffer *buffer, IdeFormatterOptions *options, const GtkTextIter *begin, const GtkTextIter *end, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { IdeLspFormatter *self = (IdeLspFormatter *)formatter; IdeLspFormatterPrivate *priv = ide_lsp_formatter_get_instance_private (self); g_autoptr(GVariant) params = NULL; g_autoptr(IdeTask) task = NULL; g_autofree gchar *uri = NULL; g_autofree gchar *text = NULL; gint64 version; gint tab_size; gboolean insert_spaces; struct { gint line; gint character; } b, e; g_assert (IDE_IS_LSP_FORMATTER (self)); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); task = ide_task_new (self, cancellable, callback, user_data); ide_task_set_source_tag (task, ide_lsp_formatter_format_async); ide_task_set_task_data (task, g_object_ref (buffer), g_object_unref); if (gtk_text_iter_compare (begin, end) > 0) { const GtkTextIter *tmp = end; end = begin; begin = tmp; } version = ide_buffer_get_change_count (buffer); uri = ide_buffer_dup_uri (buffer); text = gtk_text_buffer_get_text (GTK_TEXT_BUFFER (buffer), begin, end, TRUE); tab_size = ide_formatter_options_get_tab_width (options); insert_spaces = ide_formatter_options_get_insert_spaces (options); b.line = gtk_text_iter_get_line (begin); b.character = gtk_text_iter_get_line_offset (begin); e.line = gtk_text_iter_get_line (end); e.character = gtk_text_iter_get_line_offset (begin); params = JSONRPC_MESSAGE_NEW ( "textDocument", "{", "uri", JSONRPC_MESSAGE_PUT_STRING (uri), "text", JSONRPC_MESSAGE_PUT_STRING (text), "version", JSONRPC_MESSAGE_PUT_INT64 (version), "}", "options", "{", "tabSize", JSONRPC_MESSAGE_PUT_INT32 (tab_size), "insertSpaces", JSONRPC_MESSAGE_PUT_BOOLEAN (insert_spaces), "}", "range", "{", "start", "{", "line", JSONRPC_MESSAGE_PUT_INT32 (b.line), "character", JSONRPC_MESSAGE_PUT_INT32 (b.character), "}", "end", "{", "line", JSONRPC_MESSAGE_PUT_INT32 (e.line), "character", JSONRPC_MESSAGE_PUT_INT32 (e.character), "}", "}" ); ide_lsp_client_call_async (priv->client, "textDocument/rangeFormatting", params, cancellable, ide_lsp_formatter_format_call_cb, g_steal_pointer (&task)); }
static void ide_file_find_other_worker (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { IdeFile *self = source_object; const gchar *src_suffixes[] = { "c", "cc", "cpp", "cxx", NULL }; const gchar *hdr_suffixes[] = { "h", "hh", "hpp", "hxx", NULL }; const gchar **target = NULL; g_autofree gchar *prefix = NULL; g_autofree gchar *uri = NULL; gsize i; g_assert (IDE_IS_FILE (self)); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); uri = g_file_get_uri (self->file); if (has_suffix (uri, src_suffixes)) { target = hdr_suffixes; } else if (has_suffix (uri, hdr_suffixes)) { target = src_suffixes; } else { g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME, "File is missing a suffix."); return; } prefix = g_strndup (uri, strrchr (uri, '.') - uri); for (i = 0; target [i]; i++) { g_autofree gchar *new_uri = NULL; g_autoptr(GFile) gfile = NULL; new_uri = g_strdup_printf ("%s.%s", prefix, target [i]); gfile = g_file_new_for_uri (new_uri); if (g_file_query_exists (gfile, cancellable)) { g_autofree gchar *path = NULL; IdeContext *context; IdeVcs *vcs; IdeFile *ret; GFile *workdir; context = ide_object_get_context (IDE_OBJECT (self)); vcs = ide_context_get_vcs (context); workdir = ide_vcs_get_working_directory (vcs); path = g_file_get_relative_path (workdir, gfile); ret = g_object_new (IDE_TYPE_FILE, "context", context, "path", path, "file", gfile, NULL); g_task_return_pointer (task, ret, g_object_unref); return; } } g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "Failed to locate other file."); }
void egg_task_cache_get_async (EggTaskCache *self, gconstpointer key, gboolean force_update, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_autoptr(GTask) task = NULL; GPtrArray *queued; gpointer ret; g_return_if_fail (EGG_IS_TASK_CACHE (self)); g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable)); task = g_task_new (self, cancellable, callback, user_data); /* * If we have the answer, return it now. */ if (!force_update && (ret = egg_task_cache_peek (self, key))) { g_task_return_pointer (task, self->value_copy_func (ret), self->value_destroy_func); return; } EGG_COUNTER_INC (misses); /* * Always queue the request. If we need to dispatch the worker to * fetch the result, that will happen with another task. */ if (!(queued = g_hash_table_lookup (self->queued, key))) { queued = g_ptr_array_new_with_free_func (g_object_unref); g_hash_table_insert (self->queued, self->key_copy_func ((gpointer)key), queued); } g_ptr_array_add (queued, g_object_ref (task)); EGG_COUNTER_INC (queued); /* * The in_flight hashtable will have a bit set if we have queued * an operation for this key. */ if (!g_hash_table_contains (self->in_flight, key)) { g_autoptr(GTask) fetch_task = NULL; fetch_task = g_task_new (self, cancellable, egg_task_cache_fetch_cb, self->key_copy_func ((gpointer)key)); g_hash_table_insert (self->in_flight, self->key_copy_func ((gpointer)key), GINT_TO_POINTER (TRUE)); self->populate_callback (self, key, g_object_ref (fetch_task), self->populate_callback_data); EGG_COUNTER_INC (in_flight); } }
/** * storaged_linux_drive_object_is_not_in_use: * @object: A #StoragedLinuxDriveObject. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: A #GError or %NULL. * * Checks if the drive represented by @object is in use and sets * @error if so. * * Returns: %TRUE if @object is not is use, %FALSE if @error is set. */ gboolean storaged_linux_drive_object_is_not_in_use (StoragedLinuxDriveObject *object, GCancellable *cancellable, GError **error) { GDBusObjectManagerServer *object_manager; const gchar *drive_object_path; gboolean ret = TRUE; GList *objects = NULL; GList *l; g_return_val_if_fail (STORAGED_IS_LINUX_DRIVE_OBJECT (object), FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); drive_object_path = g_dbus_object_get_object_path (G_DBUS_OBJECT (object)); object_manager = storaged_daemon_get_object_manager (object->daemon); objects = g_dbus_object_manager_get_objects (G_DBUS_OBJECT_MANAGER (object_manager)); /* Visit all block devices related to the drive... */ for (l = objects; l != NULL; l = l->next) { GDBusObjectSkeleton *iter_object = G_DBUS_OBJECT_SKELETON (l->data); StoragedBlock *block; StoragedFilesystem *filesystem; if (!STORAGED_IS_LINUX_BLOCK_OBJECT (iter_object)) continue; block = storaged_object_peek_block (STORAGED_OBJECT (iter_object)); filesystem = storaged_object_peek_filesystem (STORAGED_OBJECT (iter_object)); if (g_strcmp0 (storaged_block_get_drive (block), drive_object_path) != 0) continue; /* bail if block device is mounted */ if (filesystem != NULL) { if (g_strv_length ((gchar **) storaged_filesystem_get_mount_points (filesystem)) > 0) { g_set_error (error, STORAGED_ERROR, STORAGED_ERROR_DEVICE_BUSY, "Device %s is mounted", storaged_block_get_preferred_device (block)); ret = FALSE; goto out; } } /* bail if block device is unlocked (LUKS) */ if (is_block_unlocked (objects, g_dbus_object_get_object_path (G_DBUS_OBJECT (iter_object)))) { g_set_error (error, STORAGED_ERROR, STORAGED_ERROR_DEVICE_BUSY, "Encrypted device %s is unlocked", storaged_block_get_preferred_device (block)); ret = FALSE; goto out; } } out: g_list_free_full (objects, g_object_unref); return ret; }
/** * push_gcm_client_deliver_async: * @client: (in): A #PushGcmClient. * @identities: (element-type PushGcmIdentity*): A #GList of #PushGcmIdentity. * @message: A #PushGcmMessage. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback. * @user_data: User data for @callback. * * Asynchronously deliver a #PushGcmMessage to one or more GCM enabled * devices. */ void push_gcm_client_deliver_async (PushGcmClient *client, GList *identities, PushGcmMessage *message, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { PushGcmClientPrivate *priv; GSimpleAsyncResult *simple; SoupMessage *request; const gchar *registration_id; const gchar *collapse_key; JsonGenerator *g; JsonObject *obj; JsonObject *data; JsonObject *mdata; JsonArray *ar; JsonNode *node; GList *iter; GList *list; gchar *str; gsize length; guint time_to_live; ENTRY; g_return_if_fail(PUSH_IS_GCM_CLIENT(client)); g_return_if_fail(identities); g_return_if_fail(PUSH_IS_GCM_MESSAGE(message)); g_return_if_fail(!cancellable || G_IS_CANCELLABLE(cancellable)); g_return_if_fail(callback); priv = client->priv; request = soup_message_new("POST", PUSH_GCM_CLIENT_URL); ar = json_array_new(); for (iter = identities; iter; iter = iter->next) { g_assert(PUSH_IS_GCM_IDENTITY(iter->data)); registration_id = push_gcm_identity_get_registration_id(iter->data); json_array_add_string_element(ar, registration_id); } str = g_strdup_printf("key=%s", priv->auth_token); soup_message_headers_append(request->request_headers, "Authorization", str); g_free(str); soup_message_headers_append(request->request_headers, "Accept", "application/json"); data = json_object_new(); if ((collapse_key = push_gcm_message_get_collapse_key(message))) { json_object_set_string_member(data, "collapse_key", collapse_key); } json_object_set_boolean_member(data, "delay_while_idle", push_gcm_message_get_delay_while_idle(message)); json_object_set_boolean_member(data, "dry_run", push_gcm_message_get_dry_run(message)); if ((time_to_live = push_gcm_message_get_time_to_live(message))) { json_object_set_int_member(data, "time_to_live", time_to_live); } if ((mdata = push_gcm_message_get_data(message))) { json_object_set_object_member(data, "data", mdata); } obj = json_object_new(); json_object_set_array_member(obj, "registration_ids", ar); json_object_set_object_member(obj, "data", data); node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(node, obj); json_object_unref(obj); g = json_generator_new(); json_generator_set_pretty(g, TRUE); json_generator_set_indent(g, 2); json_generator_set_root(g, node); str = json_generator_to_data(g, &length); json_node_free(node); g_object_unref(g); g_print("REQUEST: \"%s\"\n", str); soup_message_set_request(request, "application/json", SOUP_MEMORY_TAKE, str, length); simple = g_simple_async_result_new(G_OBJECT(client), callback, user_data, push_gcm_client_deliver_async); /* * Keep the list of identities around until we receive our result. * We need them to key with the resulting array. */ list = g_list_copy(identities); g_list_foreach(list, (GFunc)g_object_ref, NULL); g_object_set_data_full(G_OBJECT(simple), "identities", list, _push_gcm_identities_free); soup_session_queue_message(SOUP_SESSION(client), request, push_gcm_client_deliver_cb, simple); EXIT; }
GCabFileCallback file_callback, GFileProgressCallback progress_callback, gpointer user_data, GCancellable *cancellable, GError **error) { cheader_t header = { .offsetfiles = CFI_START, // CFHEADER + 1 * CFFOLDER .nfolders = 1, // a single CAB folder is enough }; cfolder_t folder = { 0, }; g_return_val_if_fail (GCAB_IS_CABINET (self), FALSE); g_return_val_if_fail (G_IS_OUTPUT_STREAM (out), FALSE); g_return_val_if_fail (G_IS_SEEKABLE (out), FALSE); g_return_val_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (!error || *error == NULL, FALSE); /* FIXME: current limitation of 1 folder */ g_return_val_if_fail (self->folders->len == 1, FALSE); GCabFolder *cabfolder = g_ptr_array_index (self->folders, 0); GCabFile *file; gsize nfiles = gcab_folder_get_nfiles (cabfolder); GInputStream *in = NULL; GDataOutputStream *dstream = NULL; gboolean success = FALSE; gssize len, offset = 0; cdata_t block = { 0, }; guint8 data[DATABLOCKSIZE]; gsize written; size_t sumstr = 0;