コード例 #1
0
ファイル: ConnmanManager.cpp プロジェクト: roland-wilhelm/vhd
GList* ConnmanManager::delete_invalid_services() {

	GHashTableIter iter;
	gpointer key, value;
	GList *list = NULL;
	gint valid = 0, invalid = 0;

	DBG3();

	if(m_services == NULL)
		return NULL;

	g_hash_table_iter_init(&iter, m_services);
	while(g_hash_table_iter_next(&iter, &key, &value)) {

		ConnmanService *service = (ConnmanService *)value;

		if(service->get_visited() == TRUE) {

			valid++;
			/* service is valid, set visited flag to FALSE */
			service->set_visited(FALSE);
		}
		else {

			invalid++;
			/* service is not valid, remove it from the table and delete it. */
			DBG("delete invalid service '%s'", service->get_object_path());
			list = g_list_prepend(list, g_strdup(service->get_object_path()));
			delete service;
			g_hash_table_iter_remove(&iter);
		}

	}

	DBG2("NETWORKS VALID '%d', INVALID '%d'", valid, invalid);

	return list;

}
コード例 #2
0
ファイル: kmsutils.c プロジェクト: ArenaCloud/kms-core
static void
remb_event_manager_calc_min (RembEventManager * manager, guint default_min)
{
  guint remb_min = 0;
  GstClockTime time = kms_utils_get_time_nsecs ();
  GstClockTime oldest_time = GST_CLOCK_TIME_NONE;
  GHashTableIter iter;
  gpointer key, v;

  g_hash_table_iter_init (&iter, manager->remb_hash);
  while (g_hash_table_iter_next (&iter, &key, &v)) {
    guint br = ((RembHashValue *) v)->bitrate;
    GstClockTime ts = ((RembHashValue *) v)->ts;

    if (time - ts > manager->clear_interval) {
      GST_TRACE ("Remove entry %" G_GUINT32_FORMAT, GPOINTER_TO_UINT (key));
      g_hash_table_iter_remove (&iter);
      continue;
    }

    if (remb_min == 0) {
      remb_min = br;
    } else {
      remb_min = MIN (remb_min, br);
    }

    oldest_time = MIN (oldest_time, ts);
  }

  if (remb_min == 0 && default_min > 0) {
    GST_DEBUG_OBJECT (manager->pad, "Setting default value: %" G_GUINT32_FORMAT,
        default_min);
    remb_min = default_min;
  }

  manager->oldest_remb_time = oldest_time;
  remb_event_manager_set_min (manager, remb_min);
}
コード例 #3
0
ファイル: kmselement.c プロジェクト: shelsonjava/kms-core
static void
kms_element_create_pending_pads (KmsElement * self, KmsElementPadType type)
{
  GHashTableIter iter;
  gpointer key, value;
  GstElement *element;
  const gchar *templ_name;
  GSList *keys = NULL, *l;

  KMS_ELEMENT_LOCK (self);

  if (!kms_element_get_data_by_type (self, type, &templ_name, &element)) {
    KMS_ELEMENT_UNLOCK (self);
    return;
  }

  g_hash_table_iter_init (&iter, self->priv->pendingpads);
  while (g_hash_table_iter_next (&iter, &key, &value)) {
    PendingSrcPad *pendingpad = value;

    /* TODO: Discriminate pads using their description */
    if (pendingpad->type != type) {
      continue;
    }

    keys = g_slist_prepend (keys, g_strdup (key));
    g_hash_table_iter_remove (&iter);
  }

  KMS_ELEMENT_UNLOCK (self);

  /* Create all pending pads */
  for (l = keys; l != NULL; l = l->next) {
    kms_element_add_src_pad (self, element, l->data, templ_name);
  }

  g_slist_free_full (keys, g_free);
}
コード例 #4
0
static void
clear_secrets_with_flags (NMSetting *setting,
	                      GParamSpec *pspec,
	                      NMSettingClearSecretsWithFlagsFn func,
	                      gpointer user_data)
{
	NMSettingVPNPrivate *priv = NM_SETTING_VPN_GET_PRIVATE (setting);
	GHashTableIter iter;
	const char *secret;

	if (priv->secrets == NULL)
		return;

	/* Iterate through secrets hash and check each entry */
	g_hash_table_iter_init (&iter, priv->secrets);
	while (g_hash_table_iter_next (&iter, (gpointer) &secret, NULL)) {
		NMSettingSecretFlags flags = NM_SETTING_SECRET_FLAG_NONE;

		nm_setting_get_secret_flags (setting, secret, &flags, NULL);
		if (func (setting, pspec->name, flags, user_data) == TRUE)
			g_hash_table_iter_remove (&iter);
	}
}
コード例 #5
0
ファイル: cpu-keepalive.c プロジェクト: spiiroin/mce
/** Update client timeout to be maximum of context timeouts
 *
 * @param self pointer to cka_client_t structure
 */
static
void
cka_client_scan_timeout(cka_client_t *self)
{
  tick_t now  = cka_tick_get_current();

  self->cli_timeout = 0;

  /* Expire sessions / update client timeout */
  GHashTableIter iter;
  gpointer       val;

  g_hash_table_iter_init(&iter, self->cli_sessions);
  while( g_hash_table_iter_next(&iter, 0, &val) )
  {
    cka_session_t *session = val;

    if( session->ses_timeout <= now )
    {
      /* Expire session */
      cka_session_finish(session, now);
      g_hash_table_iter_remove(&iter);
    }
    else if( self->cli_timeout < session->ses_timeout )
    {
      /* Update client timeout */
      self->cli_timeout = session->ses_timeout;
    }
  }

  if( self->cli_timeout > now )
  {
    mce_log(LL_DEBUG, "client T%+"PRId64"; %s",
            now - self->cli_timeout,
            cka_client_identify(self));
  }
}
コード例 #6
0
ファイル: st-texture-cache.c プロジェクト: joequant/Cinnamon
/* Evicts all cached textures for named icons */
static void
st_texture_cache_evict_icons (StTextureCache *cache)
{
  GHashTableIter iter;
  gpointer key;
  gpointer value;

  g_debug ("%s: Pre-evict count: %d\n", G_STRFUNC, g_hash_table_size (cache->priv->keyed_cache));

  g_hash_table_iter_init (&iter, cache->priv->keyed_cache);
  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      const char *cache_key = key;

      /* This is too conservative - it takes out all cached textures
       * for GIcons even when they aren't named icons, but it's not
       * worth the complexity of parsing the key and calling
       * g_icon_new_for_string(); icon theme changes aren't normal */
      if (g_str_has_prefix (cache_key, CACHE_PREFIX_ICON))
        g_hash_table_iter_remove (&iter);
    }

  g_debug ("%s: Post-evict count: %d\n", G_STRFUNC, g_hash_table_size (cache->priv->keyed_cache));
}
コード例 #7
0
void
_nm_object_cache_clear (NMObject *except)
{
	GHashTableIter iter;
	NMObject *obj;
	const char *path;
	char *foo;

	_init_cache ();
	g_hash_table_iter_init (&iter, cache);
	while (g_hash_table_iter_next (&iter, (gpointer) &path, (gpointer) &obj)) {
		if (obj != except) {
			/* Remove the callback so that if the object isn't yet released
			 * by a client, when it does finally get unrefed, it won't trigger
			 * the cache removal for a new object with the same path as the
			 * one being released.
			 */
			foo = g_object_steal_data (G_OBJECT (obj), "nm-object-cache-tag");
			g_free (foo);

			g_hash_table_iter_remove (&iter);
		}
	}
}
コード例 #8
0
ファイル: jawimpl.c プロジェクト: GNOME/java-atk-wrapper
static void
jaw_impl_finalize(GObject *gobject)
{
  JawObject *jaw_obj = JAW_OBJECT(gobject);
  jobject global_ac = jaw_obj->acc_context;

  JawImpl *jaw_impl = (JawImpl*)jaw_obj;

  JNIEnv *jniEnv = jaw_util_get_jni_env();
  object_table_remove( jniEnv, global_ac );

  (*jniEnv)->DeleteGlobalRef(jniEnv, global_ac);
  jaw_obj->acc_context = NULL;

  /* Interface finalize */
  GHashTableIter iter;
  gpointer value;

  g_hash_table_iter_init(&iter, jaw_impl->ifaceTable);
  while (g_hash_table_iter_next(&iter, NULL, &value))
  {
    JawInterfaceInfo *info = (JawInterfaceInfo*)value;
    info->finalize(info->data);

    g_free(info);

    g_hash_table_iter_remove(&iter);
  }
  if (jaw_impl->ifaceTable != NULL)
  {
    g_hash_table_unref(jaw_impl->ifaceTable);
    g_hash_table_destroy(jaw_obj->storedData);
  }
  /* Chain up to parent's finalize */
  G_OBJECT_CLASS(jaw_impl_parent_class)->finalize(gobject);
}
コード例 #9
0
static void
shell_xdg_migrate_process_corrections (GHashTable *corrections)
{
	GHashTableIter iter;
	gpointer old_filename;
	gpointer new_filename;

	g_hash_table_iter_init (&iter, corrections);

	while (g_hash_table_iter_next (&iter, &old_filename, &new_filename)) {
		gboolean is_directory;

		is_directory = g_file_test (old_filename, G_FILE_TEST_IS_DIR);

		/* If the old filename is a directory and the new filename
		 * is NULL, treat it as a request to remove the directory. */
		if (is_directory && new_filename == NULL)
			shell_xdg_migrate_rmdir (old_filename);
		else
			shell_xdg_migrate_rename (old_filename, new_filename);

		g_hash_table_iter_remove (&iter);
	}
}
コード例 #10
0
ファイル: ccl_kernel_wrapper.c プロジェクト: LaSEEB/cf4ocl
/**
 * Enqueues a kernel for execution on a device.
 *
 * Internally, this function calls the clSetKernelArg() OpenCL function
 * for each argument defined with the ::ccl_kernel_set_arg() function,
 * and the executes the kernel using the clEnqueueNDRangeKernel() OpenCL
 * function.
 *
 * @warning This function is not thread-safe. For multi-threaded
 * access to the same kernel function, create multiple instances of
 * a kernel wrapper for the given kernel function with
 * ::ccl_kernel_new(), one for each thread.
 *
 * @public @memberof ccl_kernel
 *
 * @param[in] krnl A kernel wrapper object.
 * @param[in] cq A command queue wrapper object.
 * @param[in] work_dim The number of dimensions used to specify the
 * global work-items and work-items in the work-group.
 * @param[in] global_work_offset Can be used to specify an array of
 * `work_dim` unsigned values that describe the offset used to calculate
 * the global ID of a work-item.
 * @param[in] global_work_size An array of `work_dim` unsigned values
 * that describe the number of global work-items in `work_dim`
 * dimensions that will execute the kernel function.
 * @param[in] local_work_size An array of `work_dim` unsigned values
 * that describe the number of work-items that make up a work-group that
 * will execute the specified kernel.
 * @param[in,out] evt_wait_lst List of events that need to complete
 * before this command can be executed. The list will be cleared and
 * can be reused by client code.
 * @param[out] err Return location for a ::CCLErr object, or `NULL` if error
 * reporting is to be ignored.
 * @return Event wrapper object that identifies this command.
 * */
