static gchar* _get_timestamp()
{
    GDateTime* now = g_date_time_new_now_utc();
    gint64 timestamp = g_date_time_to_unix(now);
    g_date_time_unref(now);
    return g_strdup_printf("%"G_GINT64_FORMAT, timestamp);
}
static void
time_converter(GBinding* bind,
               const GValue* from,
               GValue* to,
               gpointer udata)
{
    gchar* label = NULL;
    GDateTime* now_time;
    GDateTime* stream_started_time;
    GTimeSpan dif;

    if (g_value_get_pointer(from) != NULL)
    {
        now_time = g_date_time_new_now_utc();
        stream_started_time = (GDateTime*) g_value_get_pointer(from);

        dif = g_date_time_difference(now_time, stream_started_time);

        if (dif > G_TIME_SPAN_HOUR)
            label = g_strdup_printf("%2.1fh", (gdouble) dif / G_TIME_SPAN_HOUR);
        else
            label = g_strdup_printf("%ldm", dif / G_TIME_SPAN_MINUTE);

        g_date_time_unref(now_time);
    }

    g_value_take_string(to, label);
}
Example #3
0
time64
gnc_time_utc (time64 *tbuf)
{
     GDateTime *gdt = g_date_time_new_now_utc ();
     time64 secs = g_date_time_to_unix (gdt);
     g_date_time_unref (gdt);
     if (tbuf != NULL)
	  *tbuf = secs;
     return secs;
}
Example #4
0
gint64
utils_timestamp_now(void)
{
    gint64 timestamp;
    GDateTime* now;

    now = g_date_time_new_now_utc();
    timestamp = g_date_time_to_unix(now);
    g_date_time_unref(now);

    return timestamp;
}
Example #5
0
void
sv_ev_roster_received(void)
{
    if (prefs_get_boolean(PREF_ROSTER)) {
        ui_show_roster();
    }

    char *account_name = session_get_account_name();

#ifdef HAVE_LIBGPGME
    // check pgp key valid if specified
    ProfAccount *account = accounts_get_account(account_name);
    if (account && account->pgp_keyid) {
        char *err_str = NULL;
        if (!p_gpg_valid_key(account->pgp_keyid, &err_str)) {
            cons_show_error("Invalid PGP key ID specified: %s, %s", account->pgp_keyid, err_str);
        }
        free(err_str);
    }
    account_free(account);
#endif

    // send initial presence
    resource_presence_t conn_presence = accounts_get_login_presence(account_name);
    char *last_activity_str = accounts_get_last_activity(account_name);
    if (last_activity_str) {
        GDateTime *nowdt = g_date_time_new_now_utc();

        GTimeVal lasttv;
        gboolean res = g_time_val_from_iso8601(last_activity_str, &lasttv);
        if (res) {
            GDateTime *lastdt = g_date_time_new_from_timeval_utc(&lasttv);
            GTimeSpan diff_micros = g_date_time_difference(nowdt, lastdt);
            int diff_secs = (diff_micros / 1000) / 1000;
            if (prefs_get_boolean(PREF_LASTACTIVITY)) {
                cl_ev_presence_send(conn_presence, NULL, diff_secs);
            } else {
                cl_ev_presence_send(conn_presence, NULL, 0);
            }
            g_date_time_unref(lastdt);
        } else {
            cl_ev_presence_send(conn_presence, NULL, 0);
        }

        free(last_activity_str);
        g_date_time_unref(nowdt);
    } else {
        cl_ev_presence_send(conn_presence, NULL, 0);
    }

    const char *fulljid = connection_get_fulljid();
    plugins_on_connect(account_name, fulljid);
}
gint64
empathy_time_get_current (void)
{
  GDateTime *now;
  gint64 result;

  now = g_date_time_new_now_utc ();
  result = g_date_time_to_unix (now);
  g_date_time_unref (now);

  return result;
}
static GSignondDictionary* _respond_with_stored_token(GSignondDictionary *token)
{
    if (token == NULL)
        return FALSE;
    
    gint64 duration;
    gboolean has_duration = gsignond_dictionary_get_int64(token, 
                                                          "Duration",
                                                          &duration);
    gint64 timestamp;
    gboolean has_timestamp = gsignond_dictionary_get_int64(token, 
                                                          "Timestamp",
                                                          &timestamp);
    gint64 expires_in = 0;
    
    if (has_duration && has_timestamp) {
        GDateTime* now = g_date_time_new_now_utc();
        expires_in = duration + timestamp - g_date_time_to_unix(now);
        g_date_time_unref(now);
        if (expires_in < 0)
            return FALSE;
    }
    
    GVariant* token_variant = gsignond_dictionary_get(token, "AccessToken");
    if (token_variant != NULL) {
        GSignondSessionData* response = gsignond_dictionary_new();
        gsignond_dictionary_set(response, "AccessToken", token_variant);
        GVariant* refresh_token = gsignond_dictionary_get(token, "RefreshToken");
        if (refresh_token != NULL)
            gsignond_dictionary_set(response, "RefreshToken", refresh_token);
        GVariant* token_type = gsignond_dictionary_get(token, "TokenType");
        if (token_type != NULL)
            gsignond_dictionary_set(response, "TokenType", token_type);
        GVariant* token_params = gsignond_dictionary_get(token, "TokenParameters");
        if (token_params != NULL)
            gsignond_dictionary_set(response, "TokenParameters", token_params);
        const gchar* token_scope_s = gsignond_dictionary_get_string(token, "Scope");
        if (token_scope_s != NULL) {
            gsignond_dictionary_set_string(response, "Scope", token_scope_s);
        }
        if (has_duration) {
            gsignond_dictionary_set_int64(response, "Duration", duration);
        }
        if (has_timestamp) {
            gsignond_dictionary_set_int64(response, "Timestamp", timestamp);
        }
        return response;
    }
    return NULL;
}
Example #8
0
static void
gt_log(const gchar* domain,
       GLogLevelFlags _level,
       const gchar* msg,
       gpointer udata)
{
    gchar* level;
    GDateTime* date = NULL;
    gchar* time_fmt = NULL;

    if (_level > 8*pow(2, LOG_LEVEL))
        return;

    switch (_level)
    {
        case G_LOG_LEVEL_ERROR:
            level = "Error";
            break;
        case G_LOG_LEVEL_CRITICAL:
            level = "Critical";
            break;
        case G_LOG_LEVEL_WARNING:
            level = "Warning";
            break;
        case G_LOG_LEVEL_MESSAGE:
            level = "Message";
            break;
        case G_LOG_LEVEL_INFO:
            level = "Info";
            break;
        case G_LOG_LEVEL_DEBUG:
            level = "Debug";
            break;
        case G_LOG_LEVEL_MASK:
            level = "All";
            break;
        default:
            level = "Unkown";
            break;
    }

    date = g_date_time_new_now_utc();
    time_fmt = g_date_time_format(date, "%H:%M:%S");

    g_print("[%s] %s - %s : \"%s\"\n", time_fmt, domain, level, msg);

    g_free(time_fmt);
    g_date_time_unref(date);
}
Example #9
0
void
accounts_set_last_activity(const char *const account_name)
{
    if (accounts_account_exists(account_name)) {
        GDateTime *nowdt = g_date_time_new_now_utc();
        GTimeVal nowtv;
        gboolean res = g_date_time_to_timeval(nowdt, &nowtv);
        g_date_time_unref(nowdt);

        if (res) {
            char *timestr = g_time_val_to_iso8601(&nowtv);
            g_key_file_set_string(accounts, account_name, "last.activity", timestr);
            free(timestr);
            _save_accounts();
        }
    }
}
static void
update_last_used (CEPageDetails *page, NMConnection *connection)
{
        gchar *last_used = NULL;
        GDateTime *now = NULL;
        GDateTime *then = NULL;
        gint days;
        GTimeSpan diff;
        guint64 timestamp;
        NMSettingConnection *s_con;

        s_con = nm_connection_get_setting_connection (connection);
        if (s_con == NULL)
                goto out;
        timestamp = nm_setting_connection_get_timestamp (s_con);
        if (timestamp == 0) {
                last_used = g_strdup (_("Never"));
                goto out;
        }

        /* calculate the amount of time that has elapsed */
        now = g_date_time_new_now_utc ();
        then = g_date_time_new_from_unix_utc (timestamp);

        diff = g_date_time_difference  (now, then);
        days = diff / G_TIME_SPAN_DAY;
        if (days == 0)
                last_used = g_strdup (_("Today"));
        else if (days == 1)
                last_used = g_strdup (_("Yesterday"));
        else
                last_used = g_strdup_printf (ngettext ("%i day ago", "%i days ago", days), days);
out:
        panel_set_device_widget_details (CE_PAGE (page)->builder, "last_used", last_used);
        if (now != NULL)
                g_date_time_unref (now);
        if (then != NULL)
                g_date_time_unref (then);
        g_free (last_used);
}
static gchar *
get_last_used_string (NMConnection *connection)
{
        gchar *last_used = NULL;
        GDateTime *now = NULL;
        GDateTime *then = NULL;
        gint days;
        GTimeSpan diff;
        guint64 timestamp;
        NMSettingConnection *s_con;

        s_con = nm_connection_get_setting_connection (connection);
        if (s_con == NULL)
                goto out;
        timestamp = nm_setting_connection_get_timestamp (s_con);
        if (timestamp == 0) {
                last_used = g_strdup (_("never"));
                goto out;
        }

        /* calculate the amount of time that has elapsed */
        now = g_date_time_new_now_utc ();
        then = g_date_time_new_from_unix_utc (timestamp);
        diff = g_date_time_difference  (now, then);
        days = diff / G_TIME_SPAN_DAY;
        if (days == 0)
                last_used = g_strdup (_("today"));
        else if (days == 1)
                last_used = g_strdup (_("yesterday"));
        else
                last_used = g_strdup_printf (ngettext ("%i day ago", "%i days ago", days), days);
out:
        if (now != NULL)
                g_date_time_unref (now);
        if (then != NULL)
                g_date_time_unref (then);

        return last_used;
}
Example #12
0
void TestShouldRenew() {
  GDateTime *now = g_date_time_new_now_utc();
  GDateTime *one_hour_ago = g_date_time_add_hours(now, -1);
  GDateTime *over_1w_ago = g_date_time_add_weeks(one_hour_ago, -1);
  CachePolicy *policy = CachePolicyNew();
  CacheEntry *entry = CacheEntryNew();

  CachePolicySetValue(policy, "renew", "1w", NULL);

  entry->last_verified = one_hour_ago;
  g_assert(!CachePolicyShouldRenew(policy, entry, now));

  entry->last_verified = over_1w_ago;
  g_assert(CachePolicyShouldRenew(policy, entry, now));

  entry->last_verified = NULL;
  CacheEntryUnref(entry);
  CachePolicyUnref(policy);
  g_date_time_unref(now);
  g_date_time_unref(one_hour_ago);
  g_date_time_unref(over_1w_ago);
}
Example #13
0
/**
 * CacheEntryPasswordValidate:
 * @self: Instance with salt/hash to check @password against.
 * @password: Password to check.
 * @error: (out)(allow-none): Error return location or #NULL.
 *
 * Returns: #TRUE if the password matches, or #FALSE if there was an error and
 * @error was set. Not matching is considered an error.
 */