CCL_EXPORT
CCLEvent* ccl_kernel_enqueue_ndrange(CCLKernel* krnl, CCLQueue* cq,
	cl_uint work_dim, const size_t* global_work_offset,
	const size_t* global_work_size, const size_t* local_work_size,
	CCLEventWaitList* evt_wait_lst, CCLErr** err) {

	/* Make sure krnl is not NULL. */
	g_return_val_if_fail(krnl != NULL, NULL);
	/* Make sure cq is not NULL. */
	g_return_val_if_fail(cq != NULL, NULL);
	/* Make sure err is NULL or it is not set. */
	g_return_val_if_fail(err == NULL || *err == NULL, NULL);

	/* OpenCL status flag. */
	cl_int ocl_status;

	/* OpenCL event. */
	cl_event event;
	/* Event wrapper. */
	CCLEvent* evt;

	/* Iterator for table of kernel arguments. */
	GHashTableIter iter;
	gpointer arg_index_ptr, arg_ptr;

	/* Set pending kernel arguments. */
	if (krnl->args != NULL) {
		g_hash_table_iter_init(&iter, krnl->args);
		while (g_hash_table_iter_next(&iter, &arg_index_ptr, &arg_ptr)) {
			cl_uint arg_index = GPOINTER_TO_UINT(arg_index_ptr);
			CCLArg* arg = (CCLArg*) arg_ptr;
			ocl_status = clSetKernelArg(ccl_kernel_unwrap(krnl), arg_index,
				ccl_arg_size(arg), ccl_arg_value(arg));
			ccl_if_err_create_goto(*err, CCL_OCL_ERROR,
				CL_SUCCESS != ocl_status, ocl_status, error_handler,
				"%s: unable to set kernel arg %d (OpenCL error %d: %s).",
				CCL_STRD, arg_index, ocl_status, ccl_err(ocl_status));
			g_hash_table_iter_remove(&iter);
		}
	}

	/* Run kernel. */
	ocl_status = clEnqueueNDRangeKernel(ccl_queue_unwrap(cq),
		ccl_kernel_unwrap(krnl), work_dim, global_work_offset,
		global_work_size, local_work_size,
		ccl_event_wait_list_get_num_events(evt_wait_lst),
		ccl_event_wait_list_get_clevents(evt_wait_lst), &event);
	ccl_if_err_create_goto(*err, CCL_OCL_ERROR,
		CL_SUCCESS != ocl_status, ocl_status, error_handler,
		"%s: unable to enqueue kernel (OpenCL error %d: %s).",
		CCL_STRD, ocl_status, ccl_err(ocl_status));

	/* Wrap event and associate it with the respective command queue.
	 * The event object will be released automatically when the command
	 * queue is released. */
	evt = ccl_queue_produce_event(cq, event);

	/* Clear event wait list. */
	ccl_event_wait_list_clear(evt_wait_lst);

	/* If we got here, everything is OK. */
	g_assert(err == NULL || *err == NULL);
	goto finish;

error_handler:

	/* If we got here there was an error, verify that it is so. */
	g_assert(err == NULL || *err != NULL);

	/* An error occurred, return NULL to signal it. */
	evt = NULL;

finish:

	/* Return evt. */
	return evt;

}
コード例 #11
0
void chassis_log_backend_log(chassis_log_backend_t *backend, gchar* logger_name, GLogLevelFlags level, const gchar *message) {
	gboolean is_duplicate = FALSE;
	const gchar *log_lvl_name;
	const gchar *logger_name_clean = (logger_name[0] == '\0') ? "global" : logger_name;
	const gchar *stripped_message = chassis_log_skip_topsrcdir(message);

	switch (level & G_LOG_LEVEL_MASK) {
	case G_LOG_LEVEL_CRITICAL:
		log_lvl_name = "critical"; break;
	case G_LOG_LEVEL_ERROR:
		log_lvl_name = "error"; break;
	case G_LOG_LEVEL_WARNING:
		log_lvl_name = "warning"; break;
	case G_LOG_LEVEL_MESSAGE:
		log_lvl_name = "message"; break;
	case G_LOG_LEVEL_INFO:
		log_lvl_name = "info"; break;
	case G_LOG_LEVEL_DEBUG:
		log_lvl_name = "debug"; break;
	case CHASSIS_LOG_LEVEL_BROADCAST:
		log_lvl_name = "*"; break;
	default:
		log_lvl_name = "unknown"; break;
	}

	chassis_log_backend_lock(backend);

	/* check for a duplicate message
	 * never consider this to be a duplicate if the log level is INFO (which being used to force a message, e.g. in broadcasting)
	 */
	if (backend->last_msg->len > 0 &&
			0 == strcmp(backend->last_msg->str, stripped_message) &&
			level != CHASSIS_LOG_LEVEL_BROADCAST && /* a broadcast */
			backend->needs_compress) {
		is_duplicate = TRUE;
	}

	if (!is_duplicate ||
			backend->last_msg_count > 100 ||
			time(NULL) - backend->last_msg_ts > 30) {	/* TODO: make these limits configurable */
		if (backend->last_msg_count) {
			GString *logger_names = g_string_new("");
			guint hash_size = g_hash_table_size(backend->last_loggers);

			if (hash_size > 0) { /* should be always true... */
				GHashTableIter iter;
				gpointer key, value;
				guint i = 0;

				g_hash_table_iter_init(&iter, backend->last_loggers);
				while (g_hash_table_iter_next(&iter, &key, &value)) {
					g_string_append(logger_names, (gchar*)key);

					g_hash_table_iter_remove(&iter);
					if (++i < hash_size) {
						g_string_append(logger_names, ", ");
					}
				}
			}

			if (backend->needs_timestamp) {
				chassis_log_backend_update_timestamp(backend);
				g_string_append_len(backend->log_str, C(": "));
			}
			g_string_append_printf(backend->log_str, "[%s] last message repeated %d times\n",
					logger_names->str,
					backend->last_msg_count);
			backend->log_func(backend, level, S(backend->log_str));
			g_string_free(logger_names, TRUE);
		}

		if (backend->needs_timestamp) {
			chassis_log_backend_update_timestamp(backend);
			g_string_append_len(backend->log_str, C(": "));
		}
		g_string_append_printf(backend->log_str, "[%s] (%s) %s",
				logger_name_clean,
				log_lvl_name,
				stripped_message);

		/* reset the last-logged message */	
		g_string_assign(backend->last_msg, stripped_message);
		backend->last_msg_count = 0;
		backend->last_msg_ts = time(NULL);

		/* ask the backend to perform the write */
		backend->log_func(backend, level, S(backend->log_str));
	} else {
		/* save the logger_name to print all of the coalesced logger sources later */
		gchar *hash_logger_name = g_strdup(logger_name_clean);

		g_hash_table_insert(backend->last_loggers, hash_logger_name, hash_logger_name);

		backend->last_msg_count++;
	}

	chassis_log_backend_unlock(backend);
}
コード例 #12
0
ファイル: flac_tag.c プロジェクト: GNOME/easytag
/*
 * Read tag data from a FLAC file using the level 2 flac interface,
 * Note:
 *  - if field is found but contains no info (strlen(str)==0), we don't read it
 */
gboolean
flac_tag_read_file_tag (GFile *file,
                        File_Tag *FileTag,
                        GError **error)
{
    FLAC__Metadata_Chain *chain;
    EtFlacReadState state;
    FLAC__IOCallbacks callbacks = { et_flac_read_func,
                                    NULL, /* Do not set a write callback. */
                                    et_flac_seek_func, et_flac_tell_func,
                                    et_flac_eof_func,
                                    et_flac_read_close_func
                                  };
    FLAC__Metadata_Iterator *iter;

    EtPicture *prev_pic = NULL;

    g_return_val_if_fail (file != NULL && FileTag != NULL, FALSE);
    g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

    chain = FLAC__metadata_chain_new ();

    if (chain == NULL)
    {
        g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, "%s",
                     g_strerror (ENOMEM));
        return FALSE;
    }

    state.error = NULL;
    state.istream = g_file_read (file, NULL, &state.error);
    state.seekable = G_SEEKABLE (state.istream);

    if (!FLAC__metadata_chain_read_with_callbacks (chain, &state, callbacks))
    {
        /* TODO: Provide a dedicated error enum corresponding to status. */
        g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, "%s",
                     _("Error opening FLAC file"));
        et_flac_read_close_func (&state);

        return FALSE;
    }

    iter = FLAC__metadata_iterator_new ();

    if (iter == NULL)
    {
        et_flac_read_close_func (&state);
        g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, "%s",
                     g_strerror (ENOMEM));
        return FALSE;
    }

    FLAC__metadata_iterator_init (iter, chain);

    while (FLAC__metadata_iterator_next (iter))
    {
        FLAC__StreamMetadata *block;

        block = FLAC__metadata_iterator_get_block (iter);

        if (block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
        {
            const FLAC__StreamMetadata_VorbisComment *vc;
            GHashTable *tags;
            GSList *strings;
            GHashTableIter tags_iter;
            gchar *key;

            /* Get comments from block. */
            vc = &block->data.vorbis_comment;
            tags = populate_tag_hash_table (vc);

            /* Title */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_TITLE)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->title);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_TITLE);
            }

            /* Artist */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_ARTIST)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->artist);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_ARTIST);
            }

            /* Album artist. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_ALBUM_ARTIST)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->album_artist);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_ALBUM_ARTIST);
            }

            /* Album. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_ALBUM)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->album);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_ALBUM);
            }

            /* Disc number and total discs. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_DISC_TOTAL)))
            {
                /* Only take values from the first total discs field. */
                if (!et_str_empty (strings->data))
                {
                    FileTag->disc_total = et_disc_number_to_string (atoi (strings->data));
                }

                g_slist_free_full (strings, g_free);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_DISC_TOTAL);
            }

            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_DISC_NUMBER)))
            {
                /* Only take values from the first disc number field. */
                if (!et_str_empty (strings->data))
                {
                    gchar *separator;

                    separator = strchr (strings->data, '/');

                    if (separator && !FileTag->disc_total)
                    {
                        FileTag->disc_total = et_disc_number_to_string (atoi (separator + 1));
                        *separator = '\0';
                    }

                    FileTag->disc_number = et_disc_number_to_string (atoi (strings->data));
                }

                g_slist_free_full (strings, g_free);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_DISC_NUMBER);
            }

            /* Track number and total tracks. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_TRACK_TOTAL)))
            {
                /* Only take values from the first total tracks field. */
                if (!et_str_empty (strings->data))
                {
                    FileTag->track_total = et_track_number_to_string (atoi (strings->data));
                }

                g_slist_free_full (strings, g_free);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_TRACK_TOTAL);
            }

            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_TRACK_NUMBER)))
            {
                /* Only take values from the first track number field. */
                if (!et_str_empty (strings->data))
                {
                    gchar *separator;

                    separator = strchr (strings->data, '/');

                    if (separator && !FileTag->track_total)
                    {
                        FileTag->track_total = et_track_number_to_string (atoi (separator + 1));
                        *separator = '\0';
                    }

                    FileTag->track = et_track_number_to_string (atoi (strings->data));
                }

                g_slist_free_full (strings, g_free);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_TRACK_NUMBER);
            }

            /* Year. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_DATE)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->year);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_DATE);
            }

            /* Genre. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_GENRE)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->genre);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_GENRE);
            }

            /* Comment. */
            {
                GSList *descs;
                GSList *comments;

                descs = g_hash_table_lookup (tags,
                                             ET_VORBIS_COMMENT_FIELD_DESCRIPTION);
                comments = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_COMMENT);

                /* Prefer DESCRIPTION, as it is part of the spec. */
                if (descs && !comments)
                {
                    g_slist_foreach (descs, values_list_foreach,
                                     &FileTag->comment);
                }
                else if (descs && comments)
                {
                    /* Mark the file as modified, so that comments are written
                     * to the DESCRIPTION field on saving. */
                    FileTag->saved = FALSE;

                    g_slist_foreach (descs, values_list_foreach,
                                     &FileTag->comment);
                    g_slist_foreach (comments, values_list_foreach,
                                     &FileTag->comment);
                }
                else if (comments)
                {
                    FileTag->saved = FALSE;

                    g_slist_foreach (comments, values_list_foreach,
                                     &FileTag->comment);
                }

                g_slist_free (descs);
                g_slist_free (comments);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_DESCRIPTION);
                g_hash_table_remove (tags,
                                     ET_VORBIS_COMMENT_FIELD_COMMENT);
            }

            /* Composer. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_COMPOSER)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->composer);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_COMPOSER);
            }

            /* Original artist. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_PERFORMER)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->orig_artist);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_PERFORMER);
            }

            /* Copyright. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_COPYRIGHT)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->copyright);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_COPYRIGHT);
            }

            /* URL. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_CONTACT)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->url);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_CONTACT);
            }

            /* Encoded by. */
            if ((strings = g_hash_table_lookup (tags,
                                                ET_VORBIS_COMMENT_FIELD_ENCODED_BY)))
            {
                g_slist_foreach (strings, values_list_foreach,
                                 &FileTag->encoded_by);
                g_slist_free (strings);
                g_hash_table_remove (tags, ET_VORBIS_COMMENT_FIELD_ENCODED_BY);
            }

            /* Save unsupported fields. */
            g_hash_table_iter_init (&tags_iter, tags);

            while (g_hash_table_iter_next (&tags_iter, (gpointer *)&key,
                                           (gpointer *)&strings))
            {
                GSList *l;

                for (l = strings; l != NULL; l = g_slist_next (l))
                {
                    FileTag->other = g_list_prepend (FileTag->other,
                                                     g_strconcat (key,
                                                             "=",
                                                             l->data,
                                                             NULL));
                }

                g_slist_free_full (strings, g_free);
                g_hash_table_iter_remove (&tags_iter);
            }

            if (FileTag->other)
            {
                FileTag->other = g_list_reverse (FileTag->other);
            }

            /* The hash table should now only contain keys. */
            g_hash_table_unref (tags);
        }
        else if (block->type == FLAC__METADATA_TYPE_PICTURE)
        {
            /* Picture. */
            const FLAC__StreamMetadata_Picture *p;
            GBytes *bytes;
            EtPicture *pic;

            /* Get picture data from block. */
            p = &block->data.picture;

            bytes = g_bytes_new (p->data, p->data_length);

            pic = et_picture_new (p->type, (const gchar *)p->description,
                                  0, 0, bytes);
            g_bytes_unref (bytes);

            if (!prev_pic)
            {
                FileTag->picture = pic;
            }
            else
            {
                prev_pic->next = pic;
            }

            prev_pic = pic;
        }
    }

    FLAC__metadata_iterator_delete (iter);
    FLAC__metadata_chain_delete (chain);
    et_flac_read_close_func (&state);

#ifdef ENABLE_MP3
    /* If no FLAC vorbis tag found : we try to get the ID3 tag if it exists
     * (but it will be deleted when rewriting the tag) */
    if ( FileTag->title       == NULL
            && FileTag->artist      == NULL
            && FileTag->album_artist == NULL
            && FileTag->album       == NULL
            && FileTag->disc_number == NULL
            && FileTag->disc_total == NULL
            && FileTag->year        == NULL
            && FileTag->track       == NULL
            && FileTag->track_total == NULL
            && FileTag->genre       == NULL
            && FileTag->comment     == NULL
            && FileTag->composer    == NULL
            && FileTag->orig_artist == NULL
            && FileTag->copyright   == NULL
            && FileTag->url         == NULL
            && FileTag->encoded_by  == NULL
            && FileTag->picture     == NULL)
    {
        id3tag_read_file_tag (file, FileTag, NULL);

        // If an ID3 tag has been found (and no FLAC tag), we mark the file as
        // unsaved to rewrite a flac tag.
        if ( FileTag->title       != NULL
                || FileTag->artist      != NULL
                || FileTag->album_artist != NULL
                || FileTag->album       != NULL
                || FileTag->disc_number != NULL
                || FileTag->disc_total != NULL
                || FileTag->year        != NULL
                || FileTag->track       != NULL
                || FileTag->track_total != NULL
                || FileTag->genre       != NULL
                || FileTag->comment     != NULL
                || FileTag->composer    != NULL
                || FileTag->orig_artist != NULL
                || FileTag->copyright   != NULL
                || FileTag->url         != NULL
                || FileTag->encoded_by  != NULL
                || FileTag->picture     != NULL)
        {
            FileTag->saved = FALSE;
        }
    }