gboolean CacheEntryPasswordValidate(CacheEntry *self, const gchar *password,
                                    GError **error) {
  GBytes *hash = NULL;
  GDateTime *now = NULL;
  gboolean result = FALSE;

  if (!self->salt || !self->hash) {
    g_set_error(error, CACHE_ENTRY_ERROR, CACHE_ENTRY_EMPTY_ERROR,
                "No cached password is available");
    return FALSE;
  }

  g_assert(self->salt);
  g_assert(password);
  g_assert(strlen(password) > 0);
  hash = CacheUtilHashPassword(self->algorithm, self->salt, password);
  if (!hash) {
    g_set_error(error, CACHE_ENTRY_ERROR, CACHE_ENTRY_CORRUPT_ERROR,
                "Unknow hash algorithm selected");
    return FALSE;
  }

  now = g_date_time_new_now_utc();
  CacheEntryUpdateTime(&self->last_tried, now);

  if (g_bytes_equal(hash, self->hash)) {
    CacheEntryUpdateTime(&self->last_used, now);
    self->tries = 0;
    result = TRUE;
  } else {
    self->tries++;
    g_set_error(error, CACHE_ENTRY_ERROR, CACHE_ENTRY_PASSWORD_ERROR,
                "Password doesn't match cached value");
  }

  g_bytes_unref(hash);
  g_date_time_unref(now);
  return result;
}
Example #14
0
/**
 * egg_date_time_format_for_display:
 * @self: A #GDateTime
 *
 * Helper function to "humanize" a #GDateTime into a relative time
 * relationship string.
 *
 * Returns: (transfer full): A newly allocated string describing the
 *   date and time imprecisely such as "Yesterday".
 */
gchar *
egg_date_time_format_for_display (GDateTime *self)
{
  GDateTime *now;
  GTimeSpan diff;
  gint years;

  /*
   * TODO:
   *
   * There is probably a lot more we can do here to be friendly for
   * various locales, but this will get us started.
   */

  g_return_val_if_fail (self != NULL, NULL);

  now = g_date_time_new_now_utc ();
  diff = g_date_time_difference (now, self) / G_USEC_PER_SEC;

  if (diff < 0)
    return g_strdup ("");
  else if (diff < (60 * 45))
    return g_strdup (_("Just now"));
  else if (diff < (60 * 90))
    return g_strdup (_("An hour ago"));
  else if (diff < (60 * 60 * 24 * 2))
    return g_strdup (_("Yesterday"));
  else if (diff < (60 * 60 * 24 * 7))
    return g_date_time_format (self, "%A");
  else if (diff < (60 * 60 * 24 * 365))
    return g_date_time_format (self, "%B");
  else if (diff < (60 * 60 * 24 * 365 * 1.5))
    return g_strdup (_("About a year ago"));

  years = MAX (2, diff / (60 * 60 * 24 * 365));

  return g_strdup_printf (ngettext ("About %u year ago", "About %u years ago", years), years);
}
Example #15
0
gchar *
VMTools_GetTimeAsString(void)
{
   gchar *timePrefix = NULL;
   GDateTime *utcTime = g_date_time_new_now_utc();

   if (utcTime != NULL) {
      gchar *dateFormat = g_date_time_format(utcTime, "%FT%T");

      if (dateFormat != NULL) {
         gint msec = g_date_time_get_microsecond(utcTime) / 1000;

         timePrefix = g_strdup_printf("%s.%03dZ", dateFormat, msec);

         g_free(dateFormat);
         dateFormat = NULL;
      }

      g_date_time_unref(utcTime);
   }

   return timePrefix;
}
gchar  *
empathy_time_to_string_relative (gint64 t)
{
  GDateTime *now, *then;
  gint   seconds;
  GTimeSpan delta;
  gchar *result;

  now = g_date_time_new_now_utc ();
  then = g_date_time_new_from_unix_utc (t);

  delta = g_date_time_difference (now, then);
  seconds = delta / G_TIME_SPAN_SECOND;

  if (seconds > 0)
    result = empathy_duration_to_string (seconds);
  else
    result = g_strdup (_("in the future"));

  g_date_time_unref (now);
  g_date_time_unref (then);

  return result;
}
Example #17
0
/**
 * CacheEntryPasswordSet:
 * @self: Instance to update.
 * @password: Password used in the new #CacheEntry.hash.
 * @error: (out)(allow-none): Error return location or #NULL.
 *
 * Generates a new salt, sets hash with the salt and @password, and updates all
 * of the last_* values with the current time
 *
 * Returns: #TRUE if #CacheEntry.salt and #CacheEntry.hash were updated, or
 * #FALSE if neither was updated.
 */
gboolean CacheEntryPasswordSet(CacheEntry *self, const gchar *password,
                               GError **error) {
  GDateTime *now = NULL;
  GBytes *salt = NULL;
  GBytes *hash = NULL;

  salt = CacheUtilRandomBytes(CACHE_ENTRY_DEFAULT_SALT_LENGTH);

  g_assert(salt);
  g_assert(password);
  g_assert(strlen(password) > 0);
  hash = CacheUtilHashPassword(self->algorithm, salt, password);
  if (!hash) {
    g_set_error(error, CACHE_ENTRY_ERROR, CACHE_ENTRY_CORRUPT_ERROR,
                "Unknow hash algorithm selected");
    g_bytes_unref(salt);
    return FALSE;
  }

  if (self->salt)
    g_bytes_unref(self->salt);
  self->salt = salt;

  if (self->hash)
    g_bytes_unref(self->hash);
  self->hash = hash;

  now = g_date_time_new_now_utc();
  CacheEntryUpdateTime(&self->last_verified, now);
  CacheEntryUpdateTime(&self->last_used, now);
  CacheEntryUpdateTime(&self->last_tried, now);
  g_date_time_unref(now);

  self->tries = 0;
  return TRUE;
}
Example #18
0
static void
cleaner_task_handler (GTask *task, gpointer source_object,
			gpointer task_data, GCancellable *cancellable)
{
	HevFileboxCleaner *self = HEV_FILEBOX_CLEANER (source_object);
    HevFileboxCleanerPrivate *priv = HEV_FILEBOX_CLEANER_GET_PRIVATE (self);
	gchar *fp_path = NULL, *fm_path = NULL;
	GFile *file = NULL;
	GFileEnumerator *file_enumerator = NULL;
	GFileInfo *file_info = NULL;

    g_debug ("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	fp_path = g_key_file_get_string (priv->config, "Module", "FilePoolPath", NULL);
	fm_path = g_key_file_get_string (priv->config, "Module", "FileMetaPath", NULL);

	/* enumerate file pool */
	file = g_file_new_for_path (fp_path);
	file_enumerator = g_file_enumerate_children (file,
				G_FILE_ATTRIBUTE_STANDARD_NAME","G_FILE_ATTRIBUTE_STANDARD_TYPE,
				G_FILE_QUERY_INFO_NONE, NULL, NULL);
	while (file_info = g_file_enumerator_next_file (file_enumerator, NULL, NULL)) {
		if (G_FILE_TYPE_REGULAR == g_file_info_get_file_type (file_info)) {
			gchar *meta_path = NULL;
			GKeyFile *meta = NULL;

			meta_path = g_build_filename (fm_path, g_file_info_get_name (file_info), NULL);
			meta = g_key_file_new ();
			if (g_key_file_load_from_file (meta, meta_path, G_KEY_FILE_NONE, NULL)) {
				gint64 exp = 0;
				GDateTime *now_date = NULL, *exp_date = NULL;

				exp = g_key_file_get_int64 (meta, "Meta", "ExpDate", NULL);
				now_date = g_date_time_new_now_utc ();
				exp_date = g_date_time_new_from_unix_utc (exp);

				/* compare date */
				if (1 == g_date_time_compare (now_date, exp_date)) {
					gchar *file_path = NULL;

					file_path = g_build_filename (fp_path,
								g_file_info_get_name (file_info), NULL);
					/* delete file and it's meta */
					g_unlink ((const gchar *) file_path);
					g_unlink ((const gchar *) meta_path);
					g_free (file_path);
				}

				g_date_time_unref (now_date);
				g_date_time_unref (exp_date);
			}
			g_key_file_unref (meta);
			g_free (meta_path);
		}
		g_object_unref (file_info);
	}
	g_object_unref (file_enumerator);
	g_object_unref (file);

	g_free (fp_path);
	g_free (fm_path);

	g_task_return_boolean (task, TRUE);
}
Example #19
0
static void
test_g_date_time (void)
{
  g_autoptr(GDateTime) val = g_date_time_new_now_utc ();
  g_assert (val != NULL);
}
Example #20
0
static void
file_ptr_array_foreach_write_meta_handler (gpointer data, gpointer user_data)
{
	GFile *file = G_FILE (data), *meta_file = NULL;
	GObject *scgi_task = G_OBJECT (user_data);
	GObject *request = NULL;
	GHashTable *req_htb = NULL;
	gchar *duration = NULL, *one_off = NULL, *rand_pass = NULL;
	GKeyFile *meta = NULL;
	GDateTime *crt_time = NULL, *exp_time = NULL;
	GFileOutputStream *file_ostream = NULL;
	guint64 dur = 0;

	g_debug ("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	request = hev_scgi_task_get_request (HEV_SCGI_TASK (scgi_task));
	req_htb = hev_scgi_request_get_header_hash_table (HEV_SCGI_REQUEST (request));

	duration = g_object_get_data (scgi_task, "duration");
	one_off = g_object_get_data (scgi_task, "one-off");
	rand_pass = g_object_get_data (scgi_task, "rand-pass");

	meta_file = g_object_get_data (G_OBJECT (file), "meta");
	g_file_delete (meta_file, NULL, NULL);
	meta = g_key_file_new ();

	/* set meta contents */
	crt_time = g_date_time_new_now_utc ();
	g_key_file_set_int64 (meta, "Meta", "CrtDate",
				g_date_time_to_unix (crt_time));
	if (duration) {
		dur = g_ascii_strtoull (duration, NULL, 10);
		if ((0 >= dur) || (7 < dur))
		  dur = 1;
	} else {
		dur = 1;
	}
	exp_time = g_date_time_add_days (crt_time, dur);
	g_key_file_set_int64 (meta, "Meta", "ExpDate",
				g_date_time_to_unix (exp_time));
	g_date_time_unref (exp_time);
	g_date_time_unref (crt_time);
	g_key_file_set_boolean (meta, "Meta", "OneOff", one_off ? TRUE : FALSE);
	g_key_file_set_string (meta, "Meta", "IP",
				g_hash_table_lookup (req_htb, "REMOTE_ADDR"));
	g_key_file_set_string (meta, "Meta", "RandPass", rand_pass);

	/* create and write to meta file */
	file_ostream = g_file_create (meta_file, G_FILE_CREATE_PRIVATE, NULL, NULL);
	if (file_ostream) {
		gchar *data = NULL;
		gsize length = 0;
		data = g_key_file_to_data (meta, &length, NULL);
		g_output_stream_write_all (G_OUTPUT_STREAM (file_ostream),
					data, length, NULL, NULL, NULL);
		g_free (data);
		g_object_unref (file_ostream);
	}

	g_key_file_unref (meta);
}
/**
 * gs_shell_overview_load:
 */
static void
gs_shell_overview_load (GsShellOverview *self)
{
	GsShellOverviewPrivate *priv = gs_shell_overview_get_instance_private (self);
	const gchar *category_of_day;
	g_autoptr(GDateTime) date = NULL;

	priv->empty = TRUE;

	date = g_date_time_new_now_utc ();
	switch (g_date_time_get_day_of_year (date) % 4) {
	case 0:
		category_of_day = "Audio";
		/* TRANSLATORS: this is a heading for audio applications which have been featured ('recommended') by the distribution */
		gtk_label_set_label (GTK_LABEL (priv->popular_rotating_heading), _("Recommended Audio Applications"));
		break;
	case 1:
		category_of_day = "Game";
		/* TRANSLATORS: this is a heading for games which have been featured ('recommended') by the distribution */
		gtk_label_set_label (GTK_LABEL (priv->popular_rotating_heading), _("Recommended Games"));
		break;
	case 2:
		category_of_day = "Graphics";
		/* TRANSLATORS: this is a heading for graphics applications which have been featured ('recommended') by the distribution */
		gtk_label_set_label (GTK_LABEL (priv->popular_rotating_heading), _("Recommended Graphics Applications"));
		break;
	case 3:
		category_of_day = "Office";
		/* TRANSLATORS: this is a heading for office applications which have been featured ('recommended') by the distribution */
		gtk_label_set_label (GTK_LABEL (priv->popular_rotating_heading), _("Recommended Office Applications"));
		break;
	default:
		g_assert_not_reached ();
		break;
	}
	g_free (priv->category_of_day);
	priv->category_of_day = g_strdup (category_of_day);

	if (!priv->loading_featured) {
		priv->loading_featured = TRUE;
		gs_plugin_loader_get_featured_async (priv->plugin_loader,
						     GS_PLUGIN_REFINE_FLAGS_DEFAULT,
						     priv->cancellable,
						     gs_shell_overview_get_featured_cb,
						     self);
		priv->refresh_count++;
	}

	if (!priv->loading_popular) {
		priv->loading_popular = TRUE;
		gs_plugin_loader_get_popular_async (priv->plugin_loader,
						    GS_PLUGIN_REFINE_FLAGS_DEFAULT,
						    priv->cancellable,
						    gs_shell_overview_get_popular_cb,
						    self);
		priv->refresh_count++;
	}

	if (!priv->loading_popular_rotating) {
		LoadData *load_data;
		g_autoptr(GsCategory) category = NULL;
		g_autoptr(GsCategory) featured_category = NULL;

		category = gs_category_new (NULL, category_of_day, NULL);
		featured_category = gs_category_new (category, "featured", NULL);

		load_data = g_slice_new0 (LoadData);
		load_data->category = g_object_ref (category);
		load_data->self = g_object_ref (self);

		priv->loading_popular_rotating = TRUE;
		gs_plugin_loader_get_category_apps_async (priv->plugin_loader,
		                                          featured_category,
		                                          GS_PLUGIN_REFINE_FLAGS_DEFAULT,
		                                          priv->cancellable,
		                                          gs_shell_overview_get_popular_rotating_cb,
		                                          load_data);
		priv->refresh_count++;
	}

	if (!priv->loading_categories) {
		priv->loading_categories = TRUE;
		gs_plugin_loader_get_categories_async (priv->plugin_loader,
						       GS_PLUGIN_REFINE_FLAGS_DEFAULT,
						       priv->cancellable,
						       gs_shell_overview_get_categories_cb,
						       self);
		priv->refresh_count++;
	}
}
static void _process_access_token(GSignondOauthPlugin *self,
                                GHashTable* params,
                                GError** error
                                 )
{
    const gchar* access_token = g_hash_table_lookup(params, "access_token");
    const gchar* token_type = g_hash_table_lookup(params, "token_type");
    if (access_token == NULL) {
        *error = g_error_new(GSIGNOND_ERROR,
                            GSIGNOND_ERROR_NOT_AUTHORIZED,
                            "No access token in response");
        return;
    }
    GHashTable* additional_token_params = _get_token_params(params, token_type);
    if (additional_token_params == NULL) {
        *error = g_error_new(GSIGNOND_ERROR,
                                GSIGNOND_ERROR_NOT_AUTHORIZED,
                                "Unknown access token type %s", token_type);
        return;
    }
    GSignondDictionary* token_dict = gsignond_dictionary_new();
    gsignond_dictionary_set_string(token_dict, "AccessToken", access_token);
    gsignond_dictionary_set_string(token_dict, "TokenType", token_type);
    gsignond_dictionary_set(token_dict, "TokenParameters", 
                            gsignond_dictionary_to_variant(
                                additional_token_params));
    g_hash_table_unref(additional_token_params);

    GDateTime* now = g_date_time_new_now_utc();
    gsignond_dictionary_set_int64(token_dict, "Timestamp", g_date_time_to_unix(now));
    g_date_time_unref(now);

    const gchar* duration_s = g_hash_table_lookup(params, "expires_in");
    if (duration_s != NULL) {
        gchar* endptr;
        gint64 duration = g_ascii_strtoll(duration_s, &endptr, 10);
        if (endptr[0] == '\0')
            gsignond_dictionary_set_int64(token_dict, "Duration", duration);
    }

    const gchar* scope_s = g_hash_table_lookup(params, "scope");
    if (scope_s != NULL) {
        gsignond_dictionary_set_string(token_dict, "Scope", scope_s);
    } else {
        GVariant* scope_v = gsignond_dictionary_get(self->oauth2_request, 
                                                    "Scope");
        if (scope_v != NULL)
            gsignond_dictionary_set(token_dict, "Scope", scope_v);
        else
            gsignond_dictionary_set_string(token_dict, "Scope", "");
    }
    
    const gchar* client_id = gsignond_dictionary_get_string(self->oauth2_request, "ClientId");

    const gchar* refresh_token = g_hash_table_lookup(params, "refresh_token");
    if (refresh_token != NULL)
        gsignond_dictionary_set_string(token_dict, "RefreshToken", refresh_token);
    else {
        // reuse previously issued refresh token
        GSignondDictionary* old_token = _find_token_in_cache(self->token_cache,
                                                             client_id,
                                                             NULL);
        if (old_token != NULL) {
            const gchar* old_refresh_token = gsignond_dictionary_get_string(
                old_token, "RefreshToken");
            if (old_refresh_token != NULL)
                gsignond_dictionary_set_string(token_dict, "RefreshToken",
                                                   old_refresh_token);
        }
        gsignond_dictionary_unref(old_token);
    }
    _insert_token_in_cache(self->token_cache, token_dict, client_id);
    
    gsignond_plugin_store(GSIGNOND_PLUGIN(self), self->token_cache);
    
    _do_reset_oauth2(self);
    gsignond_plugin_response_final(GSIGNOND_PLUGIN(self), token_dict);
    gsignond_dictionary_unref(token_dict);
}
Example #23
0
GstDateTime *
gst_date_time_new_now_utc (void)
{
  return gst_date_time_new_from_gdatetime (g_date_time_new_now_utc ());
}
Example #24
0
/**
 * gst_date_time_new_from_iso8601_string:
 * @string: ISO 8601-formatted datetime string.
 *
 * Tries to parse common variants of ISO-8601 datetime strings into a
 * #GstDateTime. Possible input formats are (for example):
 * 2012-06-30T22:46:43Z, 2012, 2012-06, 2012-06-30, 2012-06-30T22:46:43-0430,
 * 2012-06-30T22:46Z, 2012-06-30T22:46-0430, 2012-06-30 22:46,
 * 2012-06-30 22:46:43, 2012-06-00, 2012-00-00, 2012-00-30, 22:46:43Z, 22:46Z,
 * 22:46:43-0430, 22:46-0430, 22:46:30, 22:46
 * If no date is provided, it is assumed to be "today" in the timezone
 * provided (if any), otherwise UTC.
 *
 * Free-function: gst_date_time_unref
 *
 * Returns: (transfer full) (nullable): a newly created #GstDateTime,
 * or %NULL on error
 */
GstDateTime *
gst_date_time_new_from_iso8601_string (const gchar * string)
{
  gint year = -1, month = -1, day = -1, hour = -1, minute = -1;
  gint gmt_offset_hour = -99, gmt_offset_min = -99;
  gdouble second = -1.0;
  gfloat tzoffset = 0.0;
  guint64 usecs;
  gint len, ret;

  g_return_val_if_fail (string != NULL, NULL);

  GST_DEBUG ("Parsing '%s' into a datetime", string);

  len = strlen (string);

  /* The input string is expected to start either with a year (4 digits) or
   * with an hour (2 digits). Hour must be followed by minute. In any case,
   * the string must be at least 4 characters long and start with 2 digits */
  if (len < 4 || !g_ascii_isdigit (string[0]) || !g_ascii_isdigit (string[1]))
    return NULL;

  if (g_ascii_isdigit (string[2]) && g_ascii_isdigit (string[3])) {
    ret = sscanf (string, "%04d-%02d-%02d", &year, &month, &day);

    if (ret == 0)
      return NULL;

    if (ret == 3 && day <= 0) {
      ret = 2;
      day = -1;
    }

    if (ret >= 2 && month <= 0) {
      ret = 1;
      month = day = -1;
    }

    if (ret >= 1 && (year <= 0 || year > 9999 || month > 12 || day > 31))
      return NULL;

    else if (ret >= 1 && len < 16)
      /* YMD is 10 chars. XMD + HM will be 16 chars. if it is less,
       * it make no sense to continue. We will stay with YMD. */
      goto ymd;

    string += 10;
    /* Exit if there is no expeceted value on this stage */
    if (!(*string == 'T' || *string == '-' || *string == ' '))
      goto ymd;

    string += 1;
  }
  /* if hour or minute fails, then we will use only ymd. */
  hour = g_ascii_strtoull (string, (gchar **) & string, 10);
  if (hour > 24 || *string != ':')
    goto ymd;

  /* minute */
  minute = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
  if (minute > 59)
    goto ymd;

  /* second */
  if (*string == ':') {
    second = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
    /* if we fail here, we still can reuse hour and minute. We
     * will still attempt to parse any timezone information */
    if (second > 59) {
      second = -1.0;
    } else {
      /* microseconds */
      if (*string == '.' || *string == ',') {
        const gchar *usec_start = string + 1;
        guint digits;

        usecs = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
        if (usecs != G_MAXUINT64 && string > usec_start) {
          digits = (guint) (string - usec_start);
          second += (gdouble) usecs / pow (10.0, digits);
        }
      }
    }
  }

  if (*string == 'Z')
    goto ymd_hms;
  else {
    /* reuse some code from gst-plugins-base/gst-libs/gst/tag/gstxmptag.c */
    gint gmt_offset = -1;
    gchar *plus_pos = NULL;
    gchar *neg_pos = NULL;
    gchar *pos = NULL;

    GST_LOG ("Checking for timezone information");

    /* check if there is timezone info */
    plus_pos = strrchr (string, '+');
    neg_pos = strrchr (string, '-');
    if (plus_pos)
      pos = plus_pos + 1;
    else if (neg_pos)
      pos = neg_pos + 1;

    if (pos && strlen (pos) >= 3) {
      gint ret_tz;
      if (pos[2] == ':')
        ret_tz = sscanf (pos, "%d:%d", &gmt_offset_hour, &gmt_offset_min);
      else
        ret_tz = sscanf (pos, "%02d%02d", &gmt_offset_hour, &gmt_offset_min);

      GST_DEBUG ("Parsing timezone: %s", pos);

      if (ret_tz == 2) {
        if (neg_pos != NULL && neg_pos + 1 == pos) {
          gmt_offset_hour *= -1;
          gmt_offset_min *= -1;
        }
        gmt_offset = gmt_offset_hour * 60 + gmt_offset_min;

        tzoffset = gmt_offset / 60.0;

        GST_LOG ("Timezone offset: %f (%d minutes)", tzoffset, gmt_offset);
      } else
        GST_WARNING ("Failed to parse timezone information");
    }
  }

ymd_hms:
  if (year == -1 || month == -1 || day == -1) {
    GDateTime *now_utc, *now_in_given_tz;

    /* No date was supplied: make it today */
    now_utc = g_date_time_new_now_utc ();
    if (tzoffset != 0.0) {
      /* If a timezone offset was supplied, get the date of that timezone */
      g_assert (gmt_offset_min != -99);
      g_assert (gmt_offset_hour != -99);
      now_in_given_tz =
          g_date_time_add_minutes (now_utc,
          (60 * gmt_offset_hour) + gmt_offset_min);
      g_date_time_unref (now_utc);
    } else {
      now_in_given_tz = now_utc;
    }
    g_date_time_get_ymd (now_in_given_tz, &year, &month, &day);
    g_date_time_unref (now_in_given_tz);
  }
  return gst_date_time_new (tzoffset, year, month, day, hour, minute, second);
ymd:
  if (year == -1) {
    /* No date was supplied and time failed to parse */
    return NULL;
  }
  return gst_date_time_new_ymd (year, month, day);
}
Example #25
0
static int
_roster_result_handler(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata)
{
    const char *id = xmpp_stanza_get_attribute(stanza, STANZA_ATTR_ID);

    if (g_strcmp0(id, "roster") != 0) {
        return 1;
    }

    // handle initial roster response
    xmpp_stanza_t *query = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_QUERY);
    xmpp_stanza_t *item = xmpp_stanza_get_children(query);

    while (item) {
        const char *barejid = xmpp_stanza_get_attribute(item, STANZA_ATTR_JID);
        gchar *barejid_lower = g_utf8_strdown(barejid, -1);
        const char *name = xmpp_stanza_get_attribute(item, STANZA_ATTR_NAME);
        const char *sub = xmpp_stanza_get_attribute(item, STANZA_ATTR_SUBSCRIPTION);

        // do not set nickname to empty string, set to NULL instead
        if (name && (strlen(name) == 0)) name = NULL;

        gboolean pending_out = FALSE;
        const char *ask = xmpp_stanza_get_attribute(item, STANZA_ATTR_ASK);
        if (g_strcmp0(ask, "subscribe") == 0) {
            pending_out = TRUE;
        }

        GSList *groups = _get_groups_from_item(item);

        gboolean added = roster_add(barejid_lower, name, groups, sub, pending_out);
        if (!added) {
            log_warning("Attempt to add contact twice: %s", barejid_lower);
        }

        g_free(barejid_lower);
        item = xmpp_stanza_get_next(item);
    }

    sv_ev_roster_received();

    char *account = jabber_get_account_name();
    resource_presence_t conn_presence = accounts_get_login_presence(account);

    char *last_activity_str = accounts_get_last_activity(account);
    if (last_activity_str) {
        GDateTime *nowdt = g_date_time_new_now_utc();

        GTimeVal lasttv;
        gboolean res = g_time_val_from_iso8601(last_activity_str, &lasttv);
        if (res) {
            GDateTime *lastdt = g_date_time_new_from_timeval_utc(&lasttv);
            GTimeSpan diff_micros = g_date_time_difference(nowdt, lastdt);
            int diff_secs = (diff_micros / 1000) / 1000;
            cl_ev_presence_send(conn_presence, NULL, diff_secs);
            g_date_time_unref(lastdt);
        } else {
            cl_ev_presence_send(conn_presence, NULL, 0);
        }

        free(last_activity_str);
        g_date_time_unref(nowdt);
    } else {
        cl_ev_presence_send(conn_presence, NULL, 0);
    }

    return 1;
}
Example #26
0
void TestCheckEntry() {
  GDateTime *now = g_date_time_new_now_utc();
  GDateTime *one_hour_ago = g_date_time_add_hours(now, -1);
  GDateTime *over_1w_ago = g_date_time_add_weeks(one_hour_ago, -1);
  GDateTime *over_2w_ago = g_date_time_add_weeks(one_hour_ago, -2);
  GDateTime *over_3w_ago = g_date_time_add_weeks(one_hour_ago, -3);

  CachePolicy *policy = CachePolicyNew();
  CacheEntry *entry = CacheEntryNew();
  GError *error = NULL;

  // Any entry works with an empty policy.
  entry->tries = 4;
  entry->last_verified = over_3w_ago;
  entry->last_used = over_3w_ago;
  g_assert(CachePolicyCheckEntry(policy, entry, now, &error));
  g_assert_no_error(error);

  // Try against a policy with all fields set from now on.
  CachePolicySetValue(policy, "tries", "3", NULL);
  CachePolicySetValue(policy, "refresh", "1w", NULL);
  CachePolicySetValue(policy, "renew", "2w", NULL);
  CachePolicySetValue(policy, "expire", "3w", NULL);

  entry->tries = 3;
  entry->last_verified = over_2w_ago;
  entry->last_used = one_hour_ago;
  g_assert(CachePolicyCheckEntry(policy, entry, now, &error));
  g_assert_no_error(error);

  entry->last_verified = over_2w_ago;
  entry->last_used = over_1w_ago;
  g_assert(!CachePolicyCheckEntry(policy, entry, now, &error));
  g_assert_error(error, CACHE_POLICY_ERROR, CACHE_POLICY_ENTRY_EXPIRED_ERROR);
  g_error_free(error);
  error = NULL;

  entry->last_verified = over_3w_ago;
  entry->last_used = one_hour_ago;
  g_assert(!CachePolicyCheckEntry(policy, entry, now, &error));
  g_assert_error(error, CACHE_POLICY_ERROR, CACHE_POLICY_ENTRY_EXPIRED_ERROR);
  g_error_free(error);
  error = NULL;

  entry->tries = 4;
  entry->last_verified = one_hour_ago;
  entry->last_used = one_hour_ago;
  g_assert(!CachePolicyCheckEntry(policy, entry, now, &error));
  g_assert_error(error, CACHE_POLICY_ERROR,
                 CACHE_POLICY_MAX_TRIES_EXCEEDED_ERROR);
  g_error_free(error);
  error = NULL;

  entry->last_verified = NULL;
  entry->last_used = NULL;
  CacheEntryUnref(entry);
  CachePolicyUnref(policy);
  g_date_time_unref(now);
  g_date_time_unref(one_hour_ago);
  g_date_time_unref(over_1w_ago);
  g_date_time_unref(over_2w_ago);
  g_date_time_unref(over_3w_ago);
}
Example #27
0
gboolean
ostree_builtin_commit (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  GOptionContext *context;
  glnx_unref_object OstreeRepo *repo = NULL;
  gboolean ret = FALSE;
  gboolean skip_commit = FALSE;
  g_autoptr(GFile) object_to_commit = NULL;
  g_autofree char *parent = NULL;
  g_autofree char *commit_checksum = NULL;
  g_autoptr(GFile) root = NULL;
  g_autoptr(GVariant) metadata = NULL;
  g_autoptr(GVariant) detached_metadata = NULL;
  glnx_unref_object OstreeMutableTree *mtree = NULL;
  g_autofree char *tree_type = NULL;
  g_autoptr(GHashTable) mode_adds = NULL;
  g_autoptr(GHashTable) skip_list = NULL;
  OstreeRepoCommitModifierFlags flags = 0;
  OstreeRepoCommitModifier *modifier = NULL;
  OstreeRepoTransactionStats stats;
  struct CommitFilterData filter_data = { 0, };

  context = g_option_context_new ("[PATH] - Commit a new revision");

  if (!ostree_option_context_parse (context, options, &argc, &argv, OSTREE_BUILTIN_FLAG_NONE, &repo, cancellable, error))
    goto out;

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

  if (opt_statoverride_file)
    {
      mode_adds = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
      if (!parse_file_by_line (opt_statoverride_file, handle_statoverride_line,
                               mode_adds, cancellable, error))
        goto out;
    }

  if (opt_skiplist_file)
    {
      skip_list = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
      if (!parse_file_by_line (opt_skiplist_file, handle_skiplist_line,
                               skip_list, cancellable, error))
        goto out;
    }

  if (opt_metadata_strings)
    {
      if (!parse_keyvalue_strings (opt_metadata_strings,
                                   &metadata, error))
        goto out;
    }
  if (opt_detached_metadata_strings)
    {
      if (!parse_keyvalue_strings (opt_detached_metadata_strings,
                                   &detached_metadata, error))
        goto out;
    }
      
  if (!(opt_branch || opt_orphan))
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "A branch must be specified with --branch, or use --orphan");
      goto out;
    }

  if (opt_no_xattrs)
    flags |= OSTREE_REPO_COMMIT_MODIFIER_FLAGS_SKIP_XATTRS;
  if (opt_generate_sizes)
    flags |= OSTREE_REPO_COMMIT_MODIFIER_FLAGS_GENERATE_SIZES;
  if (opt_disable_fsync)
    ostree_repo_set_disable_fsync (repo, TRUE);

  if (flags != 0
      || opt_owner_uid >= 0
      || opt_owner_gid >= 0
      || opt_statoverride_file != NULL
      || opt_skiplist_file != NULL
      || opt_no_xattrs)
    {
      filter_data.mode_adds = mode_adds;
      filter_data.skip_list = skip_list;
      modifier = ostree_repo_commit_modifier_new (flags, commit_filter,
                                                  &filter_data, NULL);
    }

  if (opt_parent)
    {
      if (g_str_equal (opt_parent, "none"))
        parent = NULL;
      else
        {
          if (!ostree_validate_checksum_string (opt_parent, error))
            goto out;
          parent = g_strdup (opt_parent);
        }
    }
  else if (!opt_orphan)
    {
      if (!ostree_repo_resolve_rev (repo, opt_branch, TRUE, &parent, error))
        {
          if (g_error_matches (*error, G_IO_ERROR, G_IO_ERROR_IS_DIRECTORY))
            {
              /* A folder exists with the specified ref name,
                 * which is handled by _ostree_repo_write_ref */
              g_clear_error (error);
            }
          else goto out;
        }
    }

  if (opt_editor)
    {
      if (!commit_editor (repo, opt_branch, &opt_subject, &opt_body, cancellable, error))
        goto out;
    }

  if (!ostree_repo_prepare_transaction (repo, NULL, cancellable, error))
    goto out;

  if (opt_link_checkout_speedup && !ostree_repo_scan_hardlinks (repo, cancellable, error))
    goto out;

  mtree = ostree_mutable_tree_new ();

  if (argc <= 1 && (opt_trees == NULL || opt_trees[0] == NULL))
    {
      if (!ostree_repo_write_dfd_to_mtree (repo, AT_FDCWD, ".", mtree, modifier,
                                           cancellable, error))
        goto out;
    }
  else if (opt_trees != NULL)
    {
      const char *const*tree_iter;
      const char *tree;
      const char *eq;

      for (tree_iter = (const char *const*)opt_trees; *tree_iter; tree_iter++)
        {
          tree = *tree_iter;

          eq = strchr (tree, '=');
          if (!eq)
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Missing type in tree specification '%s'", tree);
              goto out;
            }
          g_free (tree_type);
          tree_type = g_strndup (tree, eq - tree);
          tree = eq + 1;

          g_clear_object (&object_to_commit);
          if (strcmp (tree_type, "dir") == 0)
            {
              if (!ostree_repo_write_dfd_to_mtree (repo, AT_FDCWD, tree, mtree, modifier,
                                                   cancellable, error))
                goto out;
            }
          else if (strcmp (tree_type, "tar") == 0)
            {
              object_to_commit = g_file_new_for_path (tree);
              if (!ostree_repo_write_archive_to_mtree (repo, object_to_commit, mtree, modifier,
                                                       opt_tar_autocreate_parents,
                                                       cancellable, error))
                goto out;
            }
          else if (strcmp (tree_type, "ref") == 0)
            {
              if (!ostree_repo_read_commit (repo, tree, &object_to_commit, NULL, cancellable, error))
                goto out;

              if (!ostree_repo_write_directory_to_mtree (repo, object_to_commit, mtree, modifier,
                                                         cancellable, error))
                goto out;
            }
          else
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Invalid tree type specification '%s'", tree_type);
              goto out;
            }
        }
    }
  else
    {
      g_assert (argc > 1);
      if (!ostree_repo_write_dfd_to_mtree (repo, AT_FDCWD, argv[1], mtree, modifier,
                                           cancellable, error))
        goto out;
    }

  if (mode_adds && g_hash_table_size (mode_adds) > 0)
    {
      GHashTableIter hash_iter;
      gpointer key, value;

      g_hash_table_iter_init (&hash_iter, mode_adds);

      while (g_hash_table_iter_next (&hash_iter, &key, &value))
        {
          g_printerr ("Unmatched statoverride path: %s\n", (char*)key);
        }
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Unmatched statoverride paths");
      goto out;
    }

  if (skip_list && g_hash_table_size (skip_list) > 0)
    {
      GHashTableIter hash_iter;
      gpointer key;

      g_hash_table_iter_init (&hash_iter, skip_list);

      while (g_hash_table_iter_next (&hash_iter, &key, NULL))
        {
          g_printerr ("Unmatched skip-list path: %s\n", (char*)key);
        }
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Unmatched skip-list paths");
      goto out;
    }

  if (!ostree_repo_write_mtree (repo, mtree, &root, cancellable, error))
    goto out;

  if (opt_skip_if_unchanged && parent)
    {
      g_autoptr(GFile) parent_root;

      if (!ostree_repo_read_commit (repo, parent, &parent_root, NULL, cancellable, error))
        goto out;

      if (g_file_equal (root, parent_root))
        skip_commit = TRUE;
    }

  if (!skip_commit)
    {
      gboolean update_summary;
      guint64 timestamp;
      if (!opt_timestamp)
        {
          GDateTime *now = g_date_time_new_now_utc ();
          timestamp = g_date_time_to_unix (now);
          g_date_time_unref (now);

          if (!ostree_repo_write_commit (repo, parent, opt_subject, opt_body, metadata,
                                         OSTREE_REPO_FILE (root),
                                         &commit_checksum, cancellable, error))
            goto out;
        }
      else
        {
          struct timespec ts;
          if (!parse_datetime (&ts, opt_timestamp, NULL))
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Could not parse '%s'", opt_timestamp);
              goto out;
            }
          timestamp = ts.tv_sec;

          if (!ostree_repo_write_commit_with_time (repo, parent, opt_subject, opt_body, metadata,
                                                   OSTREE_REPO_FILE (root),
                                                   timestamp,
                                                   &commit_checksum, cancellable, error))
            goto out;
        }

      if (detached_metadata)
        {
          if (!ostree_repo_write_commit_detached_metadata (repo, commit_checksum,
                                                           detached_metadata,
                                                           cancellable, error))
            goto out;
        }

      if (opt_key_ids)
        {
          char **iter;

          for (iter = opt_key_ids; iter && *iter; iter++)
            {
              const char *keyid = *iter;

              if (!ostree_repo_sign_commit (repo,
                                            commit_checksum,
                                            keyid,
                                            opt_gpg_homedir,
                                            cancellable,
                                            error))
                goto out;
            }
        }

      if (opt_branch)
        ostree_repo_transaction_set_ref (repo, NULL, opt_branch, commit_checksum);
      else
        g_assert (opt_orphan);

      if (!ostree_repo_commit_transaction (repo, &stats, cancellable, error))
        goto out;

      /* The default for this option is FALSE, even for archive-z2 repos,
       * because ostree supports multiple processes committing to the same
       * repo (but different refs) concurrently, and in fact gnome-continuous
       * actually does this.  In that context it's best to update the summary
       * explicitly instead of automatically here. */
      if (!ot_keyfile_get_boolean_with_default (ostree_repo_get_config (repo), "core",
                                                "commit-update-summary", FALSE,
                                                &update_summary, error))
        goto out;

      if (update_summary && !ostree_repo_regenerate_summary (repo,
                                                             NULL,
                                                             cancellable,
                                                             error))
        goto out;
    }
  else
    {
      commit_checksum = g_strdup (parent);
    }

  if (opt_table_output)
    {
      g_print ("Commit: %s\n", commit_checksum);
      g_print ("Metadata Total: %u\n", stats.metadata_objects_total);
      g_print ("Metadata Written: %u\n", stats.metadata_objects_written);
      g_print ("Content Total: %u\n", stats.content_objects_total);
      g_print ("Content Written: %u\n", stats.content_objects_written);
      g_print ("Content Bytes Written: %" G_GUINT64_FORMAT "\n", stats.content_bytes_written);
    }
  else
    {
      g_print ("%s\n", commit_checksum);
    }

  ret = TRUE;
 out:
  if (repo)
    ostree_repo_abort_transaction (repo, cancellable, NULL);
  if (context)
    g_option_context_free (context);
  if (modifier)
    ostree_repo_commit_modifier_unref (modifier);
  return ret;
}
Example #28
0
int
main (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionGroup *option_group;
	GOptionContext *context;
	const gchar *simulation_filename, *introspection_filename;
	gchar *simulation_code, *introspection_xml;
	MainData data;
	GPtrArray/*<DfsmObject>*/ *simulated_objects;
	const gchar *test_program_name;
	GPtrArray/*<string>*/ *test_program_argv;
	guint i;
	gchar *time_str, *command_line, *log_header, *seed_str;
	GDateTime *date_time;
	GFile *working_directory_file, *dbus_daemon_config_file;

	/* Set up localisation. */
	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

#if !GLIB_CHECK_VERSION (2, 35, 0)
	g_type_init ();
#endif
	g_set_application_name (_("D-Bus Simulator"));

	/* Take a copy of the command line, for use in printing the log headers later. */
	command_line = g_strjoinv (" ", argv);

	/* Parse command line options */
	context = g_option_context_new (_("[simulation code file] [introspection XML file] -- [executable-file] [arguments]"));
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
	g_option_context_set_summary (context, _("Simulates the server in a D-Bus client–server conversation."));
	g_option_context_add_main_entries (context, main_entries, GETTEXT_PACKAGE);

	/* Logging option group */
	option_group = g_option_group_new ("logging", _("Logging Options:"), _("Show help options for output logging"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, logging_entries);
	g_option_context_add_group (context, option_group);

	/* Testing option group */
	option_group = g_option_group_new ("testing", _("Testing Options:"), _("Show help options for test runs and timeouts"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, testing_entries);
	g_option_context_add_group (context, option_group);

	/* Test program option group */
	option_group = g_option_group_new ("test-program", _("Test Program Options:"), _("Show help options for the program under test"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, test_program_entries);
	g_option_context_add_group (context, option_group);

	/* dbus-daemon option group */
	option_group = g_option_group_new ("dbus-daemon", _("D-Bus Daemon Options:"), _("Show help options for the dbus-daemon"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, dbus_daemon_entries);
	g_option_context_add_group (context, option_group);

	if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) {
		g_printerr (_("Error parsing command line options: %s"), error->message);
		g_printerr ("\n");

		print_help_text (context);

		g_error_free (error);
		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Extract the simulation and the introspection filenames. */
	if (argc < 3) {
		g_printerr (_("Error parsing command line options: %s"), _("Simulation and introspection filenames must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	simulation_filename = argv[1];
	introspection_filename = argv[2];

	/* Extract the remaining arguments */
	if (argc < 4) {
		g_printerr (_("Error parsing command line options: %s"), _("Test program must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Work out where the test program's command line starts. g_option_context_parse() sometimes leaves the ‘--’ in argv. */
	if (strcmp (argv[3], "--") == 0) {
		i = 4;
	} else {
		i = 3;
	}

	test_program_name = argv[i++];
	test_program_argv = g_ptr_array_new_with_free_func (g_free);

	for (; i < (guint) argc; i++) {
		g_ptr_array_add (test_program_argv, g_strdup (argv[i]));
	}

	g_option_context_free (context);

	/* Set up logging. */
	dsim_logging_init (test_program_log_file, test_program_log_fd, dbus_daemon_log_file, dbus_daemon_log_fd, simulator_log_file, simulator_log_fd,
	                   &error);

	if (error != NULL) {
		g_printerr (_("Error setting up logging: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (command_line);

		exit (STATUS_LOGGING_PROBLEM);
	}

	/* Output a log header to each of the log streams. */
	date_time = g_date_time_new_now_utc ();
	time_str = g_date_time_format (date_time, "%F %TZ");
	g_date_time_unref (date_time);

	log_header = g_strdup_printf (_("Bendy Bus (number %s) left the depot at %s using command line: %s"), PACKAGE_VERSION, time_str, command_line);

	g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_DBUS_DAEMON), G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_TEST_PROGRAM), G_LOG_LEVEL_MESSAGE, "%s", log_header);

	g_free (log_header);
	g_free (time_str);
	g_free (command_line);

	/* Set up the random number generator. */
	if (random_seed == 0) {
		random_seed = g_get_real_time ();
	}

	seed_str = g_strdup_printf ("%" G_GINT64_FORMAT, random_seed);
	g_message (_("Note: Setting random number generator seed to %s."), seed_str);
	g_free (seed_str);

	g_random_set_seed ((guint32) random_seed);

	/* Load the files. */
	g_file_get_contents (simulation_filename, &simulation_code, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading simulation code from file ‘%s’: %s"), simulation_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_UNREADABLE_FILE);
	}

	g_file_get_contents (introspection_filename, &introspection_xml, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading introspection XML from file ‘%s’: %s"), introspection_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (simulation_code);

		exit (STATUS_UNREADABLE_FILE);
	}

	/* Build the DfsmObjects. */
	simulated_objects = dfsm_object_factory_from_data (simulation_code, introspection_xml, &error);

	g_free (introspection_xml);
	g_free (simulation_code);

	if (error != NULL) {
		g_printerr (_("Error creating simulated DFSMs: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_INVALID_CODE);
	}

	/* Prepare the main data struct, which will last for the lifetime of the program. */
	data.main_loop = g_main_loop_new (NULL, FALSE);
	data.exit_status = STATUS_SUCCESS;
	data.exit_signal = EXIT_SIGNAL_INVALID;
	data.test_program = NULL;
	data.connection = NULL;
	data.simulated_objects = g_ptr_array_ref (simulated_objects);
	data.outstanding_registration_callbacks = 0;
	data.test_run_inactivity_timeout_id = 0;
	data.test_program_spawn_end_signal = 0;
	data.test_program_process_died_signal = 0;
	data.test_program_sigkill_timeout_id = 0;

	if (run_infinitely == TRUE || (run_iters == 0 && run_time == 0)) {
		data.num_test_runs_remaining = -1;
	} else {
		data.num_test_runs_remaining = run_iters;
	}

	g_ptr_array_unref (simulated_objects);

	/* Store the test program name and argv, since we can only spawn it once we know the bus address. */
	data.test_program_name = g_strdup (test_program_name);
	data.test_program_argv = g_ptr_array_ref (test_program_argv);

	g_ptr_array_unref (test_program_argv);

	/* Set up signal handlers for SIGINT and SIGTERM so that we can close gracefully. */
	g_unix_signal_add (SIGINT, (GSourceFunc) sigint_handler_cb, &data);
	g_unix_signal_add (SIGTERM, (GSourceFunc) sigterm_handler_cb, &data);

	/* Create a working directory. */
	prepare_dbus_daemon_working_directory (&(data.working_directory_file), &working_directory_file, &dbus_daemon_config_file, &error);

	if (error != NULL) {
		g_printerr (_("Error creating dbus-daemon working directory: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_TMP_DIR_ERROR);
	}

	/* Start up our own private dbus-daemon instance. */
	data.dbus_daemon = dsim_dbus_daemon_new (working_directory_file, dbus_daemon_config_file);
	data.dbus_address = NULL;

	g_object_unref (dbus_daemon_config_file);
	g_object_unref (working_directory_file);

	g_signal_connect (data.dbus_daemon, "process-died", (GCallback) dbus_daemon_died_cb, &data);
	g_signal_connect (data.dbus_daemon, "notify::bus-address", (GCallback) dbus_daemon_notify_bus_address_cb, &data);

	dsim_program_wrapper_spawn (DSIM_PROGRAM_WRAPPER (data.dbus_daemon), &error);

	if (error != NULL) {
		g_printerr (_("Error spawning private dbus-daemon instance: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_DAEMON_SPAWN_ERROR);
	}

	/* Start the main loop and wait for the dbus-daemon to send us its address. */
	g_main_loop_run (data.main_loop);

	/* Free the main data struct. */
	main_data_clear (&data);
	dsim_logging_finalise ();

	if (data.exit_signal != EXIT_SIGNAL_INVALID) {
		struct sigaction action;

		/* Propagate the signal to the default handler. */
		action.sa_handler = SIG_DFL;
		sigemptyset (&action.sa_mask);
		action.sa_flags = 0;

		sigaction (data.exit_signal, &action, NULL);

		kill (getpid (), data.exit_signal);
	}

	return data.exit_status;
}