#endif

    return TRUE;
}
コード例 #13
0
static void
update_with_variant (GPid pid,
                     GVariant *info,
                     GError *error,
                     gpointer user_data)
{
    StoragedLinuxVolumeGroupObject *object = user_data;
    StoragedDaemon *daemon;
    GDBusObjectManagerServer *manager;
    GVariantIter *iter;
    GHashTableIter volume_iter;
    gpointer key, value;
    GHashTable *new_lvs;
    GHashTable *new_pvs;
    GList *objects, *l;
    gboolean needs_polling = FALSE;

    daemon = storaged_linux_volume_group_object_get_daemon (object);
    manager = storaged_daemon_get_object_manager (daemon);

    if (error)
    {
        storaged_warning ("Failed to update LVM volume group %s: %s",
                          storaged_linux_volume_group_object_get_name (object),
                          error->message);
        g_object_unref (object);
        return;
    }

    storaged_linux_volume_group_update (STORAGED_LINUX_VOLUME_GROUP (object->iface_volume_group), info, &needs_polling);

    if (!g_dbus_object_manager_server_is_exported (manager, G_DBUS_OBJECT_SKELETON (object)))
        g_dbus_object_manager_server_export_uniquely (manager, G_DBUS_OBJECT_SKELETON (object));

    new_lvs = g_hash_table_new (g_str_hash, g_str_equal);

    if (g_variant_lookup (info, "lvs", "aa{sv}", &iter))
    {
        GVariant *lv_info = NULL;
        while (g_variant_iter_loop (iter, "@a{sv}", &lv_info))
        {
            const gchar *name;
            StoragedLinuxLogicalVolumeObject *volume;

            g_variant_lookup (lv_info, "name", "&s", &name);

            update_operations (daemon, name, lv_info, &needs_polling);

            if (lv_is_pvmove_volume (name))
                needs_polling = TRUE;

            if (storaged_daemon_util_lvm2_name_is_reserved (name))
                continue;

            volume = g_hash_table_lookup (object->logical_volumes, name);
            if (volume == NULL)
            {
                volume = storaged_linux_logical_volume_object_new (daemon, object, name);
                storaged_linux_logical_volume_object_update (volume, lv_info, &needs_polling);
                storaged_linux_logical_volume_object_update_etctabs (volume);
                g_dbus_object_manager_server_export_uniquely (manager, G_DBUS_OBJECT_SKELETON (volume));
                g_hash_table_insert (object->logical_volumes, g_strdup (name), g_object_ref (volume));
            }
            else
                storaged_linux_logical_volume_object_update (volume, lv_info, &needs_polling);

            g_hash_table_insert (new_lvs, (gchar *)name, volume);
        }
        g_variant_iter_free (iter);
    }

    g_hash_table_iter_init (&volume_iter, object->logical_volumes);
    while (g_hash_table_iter_next (&volume_iter, &key, &value))
    {
        const gchar *name = key;
        StoragedLinuxLogicalVolumeObject *volume = value;

        if (!g_hash_table_contains (new_lvs, name))
        {
            g_dbus_object_manager_server_unexport (manager,
                                                   g_dbus_object_get_object_path (G_DBUS_OBJECT (volume)));
            g_hash_table_iter_remove (&volume_iter);

            g_object_unref (G_OBJECT (volume));
        }
    }

    storaged_volume_group_set_needs_polling (STORAGED_VOLUME_GROUP (object->iface_volume_group),
            needs_polling);

    /* Update block objects. */

    new_pvs = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, (GDestroyNotify)g_variant_unref);
    if (g_variant_lookup (info, "pvs", "aa{sv}", &iter))
    {
        const gchar *name;
        GVariant *pv_info;
        while (g_variant_iter_next (iter, "@a{sv}", &pv_info))
        {
            if (g_variant_lookup (pv_info, "device", "&s", &name))
                g_hash_table_insert (new_pvs, (gchar *)name, pv_info);
            else
                g_variant_unref (pv_info);
        }
    }

    objects = g_dbus_object_manager_get_objects (G_DBUS_OBJECT_MANAGER (manager));
    for (l = objects; l != NULL; l = l->next)
    {
        if (STORAGED_IS_LINUX_BLOCK_OBJECT (l->data))
            update_block (STORAGED_LINUX_BLOCK_OBJECT (l->data), object, new_lvs, new_pvs);
    }
    g_list_free_full (objects, g_object_unref);

    g_hash_table_destroy (new_lvs);
    g_hash_table_destroy (new_pvs);

    g_object_unref (object);
}
コード例 #14
0
ファイル: session.c プロジェクト: jpsutton/fusedav
static void construct_resolve_slist(GHashTable *addr_table) {
    static const char *funcname = "construct_resolve_slist";
    int addr_score_idx = 0;
    GHashTableIter iter;
    gpointer key, value;
    // Did we change the list? Used to decide to print new list
    // We get a new list if we get a new session, or we add or delete a node 
    // from the cluster; or if we update a health score
    struct addr_score_s *addr_score[MAX_NODES + 1] = {NULL};

    // Is there anything in node_hash_table not in addr table,
    // e.g. a deleted addr
    g_hash_table_iter_init (&iter, node_status.node_hash_table);
    log_print(LOG_DEBUG, SECTION_SESSION_DEFAULT, "%s: hash_table [%p], iter [%p]",
        funcname, node_status.node_hash_table, iter);
    while (g_hash_table_iter_next (&iter, &key, &value)) {
        // Is this address in addr_table?
        bool exists = g_hash_table_lookup(addr_table, key);
        if (!exists) {
            // delete the node
            g_hash_table_iter_remove(&iter);
            log_print(LOG_NOTICE, SECTION_SESSION_DEFAULT, "%s: removed from hash table: %s", 
                    funcname, key);
        }
    }
    // Is there anything in addr_table not in node_hash_table
    // e.g. an added addr
    g_hash_table_iter_init (&iter, addr_table);
    while (g_hash_table_iter_next (&iter, &key, &value)) {
        // Is this address in addr_table?
        bool exists = g_hash_table_lookup(node_status.node_hash_table, key);
        if (!exists) {
            // Add to node_hash_table
            set_health_status(key, value);
            log_print(LOG_NOTICE, SECTION_SESSION_DEFAULT, "%s: added to hash table %s :: %s",
                    funcname, key, value);
        }
    }

    // Prepare a sortable array
    g_hash_table_iter_init (&iter, node_status.node_hash_table);

    addr_score_idx = 0;
    while (g_hash_table_iter_next (&iter, &key, &value)) {
        struct health_status_s *healthstatus = (struct health_status_s *)value;

        log_print(LOG_DEBUG, SECTION_SESSION_DEFAULT, "%s: healthstatus->curladdr: %s", funcname, healthstatus->curladdr);

        // We need to sort on health score, but use the addr name.
        addr_score[addr_score_idx] = g_new(struct addr_score_s, 1);

        // Save values into sortable array
        strncpy(addr_score[addr_score_idx]->addr, healthstatus->curladdr, IPSTR_SZ);
        addr_score[addr_score_idx]->score = healthstatus->score;
        log_print(LOG_INFO, SECTION_SESSION_DEFAULT, "%s: addr_score_idx [%d], addr [%s], score [%d]",
            funcname, addr_score_idx, addr_score[addr_score_idx]->addr, addr_score[addr_score_idx]->score);
        ++addr_score_idx;
    }

    // Randomize first; then sort and expect that the order of items with the same score (think '0') stays randomized
    randomize((void *)addr_score, addr_score_idx);

    // sort the array
    qsort(addr_score, addr_score_idx, sizeof(struct addr_score_s *), compare_node_score);

    if (addr_score[0]->score != 0) {
        // All connections are in some state of bad
        log_print(LOG_ERR, SECTION_SESSION_DEFAULT, "%s: top entry is non-zero: %s -- %d",
            funcname, addr_score[0]->addr, addr_score[0]->score);
    }

    // addr_score_idx is the number of addresses we processed above
    for (int idx = 0; idx < addr_score_idx; idx++) {
        log_print(LOG_DYNAMIC, SECTION_SESSION_DEFAULT, 
                "%s: inserting into resolve_slist (%p): %s, score %d",
                funcname, node_status.resolve_slist, addr_score[idx]->addr, addr_score[idx]->score);
        node_status.resolve_slist = curl_slist_append(node_status.resolve_slist, addr_score[idx]->addr);
        g_free(addr_score[idx]);
    }
}
コード例 #15
0
ファイル: load_metadata.c プロジェクト: M0ses/createrepo_c
int
cr_metadata_load_xml(cr_Metadata *md,
                     struct cr_MetadataLocation *ml,
                     GError **err)
{
    int result;
    GError *tmp_err = NULL;
    GHashTable *intern_hashtable;  // key is checksum (pkgId)
    cr_HashTableKeyDupAction dupaction = md->dupaction;

    assert(md);
    assert(ml);
    assert(!err || *err == NULL);

    if (!ml->pri_xml_href) {
        g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "primary.xml file is missing");
        return CRE_BADARG;
    }

    // Load metadata
    intern_hashtable = cr_new_metadata_hashtable();
    result = cr_load_xml_files(intern_hashtable,
                               ml->pri_xml_href,
                               ml->fil_xml_href,
                               ml->oth_xml_href,
                               md->chunk,
                               md->pkglist_ht,
                               &tmp_err);

    if (result != CRE_OK) {
        g_critical("%s: Error encountered while parsing", __func__);
        g_propagate_prefixed_error(err, tmp_err,
                                   "Error encountered while parsing:");
        cr_destroy_metadata_hashtable(intern_hashtable);
        return result;
    }

    g_debug("%s: Parsed items: %d", __func__,
            g_hash_table_size(intern_hashtable));

    // Fill user hashtable and use user selected key

    GHashTableIter iter;
    gpointer p_key, p_value;
    GHashTable *ignored_keys = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                     g_free, NULL);

    g_hash_table_iter_init (&iter, intern_hashtable);
    while (g_hash_table_iter_next (&iter, &p_key, &p_value)) {
        cr_Package *pkg = (cr_Package *) p_value;
        cr_Package *epkg;
        gpointer new_key;

        switch (md->key) {
            case CR_HT_KEY_FILENAME:
                new_key = cr_get_filename(pkg->location_href);
                break;
            case CR_HT_KEY_HASH:
                new_key = pkg->pkgId;
                break;
            case CR_HT_KEY_NAME:
                new_key = pkg->name;
                break;
            default:
                // Well, this SHOULD never happend!
                // (md->key SHOULD be setted only by cr_metadata_new()
                // and it SHOULD set only valid key values)
                g_critical("%s: Unknown hash table key selected", __func__);
                assert(0);
                g_set_error(err, ERR_DOMAIN, CRE_ASSERT,
                            "Bad db type");
                return CRE_ASSERT;
        }

        epkg = g_hash_table_lookup(md->ht, new_key);
        if (epkg) {
            // Such key already exists
            if (dupaction == CR_HT_DUPACT_KEEPFIRST) {
                g_debug("%s: Key \"%s\" already exists in hashtable - Keeping the first occurrence",
                        __func__, (char *) new_key);
            } else {
                if (pkg->time_file != epkg->time_file
                    || pkg->size_package != epkg->size_package
                    || g_strcmp0(pkg->pkgId, epkg->pkgId)
                    || g_strcmp0(cr_get_filename(pkg->location_href),
                                 cr_get_filename(epkg->location_href))
                    )
                {
                    // We got a key (checksum, filename, pkg name, ..)
                    // which has a multiple occurences which are different.
                    // Ignore such key
                    g_debug("%s: Key \"%s\" is present multiple times and with "
                            "different values. Ignoring all occurrences. "
                            "[size_package: %"G_GINT64_FORMAT"|%"G_GINT64_FORMAT
                            "; time_file: %"G_GINT64_FORMAT"|%"G_GINT64_FORMAT
                            "; pkgId: %s|%s; basename: %s|%s]",
                            __func__, (gchar *) new_key,
                            pkg->size_package, epkg->size_package,
                            pkg->time_file, epkg->time_file,
                            pkg->pkgId, epkg->pkgId,
                            cr_get_filename(pkg->location_href),
                            cr_get_filename(epkg->location_href));
                    g_hash_table_insert(ignored_keys, g_strdup((gchar *) new_key), NULL);
                }
            }
            // Remove the package from the iterator anyway
            g_hash_table_iter_remove(&iter);
        } else {
            g_hash_table_insert(md->ht, new_key, p_value);
            g_hash_table_iter_steal(&iter);
        }
    }

    // Remove ignored_keys from resulting hashtable
    g_hash_table_iter_init(&iter, ignored_keys);
    while (g_hash_table_iter_next(&iter, &p_key, &p_value)) {
        char *key = (gchar *) p_key;
        g_hash_table_remove(md->ht, key);
    }

    // How much items we really use
    g_debug("%s: Really usable items: %d", __func__,
            g_hash_table_size(md->ht));

    // Cleanup

    g_hash_table_destroy(ignored_keys);
    cr_destroy_metadata_hashtable(intern_hashtable);

    return CRE_OK;
}
コード例 #16
0
static gboolean
load_mtp_db_idle_cb (RBMtpSource* source)
{
	RhythmDB *db = NULL;
	RBMtpSourcePrivate *priv = MTP_SOURCE_GET_PRIVATE (source);
	LIBMTP_track_t *tracks = NULL;
	LIBMTP_album_t *albums;
	gboolean device_forgets_albums = TRUE;

	db = get_db_for_source (source);

	g_assert (db != NULL);

	albums = LIBMTP_Get_Album_List (priv->device);
	report_libmtp_errors (priv->device, FALSE);
	if (albums != NULL) {
		LIBMTP_album_t *album;

		for (album = albums; album != NULL; album = album->next) {
			rb_debug ("album: %s, %d tracks", album->name, album->no_tracks);
			g_hash_table_insert (priv->album_map, album->name, album);
			if (album->no_tracks != 0) {
				device_forgets_albums = FALSE;
			}
		}

		if (device_forgets_albums) {
			rb_debug ("stupid mtp device detected.  will rebuild all albums.");
		}
	} else {
		rb_debug ("No albums");
		device_forgets_albums = FALSE;
	}

#ifdef HAVE_LIBMTP_030
	tracks = LIBMTP_Get_Tracklisting_With_Callback (priv->device, NULL, NULL);
#else
	tracks = LIBMTP_Get_Tracklisting (priv->device);
#endif
	report_libmtp_errors (priv->device, FALSE);
	if (tracks != NULL) {
		LIBMTP_track_t *track;
		for (track = tracks; track != NULL; track = track->next) {
			add_mtp_track_to_db (source, db, track);

			if (device_forgets_albums && track->album != NULL) {
				add_track_to_album (source, track->album, track);
			}
		}
	} else {
		rb_debug ("No tracks");
	}

	/* for stupid devices, remove any albums left with no tracks */
	if (device_forgets_albums) {
		GHashTableIter iter;
		gpointer value;
		LIBMTP_album_t *album;

		g_hash_table_iter_init (&iter, priv->album_map);
		while (g_hash_table_iter_next (&iter, NULL, &value)) {
			int ret;

			album = value;
			if (album->no_tracks == 0) {
				rb_debug ("pruning empty album \"%s\"", album->name); 
				ret = LIBMTP_Delete_Object (priv->device, album->album_id);
				if (ret != 0) {
					report_libmtp_errors (priv->device, FALSE);
				}
				g_hash_table_iter_remove (&iter);
			}
		}
	}


	g_object_unref (G_OBJECT (db));
	return FALSE;
}
コード例 #17
0
static void
lvm_update_vgs (GObject      *source_obj,
                GAsyncResult *result,
                gpointer      user_data)
{
  UDisksLVM2State *state;
  UDisksDaemon *daemon = UDISKS_DAEMON (source_obj);
  GDBusObjectManagerServer *manager;

  GTask *task = G_TASK (result);
  GError *error = NULL;
  VGsPVsData *data = g_task_propagate_pointer (task, &error);
  BDLVMVGdata **vgs = NULL;
  BDLVMPVdata **pvs = NULL;

  GHashTableIter vg_name_iter;
  gpointer key, value;
  const gchar *vg_name;

  if (!data)
    {
      if (error)
        udisks_warning ("LVM2 plugin: %s", error->message);
      else
        /* this should never happen */
        udisks_warning ("LVM2 plugin: failure but no error when getting VGs!");

      return;
    }
  vgs = data->vgs;
  pvs = data->pvs;

  /* free the data container (but not 'vgs' and 'pvs') */
  g_free (data);

  manager = udisks_daemon_get_object_manager (daemon);
  state = get_module_state (daemon);

  /* Remove obsolete groups */
  g_hash_table_iter_init (&vg_name_iter,
                          udisks_lvm2_state_get_name_to_volume_group (state));
  while (g_hash_table_iter_next (&vg_name_iter, &key, &value))
    {
      UDisksLinuxVolumeGroupObject *group;
      gboolean found = FALSE;

      vg_name = key;
      group = value;

      for (BDLVMVGdata **vgs_p=vgs; !found && (*vgs_p); vgs_p++)
          found = g_strcmp0 ((*vgs_p)->name, vg_name) == 0;

      if (!found)
        {
          udisks_linux_volume_group_object_destroy (group);
          g_dbus_object_manager_server_unexport (manager,
                                                 g_dbus_object_get_object_path (G_DBUS_OBJECT (group)));
          g_hash_table_iter_remove (&vg_name_iter);
        }
    }

  /* Add new groups and update existing groups */
  for (BDLVMVGdata **vgs_p=vgs; *vgs_p; vgs_p++)
    {
      UDisksLinuxVolumeGroupObject *group;
      GSList *vg_pvs = NULL;
      vg_name = (*vgs_p)->name;
      group = g_hash_table_lookup (udisks_lvm2_state_get_name_to_volume_group (state),
                                   vg_name);

      if (group == NULL)
        {
          group = udisks_linux_volume_group_object_new (daemon, vg_name);
          g_hash_table_insert (udisks_lvm2_state_get_name_to_volume_group (state),
                               g_strdup (vg_name), group);
        }

      for (BDLVMPVdata **pvs_p=pvs; *pvs_p; pvs_p++)
        if (g_strcmp0 ((*pvs_p)->vg_name, vg_name) == 0)
            vg_pvs = g_slist_prepend (vg_pvs, *pvs_p);

      udisks_linux_volume_group_object_update (group, *vgs_p, vg_pvs);
    }

  /* this is safe to do -- all BDLVMPVdata objects are still existing because
     the function that frees them is scheduled in main loop by the
     udisks_linux_volume_group_object_update() call above */
  for (BDLVMPVdata **pvs_p=pvs; *pvs_p; pvs_p++)
    if ((*pvs_p)->vg_name == NULL)
      bd_lvm_pvdata_free (*pvs_p);

  /* only free the containers, the contents were passed further */
  g_free (vgs);
  g_free (pvs);
}
コード例 #18
0
static gboolean
sysroot_populate_deployments_unlocked (RpmostreedSysroot *self,
				       gboolean *out_changed,
				       GError **error)
{
  gboolean ret = FALSE;
  OstreeDeployment *booted = NULL; /* owned by sysroot */
  g_autofree gchar *booted_id = NULL;
  g_autoptr(GPtrArray) deployments = NULL;
  g_autoptr(GHashTable) seen_osnames = NULL;
  GHashTableIter iter;
  gpointer hashkey;
  gpointer value;
  GVariantBuilder builder;
  guint i;
  gboolean sysroot_changed;
  gboolean repo_changed;
  struct stat repo_new_stat;

  if (!ostree_sysroot_load_if_changed (self->ot_sysroot, &sysroot_changed, self->cancellable, error))
    goto out;

  if (fstat (ostree_repo_get_dfd (self->repo), &repo_new_stat) < 0)
    {
      glnx_set_error_from_errno (error);
      goto out;
    }

  repo_changed = !(self->repo_last_stat.st_mtim.tv_sec == repo_new_stat.st_mtim.tv_sec
		   && self->repo_last_stat.st_mtim.tv_nsec == repo_new_stat.st_mtim.tv_nsec);
  if (repo_changed)
    self->repo_last_stat = repo_new_stat;

  if (!(sysroot_changed || repo_changed))
    {
      ret = TRUE;
      if (out_changed)
	*out_changed = FALSE;
      goto out;
    }

  g_debug ("loading deployments");
  g_variant_builder_init (&builder, G_VARIANT_TYPE ("aa{sv}"));

  seen_osnames = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);

  /* Updated booted property */
  booted = ostree_sysroot_get_booted_deployment (self->ot_sysroot);
  if (booted)
    {
      const gchar *os = ostree_deployment_get_osname (booted);
      g_autofree gchar *path = rpmostreed_generate_object_path (BASE_DBUS_PATH,
                                                                os, NULL);
      rpmostree_sysroot_set_booted (RPMOSTREE_SYSROOT (self), path);
      booted_id = rpmostreed_deployment_generate_id (booted);
    }
  else
    {
      rpmostree_sysroot_set_booted (RPMOSTREE_SYSROOT (self), "/");
    }

  /* Add deployment interfaces */
  deployments = ostree_sysroot_get_deployments (self->ot_sysroot);

  for (i = 0; deployments != NULL && i < deployments->len; i++)
    {
      GVariant *variant;
      OstreeDeployment *deployment = deployments->pdata[i];
      const char *deployment_os;
      
      variant = rpmostreed_deployment_generate_variant (deployment, booted_id, self->repo, error);
      if (!variant)
	goto out;
      g_variant_builder_add_value (&builder, variant);

      deployment_os = ostree_deployment_get_osname (deployment);

      /* Have we not seen this osname instance before?  If so, add it
       * now.
       */
      if (!g_hash_table_contains (self->os_interfaces, deployment_os))
	{
	  RPMOSTreeOS *obj = rpmostreed_os_new (self->ot_sysroot, self->repo,
						deployment_os,
                                                self->transaction_monitor);
          g_hash_table_insert (self->os_interfaces, g_strdup (deployment_os), obj);
	}
      /* Owned by deployment, hash lifetime is smaller */
      g_hash_table_add (seen_osnames, (char*)deployment_os);
    }

  /* Remove dead os paths */
  g_hash_table_iter_init (&iter, self->os_interfaces);
  while (g_hash_table_iter_next (&iter, &hashkey, &value))
    {
      if (!g_hash_table_contains (seen_osnames, hashkey))
        {
          g_object_run_dispose (G_OBJECT (value));
          g_hash_table_iter_remove (&iter);
        }
    }

  rpmostree_sysroot_set_deployments (RPMOSTREE_SYSROOT (self),
                                     g_variant_builder_end (&builder));
  g_debug ("finished deployments");

  ret = TRUE;
  if (out_changed)
    *out_changed = TRUE;
 out:
  return ret;
}
コード例 #19
0
ファイル: volumegroup.c プロジェクト: carriercomm/storaged-1
static void
update_with_variant (GPid pid,
                     GVariant *info,
                     GError *error,
                     gpointer user_data)
{
  struct UpdateData *data = user_data;
  StorageVolumeGroup *self = data->self;
  GVariantIter *iter;
  GHashTableIter volume_iter;
  gpointer key, value;
  GHashTable *new_lvs;
  gboolean needs_polling = FALSE;
  StorageDaemon *daemon;
  gchar *path;

  daemon = storage_daemon_get ();

  if (!error)
      volume_group_update_props (self, info, &needs_polling);

  /* After basic props, publish group, if not already done */
  if (self->need_publish)
    {
      self->need_publish = FALSE;
      path = storage_util_build_object_path ("/org/freedesktop/UDisks2/lvm",
                                        storage_volume_group_get_name (self), NULL);
      storage_daemon_publish (daemon, path, FALSE, self);
      g_free (path);
    }

  if (error)
    {
      g_message ("Failed to update LVM volume group %s: %s",
                 storage_volume_group_get_name (self), error->message);
      g_object_unref (self);
      return;
    }

  if (self->info && g_variant_equal (self->info, info))
    {
      g_debug ("%s updated without changes", self->name);
      g_object_unref (self);
      return;
    }

  if (self->info)
    g_variant_unref (self->info);
  self->info = g_variant_ref (info);

  new_lvs = g_hash_table_new (g_str_hash, g_str_equal);

  if (g_variant_lookup (info, "lvs", "aa{sv}", &iter))
    {
      GVariant *lv_info = NULL;
      while (g_variant_iter_loop (iter, "@a{sv}", &lv_info))
        {
          const gchar *name;
          StorageLogicalVolume *volume;

          g_variant_lookup (lv_info, "name", "&s", &name);

          update_operations (name, lv_info, &needs_polling);

          if (lv_is_pvmove_volume (name))
            needs_polling = TRUE;

          if (!lv_is_visible (name))
            continue;

          volume = g_hash_table_lookup (self->logical_volumes, name);
          if (volume == NULL)
            {
              volume = storage_logical_volume_new (self, name);
              storage_logical_volume_update (volume, self, lv_info, &needs_polling);

              g_hash_table_insert (self->logical_volumes, g_strdup (name), g_object_ref (volume));
            }
          else
            storage_logical_volume_update (volume, self, lv_info, &needs_polling);

          g_hash_table_insert (new_lvs, (gchar *)name, volume);
        }
      g_variant_iter_free (iter);
    }

  g_hash_table_iter_init (&volume_iter, self->logical_volumes);
  while (g_hash_table_iter_next (&volume_iter, &key, &value))
    {
      const gchar *name = key;
      StorageLogicalVolume *volume = value;

      if (!g_hash_table_contains (new_lvs, name))
        {
          /* Volume unpublishes itself */
          g_object_run_dispose (G_OBJECT (volume));
          g_hash_table_iter_remove (&volume_iter);
        }
    }

  lvm_volume_group_set_needs_polling (LVM_VOLUME_GROUP (self), needs_polling);

  /* Update physical volumes. */

  g_hash_table_remove_all (self->physical_volumes);

  if (g_variant_lookup (info, "pvs", "aa{sv}", &iter))
    {
      const gchar *name;
      GVariant *pv_info;
      while (g_variant_iter_next (iter, "@a{sv}", &pv_info))
        {
          if (g_variant_lookup (pv_info, "device", "&s", &name))
            g_hash_table_insert (self->physical_volumes, g_strdup (name), pv_info);
          else
            g_variant_unref (pv_info);
        }
    }

  /* Make sure above is published before updating blocks to point at volume group */
  update_all_blocks (self);

  if (data->done)
    data->done (self, data->done_user_data);

  g_hash_table_destroy (new_lvs);
  g_object_unref (self);
  g_free (data);
}
コード例 #20
0
ファイル: lua_timer.c プロジェクト: welterde/MudCore
 TIMER_FOREACH(iter, timer) {
   if (timer->dead) g_hash_table_iter_remove(&iter);
 }
コード例 #21
0
/**
 * gst_rtsp_session_pool_filter:
 * @pool: a #GstRTSPSessionPool
 * @func: (scope call) (allow-none): a callback
 * @user_data: (closure): user data passed to @func
 *
 * Call @func for each session in @pool. The result value of @func determines
 * what happens to the session. @func will be called with the session pool
 * locked so no further actions on @pool can be performed from @func.
 *
 * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be set to the
 * expired state with gst_rtsp_session_set_expired() and removed from
 * @pool.
 *
 * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @pool.
 *
 * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @pool but
 * will also be added with an additional ref to the result GList of this
 * function..
 *
 * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for all sessions.
 *
 * Returns: (element-type GstRTSPSession) (transfer full): a GList with all
 * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
 * element in the GList should be unreffed before the list is freed.
 */
GList *
gst_rtsp_session_pool_filter (GstRTSPSessionPool * pool,
    GstRTSPSessionPoolFilterFunc func, gpointer user_data)
{
  GstRTSPSessionPoolPrivate *priv;
  GHashTableIter iter;
  gpointer key, value;
  GList *result;
  GHashTable *visited;
  guint cookie;

  g_return_val_if_fail (GST_IS_RTSP_SESSION_POOL (pool), NULL);

  priv = pool->priv;

  result = NULL;
  if (func)
    visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);

  g_mutex_lock (&priv->lock);
restart:
  g_hash_table_iter_init (&iter, priv->sessions);
  cookie = priv->sessions_cookie;
  while (g_hash_table_iter_next (&iter, &key, &value)) {
    GstRTSPSession *session = value;
    GstRTSPFilterResult res;
    gboolean changed;

    if (func) {
      /* only visit each session once */
      if (g_hash_table_contains (visited, session))
        continue;

      g_hash_table_add (visited, g_object_ref (session));
      g_mutex_unlock (&priv->lock);

      res = func (pool, session, user_data);

      g_mutex_lock (&priv->lock);
    } else
      res = GST_RTSP_FILTER_REF;

    changed = (cookie != priv->sessions_cookie);

    switch (res) {
      case GST_RTSP_FILTER_REMOVE:
      {
        gboolean removed = TRUE;

        if (changed)
          /* something changed, check if we still have the session */
          removed = g_hash_table_remove (priv->sessions, key);
        else
          g_hash_table_iter_remove (&iter);

        if (removed) {
          /* if we managed to remove the session, update the cookie and
           * signal */
          cookie = ++priv->sessions_cookie;
          g_mutex_unlock (&priv->lock);

          g_signal_emit (pool,
              gst_rtsp_session_pool_signals[SIGNAL_SESSION_REMOVED], 0,
              session);

          g_mutex_lock (&priv->lock);
          /* cookie could have changed again, make sure we restart */
          changed |= (cookie != priv->sessions_cookie);
        }
        break;
      }
      case GST_RTSP_FILTER_REF:
        /* keep ref */
        result = g_list_prepend (result, g_object_ref (session));
        break;
      case GST_RTSP_FILTER_KEEP:
      default:
        break;
    }
    if (changed)
      goto restart;
  }
  g_mutex_unlock (&priv->lock);

  if (func)
    g_hash_table_unref (visited);

  return result;
}
コード例 #22
0
ファイル: bt-obex.c プロジェクト: LesterYang/bt-tool
int bt_obex(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

	/* Query current locale */
	setlocale(LC_CTYPE, "");

	g_type_init();
	dbus_init();

	context = g_option_context_new(" - a bluetooth OBEX client/server");
	g_option_context_add_main_entries(context, entries, NULL);
	g_option_context_set_summary(context, "Version "PACKAGE_VERSION);
	g_option_context_set_description(context,
			"Server Options:\n"
			"  -s, --server [<path>]\n"
			"  Register self at OBEX server and use given `path` as OPP save directory\n"
			"  If `path` does not specified - use current directory\n\n"
			"OPP Options:\n"
			"  -p, --opp <name|mac> <file>\n"
			"  Send `file` to remote device using Object Push Profile\n\n"
			//"Report bugs to <"PACKAGE_BUGREPORT">."
			"Project home page <"PACKAGE_URL">."
			);

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("%s: %s\n", g_get_prgname(), error->message);
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (!server_arg && !opp_arg && (!ftp_arg || strlen(ftp_arg) == 0)) {
		g_print("%s", g_option_context_get_help(context, FALSE, NULL));
		exit(EXIT_FAILURE);
	} else if (server_arg && argc != 1 && (argc != 2 || strlen(argv[1]) == 0)) {
		g_print("%s: Invalid arguments for --server\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (opp_arg && (argc != 3 || strlen(argv[1]) == 0 || strlen(argv[2]) == 0)) {
		g_print("%s: Invalid arguments for --opp\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (!dbus_system_connect(&error)) {
		g_printerr("Couldn't connect to DBus system bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	if (!dbus_session_connect(&error)) {
		g_printerr("Couldn't connect to DBus session bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	/* Check, that bluetooth daemon is running */
	if (!intf_supported(BLUEZ_DBUS_NAME, MANAGER_DBUS_PATH, MANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: bluez service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run bluetoothd?\n");
		exit(EXIT_FAILURE);
	}

	/* Check, that obexd daemon is running */
	if (!intf_supported(OBEXS_DBUS_NAME, OBEXMANAGER_DBUS_PATH, OBEXMANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: obex service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run obexd?\n");
		exit(EXIT_FAILURE);
	}

	if (server_arg) {
		if (argc == 2) {
			server_path_arg = argv[1];
		}

		/* Check that `path` is valid */
		gchar *root_folder = server_path_arg == NULL ? g_get_current_dir() : g_strdup(server_path_arg);
		if (!is_dir(root_folder, &error)) {
			exit_if_error(error);
		}

		server_transfers = g_hash_table_new(g_str_hash, g_str_equal);

		OBEXManager *manager = g_object_new(OBEXMANAGER_TYPE, NULL);
		g_signal_connect(manager, "SessionCreated", G_CALLBACK(obexmanager_session_created), NULL);
		g_signal_connect(manager, "SessionRemoved", G_CALLBACK(obexmanager_session_removed), NULL);
		g_signal_connect(manager, "TransferStarted", G_CALLBACK(obexmanager_transfer_started), NULL);
		g_signal_connect(manager, "TransferCompleted", G_CALLBACK(obexmanager_transfer_completed), NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, "RootFolder", root_folder, NULL);

		g_free(root_folder);

		obexmanager_register_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		mainloop = g_main_loop_new(NULL, FALSE);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Waiting for connections... */

		g_main_loop_unref(mainloop);

		/* Stop active transfers */
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, server_transfers);
		while (g_hash_table_iter_next(&iter, &key, &value)) {
			OBEXTransfer *t = OBEXTRANSFER(value);
			obextransfer_cancel(t, NULL); // skip errors
			g_object_unref(t);
			g_hash_table_iter_remove(&iter);
		}
		g_hash_table_unref(server_transfers);

		obexmanager_unregister_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		g_object_unref(agent);
		g_object_unref(manager);
	} else if (opp_arg) {
		opp_device_arg = argv[1];
		opp_file_arg = argv[2];

		/* Check that `file` is valid */
		if (!is_file(opp_file_arg, &error)) {
			exit_if_error(error);
		}

		gchar * files_to_send[] = {NULL, NULL};
		files_to_send[0] = g_path_is_absolute(opp_file_arg) ? g_strdup(opp_file_arg) : get_absolute_path(opp_file_arg);

		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		gchar *dst_address = NULL;
		if (g_regex_match_simple("^\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}$", opp_device_arg, 0, 0)) {
			dst_address = g_strdup(opp_device_arg);
		} else {
			Device *device = find_device(adapter, opp_device_arg, &error);
			exit_if_error(error);
			dst_address = g_strdup(device_get_address(device));
			g_object_unref(device);
		}

		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);

		mainloop = g_main_loop_new(NULL, FALSE);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);
		g_signal_connect(agent, "AgentReleased", G_CALLBACK(agent_released), mainloop);

		/* Sending file(s) */
		obexclient_send_files(client, device_dict, files_to_send, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Sending files process here ?? */

		g_main_loop_unref(mainloop);

		g_object_unref(agent);
		g_object_unref(client);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
		g_free(files_to_send[0]);
		files_to_send[0] = NULL;
	} else if (ftp_arg) {
		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		Device *device = find_device(adapter, ftp_arg, &error);
		exit_if_error(error);
		gchar *dst_address = g_strdup(device == NULL ? ftp_arg : device_get_address(device));

		g_object_unref(device);
		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		GValue target_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_init(&target_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_value_set_string(&target_v, "FTP");
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);
		g_hash_table_insert(device_dict, "Target", &target_v);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);
		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);

		/* Create FTP session */
		gchar *session_path = obexclient_create_session(client, device_dict, &error);
		exit_if_error(error);

		OBEXClientFileTransfer *ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
		g_free(session_path);

		g_print("FTP session opened\n");

		while (TRUE) {
			gchar *cmd;
			/*
			cmd = readline("> ");
			if (cmd == NULL) {
				continue;
			} else {
				add_history(cmd);
			}
			*/
			gint f_argc;
			gchar **f_argv;
			/* Parsing command line */
			if (!g_shell_parse_argv(cmd, &f_argc, &f_argv, &error)) {
				g_print("%s\n", error->message);
				g_error_free(error);
				error = NULL;

				g_free(cmd);
				continue;
			}

			/* Execute commands */
			if (g_strcmp0(f_argv[0], "cd") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_change_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mkdir") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_create_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "ls") == 0) {
				if (f_argc != 1) {
					g_print("invalid arguments\n");
				} else {
					GPtrArray *folders = obexclient_file_transfer_list_folder(ftp_session, &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						for (int i = 0; i < folders->len; i++) {
							GHashTable *el = g_ptr_array_index(folders, i);
							g_print(
									"%s\t%llu\t%s\n",
									g_value_get_string(g_hash_table_lookup(el, "Type")),
									G_VALUE_HOLDS_UINT64(g_hash_table_lookup(el, "Size")) ?
									g_value_get_uint64(g_hash_table_lookup(el, "Size")) :
									0,
									g_value_get_string(g_hash_table_lookup(el, "Name"))
									);
						}
					}

					if (folders) g_ptr_array_unref(folders);

					/*obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
					exit_if_error(error);
					g_object_unref(ftp_session);
					session_path = obexclient_create_session(client, device_dict, &error);
					exit_if_error(error);
					ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
					g_free(session_path);*/

				}
			} else if (g_strcmp0(f_argv[0], "get") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_dst_path = get_absolute_path(f_argv[2]);
					gchar *dir = g_path_get_dirname(abs_dst_path);
					if (!is_dir(dir, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_get_file(ftp_session, abs_dst_path, f_argv[1], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(dir);
					g_free(abs_dst_path);
				}
			} else if (g_strcmp0(f_argv[0], "put") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_src_path = get_absolute_path(f_argv[1]);
					if (!is_file(abs_src_path, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_put_file(ftp_session, abs_src_path, f_argv[2], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(abs_src_path);
				}
			} else if (g_strcmp0(f_argv[0], "cp") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_copy_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mv") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_move_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "rm") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_delete(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "help") == 0) {
				g_print(
						"help\t\t\tShow this message\n"
						"exit\t\t\tClose FTP session\n"
						"cd <folder>\t\tChange the current folder of the remote device\n"
						"mkdir <folder>\t\tCreate a new folder in the remote device\n"
						"ls\t\t\tList folder contents\n"
						"get <src> <dst>\t\tCopy the src file (from remote device) to the dst file (on local filesystem)\n"
						"put <src> <dst>\t\tCopy the src file (from local filesystem) to the dst file (on remote device)\n"
						"cp <src> <dst>\t\tCopy a file within the remote device from src file to dst file\n"
						"mv <src> <dst>\t\tMove a file within the remote device from src file to dst file\n"
						"rm <target>\t\tDeletes the specified file/folder\n"
						);
			} else if (g_strcmp0(f_argv[0], "exit") == 0 || g_strcmp0(f_argv[0], "quit") == 0) {
				obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
				exit_if_error(error);

				g_strfreev(f_argv);
				g_free(cmd);
				break;
			} else {
				g_print("invalid command\n");
			}

			g_strfreev(f_argv);
			g_free(cmd);
		}

		g_object_unref(agent);
		g_object_unref(client);
		g_object_unref(ftp_session);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_value_unset(&target_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
	}

	dbus_disconnect();

	exit(EXIT_SUCCESS);
}
コード例 #23
0
static GstFlowReturn
gst_rtp_rtx_receive_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
{
  GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (parent);
  GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
  GstFlowReturn ret = GST_FLOW_OK;
  GstBuffer *new_buffer = NULL;
  guint32 ssrc = 0;
  gpointer ssrc1 = 0;
  guint32 ssrc2 = 0;
  guint16 seqnum = 0;
  guint16 orign_seqnum = 0;
  guint8 payload_type = 0;
  guint8 origin_payload_type = 0;
  gboolean is_rtx;
  gboolean drop = FALSE;

  /* map current rtp packet to parse its header */
  gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp);
  ssrc = gst_rtp_buffer_get_ssrc (&rtp);
  seqnum = gst_rtp_buffer_get_seq (&rtp);
  payload_type = gst_rtp_buffer_get_payload_type (&rtp);

  /* check if we have a retransmission packet (this information comes from SDP) */
  GST_OBJECT_LOCK (rtx);

  rtx->last_time = GST_BUFFER_PTS (buffer);

  if (g_hash_table_size (rtx->seqnum_ssrc1_map) > 0) {
    GHashTableIter iter;
    gpointer key, value;

    g_hash_table_iter_init (&iter, rtx->seqnum_ssrc1_map);
    while (g_hash_table_iter_next (&iter, &key, &value)) {
      SsrcAssoc *assoc = value;

      /* remove association request if it is too old */
      if (GST_CLOCK_TIME_IS_VALID (rtx->last_time) &&
          GST_CLOCK_TIME_IS_VALID (assoc->time) &&
          assoc->time + ASSOC_TIMEOUT < rtx->last_time) {
        g_hash_table_iter_remove (&iter);
      }
    }
  }

  is_rtx =
      g_hash_table_lookup_extended (rtx->rtx_pt_map,
      GUINT_TO_POINTER (payload_type), NULL, NULL);

  /* if the current packet is from a retransmission stream */
  if (is_rtx) {
    /* increase our statistic */
    ++rtx->num_rtx_packets;

    /* read OSN in the rtx payload */
    orign_seqnum = GST_READ_UINT16_BE (gst_rtp_buffer_get_payload (&rtp));
    origin_payload_type =
        GPOINTER_TO_UINT (g_hash_table_lookup (rtx->rtx_pt_map,
            GUINT_TO_POINTER (payload_type)));

    /* first we check if we already have associated this retransmission stream
     * to a master stream */
    if (g_hash_table_lookup_extended (rtx->ssrc2_ssrc1_map,
            GUINT_TO_POINTER (ssrc), NULL, &ssrc1)) {
      GST_DEBUG_OBJECT (rtx,
          "packet is from retransmission stream %" G_GUINT32_FORMAT
          " already associated to master stream %" G_GUINT32_FORMAT, ssrc,
          GPOINTER_TO_UINT (ssrc1));
      ssrc2 = ssrc;
    } else {
      SsrcAssoc *assoc;

      /* the current retransmitted packet has its rtx stream not already
       * associated to a master stream, so retrieve it from our request
       * history */
      if (g_hash_table_lookup_extended (rtx->seqnum_ssrc1_map,
              GUINT_TO_POINTER (orign_seqnum), NULL, (gpointer *) & assoc)) {
        GST_DEBUG_OBJECT (rtx,
            "associate retransmitted stream %" G_GUINT32_FORMAT
            " to master stream %" G_GUINT32_FORMAT " thanks to packet %"
            G_GUINT16_FORMAT "", ssrc, assoc->ssrc, orign_seqnum);
        ssrc1 = GUINT_TO_POINTER (assoc->ssrc);
        ssrc2 = ssrc;

        /* just put a guard */
        if (GPOINTER_TO_UINT (ssrc1) == ssrc2)
          GST_WARNING_OBJECT (rtx, "RTX receiver ssrc2_ssrc1_map bad state, "
              "ssrc %" G_GUINT32_FORMAT " are the same\n", ssrc);

        /* free the spot so that this seqnum can be used to do another
         * association */
        g_hash_table_remove (rtx->seqnum_ssrc1_map,
            GUINT_TO_POINTER (orign_seqnum));

        /* actually do the association between rtx stream and master stream */
        g_hash_table_insert (rtx->ssrc2_ssrc1_map, GUINT_TO_POINTER (ssrc2),
            ssrc1);

        /* also do the association between master stream and rtx stream
         * every ssrc are unique so we can use the same hash table
         * for both retrieving the ssrc1 from ssrc2 and also ssrc2 from ssrc1
         */
        g_hash_table_insert (rtx->ssrc2_ssrc1_map, ssrc1,
            GUINT_TO_POINTER (ssrc2));

      } else {
        /* we are not able to associate this rtx packet with a master stream */
        GST_DEBUG_OBJECT (rtx,
            "drop rtx packet because its orign_seqnum %" G_GUINT16_FORMAT
            " is not in pending retransmission requests", orign_seqnum);
        drop = TRUE;
      }
    }
  }

  /* if not dropped the packet was successfully associated */
  if (is_rtx && !drop)
    ++rtx->num_rtx_assoc_packets;

  GST_OBJECT_UNLOCK (rtx);

  /* just drop the packet if the association could not have been made */
  if (drop) {
    gst_rtp_buffer_unmap (&rtp);
    gst_buffer_unref (buffer);
    return GST_FLOW_OK;
  }

  /* create the retransmission packet */
  if (is_rtx)
    new_buffer =
        _gst_rtp_buffer_new_from_rtx (&rtp, GPOINTER_TO_UINT (ssrc1),
        orign_seqnum, origin_payload_type);

  gst_rtp_buffer_unmap (&rtp);

  /* push the packet */
  if (is_rtx) {
    gst_buffer_unref (buffer);
    GST_LOG_OBJECT (rtx, "push packet seqnum:%" G_GUINT16_FORMAT
        " from a restransmission stream ssrc2:%" G_GUINT32_FORMAT " (src %"
        G_GUINT32_FORMAT ")", orign_seqnum, ssrc2, GPOINTER_TO_UINT (ssrc1));
    ret = gst_pad_push (rtx->srcpad, new_buffer);
  } else {
    GST_LOG_OBJECT (rtx, "push packet seqnum:%" G_GUINT16_FORMAT
        " from a master stream ssrc: %" G_GUINT32_FORMAT, seqnum, ssrc);
    ret = gst_pad_push (rtx->srcpad, buffer);
  }

  return ret;
}
コード例 #24
0
static void
get_track_list (RBMtpThread *thread, RBMtpThreadTask *task)
{
	RBMtpTrackListCallback cb = task->callback;
	gboolean device_forgets_albums = TRUE;
	GHashTable *update_albums = NULL;
	LIBMTP_track_t *tracks = NULL;
	LIBMTP_album_t *albums;
	LIBMTP_album_t *album;

	/* get all the albums */
	albums = LIBMTP_Get_Album_List (thread->device);
	rb_mtp_thread_report_errors (thread, FALSE);
	if (albums != NULL) {
		LIBMTP_album_t *album;

		for (album = albums; album != NULL; album = album->next) {
			if (album->name == NULL)
				continue;

			rb_debug ("album: %s, %d tracks", album->name, album->no_tracks);
			g_hash_table_insert (thread->albums, album->name, album);
			if (album->no_tracks != 0) {
				device_forgets_albums = FALSE;
			}
		}

		if (device_forgets_albums) {
			rb_debug ("stupid mtp device detected.  will rebuild all albums.");
		}
	} else {
		rb_debug ("No albums");
		device_forgets_albums = FALSE;
	}

	tracks = LIBMTP_Get_Tracklisting_With_Callback (thread->device, NULL, NULL);
	rb_mtp_thread_report_errors (thread, FALSE);
	if (tracks == NULL) {
		rb_debug ("no tracks on the device");
	} else if (device_forgets_albums) {
		LIBMTP_track_t *track;
	       
		rb_debug ("rebuilding albums");
		update_albums = g_hash_table_new (g_direct_hash, g_direct_equal);
		for (track = tracks; track != NULL; track = track->next) {
			if (track->album != NULL) {
				gboolean new_album = FALSE;
				album = add_track_to_album (thread, track->album, track->item_id, track->storage_id, &new_album);
				g_hash_table_insert (update_albums, album, GINT_TO_POINTER (new_album));
			}
		}
		rb_debug ("finished rebuilding albums");
	}

	cb (tracks, task->user_data);
	/* the callback owns the tracklist */

	if (device_forgets_albums) {
		GHashTableIter iter;
		gpointer album_ptr;
		gpointer new_album_ptr;

		rb_debug ("writing rebuilt albums back to the device");
		g_hash_table_iter_init (&iter, update_albums);
		while (g_hash_table_iter_next (&iter, &album_ptr, &new_album_ptr)) {
			album = album_ptr;
			rb_debug ("writing album \"%s\"", album->name);
			write_album_to_device (thread, album, GPOINTER_TO_INT (new_album_ptr));
		}
		g_hash_table_destroy (update_albums);

		rb_debug ("removing remaining empty albums");
		g_hash_table_iter_init (&iter, thread->albums);
		while (g_hash_table_iter_next (&iter, NULL, &album_ptr)) {
			int ret;

			album = album_ptr;
			if (album->no_tracks == 0) {
				rb_debug ("pruning empty album \"%s\"", album->name); 
				ret = LIBMTP_Delete_Object (thread->device, album->album_id);
				if (ret != 0) {
					rb_mtp_thread_report_errors (thread, FALSE);
				}
				g_hash_table_iter_remove (&iter);
			}
		}

		rb_debug ("finished updating albums on the device");
	}
}
コード例 #25
0
ファイル: services_task_check.c プロジェクト: korween/oio-sds
static void
_detect_obsolete_services(struct namespace_data_s *ns_data)
{
	guint counter;
	time_t time_now, time_down, time_broken;
	GHashTableIter s_iterator;
	gpointer s_k, s_v;
	gchar *str_key;
	struct service_info_s *si;


	time_now = g_get_real_time()/1000000;
	time_down = time_now - 5;
	time_broken = time_now - 30;
	counter = 0;
	
	if (!ns_data->configured) {
		return;
	}

	/*move services from UP to DOWN */
	g_hash_table_iter_init(&s_iterator, ns_data->local_services);
	while (g_hash_table_iter_next(&s_iterator, &s_k, &s_v)) {
		str_key = s_k;
		si = s_v;
		si->score.value = -2;/*score not set*/
		if (si->score.timestamp < time_down) {
			gchar str_addr[STRLEN_ADDRINFO];

			addr_info_to_string(&(si->addr),str_addr,sizeof(str_addr));
			DEBUG("Timeout on service [%s/%s/%s] (%"G_GINT32_FORMAT" < %ld) --> DOWN",
				si->ns_name, si->type, str_addr, si->score.timestamp, time_down);

			g_hash_table_iter_steal(&s_iterator);
			g_hash_table_insert(ns_data->down_services, str_key, si);

			invalidate_conscience_service(ns_data,si);
			zero_service_stats(si->tags);
			service_tag_set_value_boolean(service_info_ensure_tag(si->tags,"tag.up"), FALSE);

			counter++;
		}
	}

	/*remove services DOWN from a long time ago */
	g_hash_table_iter_init(&s_iterator, ns_data->down_services);
	while (g_hash_table_iter_next(&s_iterator, &s_k, &s_v)) {
		str_key = s_k;
		si = s_v;
		si->score.value = -2;/*score not set*/
		if (si->score.timestamp < time_broken) {
			gchar str_addr[STRLEN_ADDRINFO];

			addr_info_to_string(&(si->addr),str_addr,sizeof(str_addr));
			DEBUG("Service obsolete [%s/%s/%s] --> DELETED", si->ns_name, si->type, str_addr);

			g_hash_table_iter_remove(&s_iterator);
			counter++;
		}
		else
			zero_service_stats(si->tags);
	}

	if (counter)
		DEBUG("[task_id=%s] %u services states have changed", TASK_ID, counter);
}
コード例 #26
0
ファイル: render.c プロジェクト: LaCucuracha/libvob-c
void gfx_render(struct gfx_window *w, 
		enum GFX_ANIM_TYPE chg, 
		long anim_time)
{
	//DBG("%d",chg)
	struct timespec now;

	struct gfx_callbacks *cb = gfx_callbacks(w);
	struct gfx_render *render = w->render;

	if (!cb->generate_scene)
		return;

	switch (chg) {
	case CHG_SWITCH_VOB_SCENE: {
		render->prev = render->current;
		render->current = cb->generate_scene(w);
		clock_gettime(CLOCK_REALTIME, &render->t0);
		memcpy(&render->t1, &render->t0, sizeof(struct timespec));
		break;
	}
	case CHG_ANIMATE: {
		render->prev = render->current;
		render->current = cb->generate_scene(w);

		clock_gettime(CLOCK_REALTIME, &render->t0);
		memcpy(&render->t1, &render->t0, sizeof(struct timespec));
		render->t1.tv_sec += anim_time / 1000;
		render->t1.tv_nsec += (anim_time % 1000)*1000;
		DBG("t0 %d.%d  t1 %d.%d",render->t0.tv_sec ,render->t0.tv_nsec, render->t1.tv_sec ,render->t1.tv_nsec )
		break;
	}
        case CHG_RERENDER:
	default:
		break;
	}

	// just render in here.

	clock_gettime(CLOCK_REALTIME, &now);
	render->t_since_ms = (now.tv_sec - render->t_frame.tv_sec) * 1000
		+ (now.tv_nsec - render->t_frame.tv_nsec)/1000000.0f;
	render->t_frame.tv_sec = now.tv_sec;
	render->t_frame.tv_nsec = now.tv_nsec;

	if (time_cmp(render->t0, render->t1) < 0 
		&& time_cmp(render->t_frame, render->t1) < 0) {
		//float d = get_anim_fract(render, &now);
		//DBG("fract: %f",render->t_frame)
		gfx_render_frame(w);
		//w->anim_render(w, d);
	} else {
		// no anim...

		GHashTableIter iter;
		gpointer key, value;

		g_hash_table_iter_init (&iter, render->current->anim_set);
		while (g_hash_table_iter_next (&iter, &key, &value)) 
		{
			float ms = render->t_since_ms;
			LobAnimModel *m = (LobAnimModel *)key;
			if (m->tick(m, &now)) {
				g_hash_table_iter_remove(&iter);
				DBG("remove %p",m);
			}
		}



		//printf("no anim\n");
		w->single_render(w, render->current);
	}

}