Beispiel #1
0
static gboolean
meta_monitor_manager_handle_get_crtc_gamma  (MetaDBusDisplayConfig *skeleton,
                                             GDBusMethodInvocation *invocation,
                                             guint                  serial,
                                             guint                  crtc_id)
{
  MetaMonitorManager *manager = META_MONITOR_MANAGER (skeleton);
  MetaMonitorManagerClass *klass;
  MetaCRTC *crtc;
  gsize size;
  unsigned short *red;
  unsigned short *green;
  unsigned short *blue;
  GBytes *red_bytes, *green_bytes, *blue_bytes;
  GVariant *red_v, *green_v, *blue_v;

  if (serial != manager->serial)
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
                                             G_DBUS_ERROR_ACCESS_DENIED,
                                             "The requested configuration is based on stale information");
      return TRUE;
    }

  if (crtc_id >= manager->n_crtcs)
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
                                             G_DBUS_ERROR_INVALID_ARGS,
                                             "Invalid crtc id");
      return TRUE;
    }
  crtc = &manager->crtcs[crtc_id];

  klass = META_MONITOR_MANAGER_GET_CLASS (manager);
  if (klass->get_crtc_gamma)
    klass->get_crtc_gamma (manager, crtc, &size, &red, &green, &blue);
  else
    {
      size = 0;
      red = green = blue = NULL;
    }

  red_bytes = g_bytes_new_take (red, size * sizeof (unsigned short));
  green_bytes = g_bytes_new_take (green, size * sizeof (unsigned short));
  blue_bytes = g_bytes_new_take (blue, size * sizeof (unsigned short));

  red_v = g_variant_new_from_bytes (G_VARIANT_TYPE ("aq"), red_bytes, TRUE);
  green_v = g_variant_new_from_bytes (G_VARIANT_TYPE ("aq"), green_bytes, TRUE);
  blue_v = g_variant_new_from_bytes (G_VARIANT_TYPE ("aq"), blue_bytes, TRUE);

  meta_dbus_display_config_complete_get_crtc_gamma (skeleton, invocation,
                                                    red_v, green_v, blue_v);

  g_bytes_unref (red_bytes);
  g_bytes_unref (green_bytes);
  g_bytes_unref (blue_bytes);

  return TRUE;
}
Beispiel #2
0
GBytes* gexiv2_metadata_get_iptc_tag_raw (GExiv2Metadata *self, const gchar* tag) {
    g_return_val_if_fail(GEXIV2_IS_METADATA (self), NULL);
    g_return_val_if_fail(tag != NULL, NULL);
    g_return_val_if_fail(self->priv->image.get() != NULL, NULL);

    Exiv2::IptcData& iptc_data = self->priv->image->iptcData();

    try {
        Exiv2::IptcData::iterator it = iptc_data.findKey(Exiv2::IptcKey(tag));
        while (it != iptc_data.end() && it->count() == 0)
            it++;

        if (it != iptc_data.end()) {
            long size = it->size();
            if( size > 0 ) {
                gpointer data = g_malloc(size);
                it->copy((Exiv2::byte*)data, Exiv2::invalidByteOrder);
                return g_bytes_new_take(data, size);
            }
        }
    } catch (Exiv2::Error& e) {
        LOG_ERROR(e);
    }

    return NULL;
}
static void
cockpit_pipe_transport_send (CockpitTransport *transport,
                             const gchar *channel_id,
                             GBytes *payload)
{
  CockpitPipeTransport *self = COCKPIT_PIPE_TRANSPORT (transport);
  GBytes *prefix;
  gchar *prefix_str;
  gsize payload_len;
  gsize channel_len;

  if (self->closed)
    {
      g_debug ("dropping message on closed transport");
      return;
    }

  channel_len = channel_id ? strlen (channel_id) : 0;
  payload_len = g_bytes_get_size (payload);

  prefix_str = g_strdup_printf ("%" G_GSIZE_FORMAT "\n%s\n",
                                channel_len + 1 + payload_len,
                                channel_id ? channel_id : "");
  prefix = g_bytes_new_take (prefix_str, strlen (prefix_str));

  cockpit_pipe_write (self->pipe, prefix);
  cockpit_pipe_write (self->pipe, payload);
  g_bytes_unref (prefix);

  g_debug ("%s: queued %" G_GSIZE_FORMAT " byte payload", self->name, payload_len);
}
Beispiel #4
0
/**
 * dfu_utils_bytes_join_array:
 * @chunks: (element-kind GBytes): bytes
 *
 * Creates a monolithic block of memory from an array of #GBytes.
 *
 * Return value: (transfer full): a new GBytes
 **/
GBytes *
dfu_utils_bytes_join_array (GPtrArray *chunks)
{
	gsize total_size = 0;
	guint32 offset = 0;
	guint8 *buffer;

	/* get the size of all the chunks */
	for (guint i = 0; i < chunks->len; i++) {
		GBytes *chunk_tmp = g_ptr_array_index (chunks, i);
		total_size += g_bytes_get_size (chunk_tmp);
	}

	/* copy them into a buffer */
	buffer = g_malloc0 (total_size);
	for (guint i = 0; i < chunks->len; i++) {
		const guint8 *chunk_data;
		gsize chunk_size = 0;
		GBytes *chunk_tmp = g_ptr_array_index (chunks, i);
		chunk_data = g_bytes_get_data (chunk_tmp, &chunk_size);
		if (chunk_size == 0)
			continue;
		memcpy (buffer + offset, chunk_data, chunk_size);
		offset += chunk_size;
	}
	return g_bytes_new_take (buffer, total_size);
}
Beispiel #5
0
GBytes *
gst_amf_serialize_command2 (const char *command_name, int transaction_id,
    GstAmfNode * command_object, GstAmfNode * optional_args, GstAmfNode * n3,
    GstAmfNode * n4)
{
  AmfSerializer _s = { 0 }, *serializer = &_s;

  serializer->size = 4096;
  serializer->data = g_malloc (serializer->size);

  _serialize_u8 (serializer, GST_AMF_TYPE_STRING);
  _serialize_utf8_string (serializer, command_name);
  _serialize_u8 (serializer, GST_AMF_TYPE_NUMBER);
  _serialize_number (serializer, transaction_id);
  _serialize_value (serializer, command_object);
  if (optional_args)
    _serialize_value (serializer, optional_args);
  if (n3)
    _serialize_value (serializer, n3);
  if (n4)
    _serialize_value (serializer, n4);

  if (serializer->error) {
    GST_ERROR ("failed to serialize");
    g_free (serializer->data);
    return NULL;
  }
  return g_bytes_new_take (serializer->data, serializer->offset);
}
Beispiel #6
0
static GBytes *
base64_encode (GBytes *bytes)
{
  gconstpointer data;
  gchar *encoded;
  gsize length;
  gint state = 0;
  gint save = 0;

  data = g_bytes_get_data (bytes, &length);

  if (length == 0)
    return g_bytes_new_static ("", 0);

  /* We can use a smaller limit here, since we know the saved state is 0,
     +1 is needed for trailing \0, also check for unlikely integer overflow */

  if (length >= ((G_MAXSIZE - 1) / 4 - 1) * 3)
    g_error ("%s: input too large for Base64 encoding (%"G_GSIZE_FORMAT" chars)", G_STRLOC, length);

  encoded = g_malloc ((length / 3 + 1) * 4 + 4);
  length = g_base64_encode_step (data, length, FALSE, encoded, &state, &save);
  length += g_base64_encode_close (FALSE, encoded + length, &state, &save);

  return g_bytes_new_take (encoded, length);
}
Beispiel #7
0
enum http_rc_e
action_forward_stats (struct req_args_s *args)
{
	const char *id = OPT("id");
	if (!id)
		return _reply_format_error (args, BADREQ("Missing SRVID"));

	args->rp->no_access();
	MESSAGE req = metautils_message_create_named("REQ_STATS");
	GByteArray *encoded = message_marshall_gba_and_clean (req);
	gchar *packed = NULL;
	GError *err = gridd_client_exec_and_concat_string (id, 1.0, encoded, &packed);
	if (err) {
		g_free0 (packed);
		if (CODE_IS_NETWORK_ERROR(err->code)) {
			if (err->code == ERRCODE_CONN_TIMEOUT || err->code == ERRCODE_READ_TIMEOUT)
				return _reply_gateway_timeout (args, err);
			return _reply_srv_unavailable (args, err);
		}
		return _reply_common_error (args, err);
	}

	for (gchar *s=packed; *s ;++s) { if (*s == '=') *s = ' '; }

	/* TODO(jfs): quite duplicated from _reply_json() but the original
	   was not suitable. */
	args->rp->set_status (200, "OK");
	args->rp->set_body_bytes (g_bytes_new_take((guint8*)packed, strlen(packed)));
	args->rp->finalize ();
	return HTTPRC_DONE;
}
Beispiel #8
0
/**
 * mega_aes_key_decrypt:
 * @aes_key: a #MegaAesKey
 * @cipher: UBase64 encoded ciphertext.
 *
 * Decrypt UBase64 encoded 16-byte aligned ciphertext into binary plaintext data.
 *
 * Returns: (transfer full): Binary plaintext data.
 */
GBytes* mega_aes_key_decrypt(MegaAesKey* aes_key, const gchar* cipher)
{
    gsize cipherlen = 0;
    guchar* cipher_raw;
    guchar* plain;

    g_return_val_if_fail(MEGA_IS_AES_KEY(aes_key), NULL);
    g_return_val_if_fail(cipher != NULL, NULL);

    cipher_raw = mega_base64urldecode(cipher, &cipherlen);
    if (cipher_raw == NULL)
        return NULL;

    if (cipherlen == 0)
    {
        g_free(cipher_raw);
        return NULL;
    }

    if (cipherlen % 16 != 0)
    {
        g_free(cipher_raw);
        return NULL;
    }

    plain = g_malloc0(cipherlen);
    mega_aes_key_decrypt_raw(aes_key, cipher_raw, plain, cipherlen);
    g_free(cipher_raw);

    return g_bytes_new_take(plain, cipherlen);
}
Beispiel #9
0
/**
 * dfu_element_set_target_size:
 * @element: a #DfuElement
 * @target_size: size in bytes
 *
 * Sets a target size for the element. If the prepared element is smaller
 * than this then it will be padded with NUL bytes up to the required size.
 *
 * Since: 0.5.4
 **/
void
dfu_element_set_target_size (DfuElement *element, guint32 target_size)
{
	DfuElementPrivate *priv = GET_PRIVATE (element);
	const guint8 *data;
	gsize length;
	guint8 *buf;
	g_autoptr(GBytes) contents_padded = NULL;

	g_return_if_fail (DFU_IS_ELEMENT (element));

	/* save for dump */
	priv->target_size = target_size;

	/* no need to pad */
	if (priv->contents == NULL)
		return;
	if (g_bytes_get_size (priv->contents) >= target_size)
		return;

	/* reallocate and pad */
	data = g_bytes_get_data (priv->contents, &length);
	buf = g_malloc0 (target_size);
	g_assert (buf != NULL);
	memcpy (buf, data, length);

	/* replace */
	g_bytes_unref (priv->contents);
	priv->contents = g_bytes_new_take (buf, target_size);
}
Beispiel #10
0
GBytes *
gtk_file_load_bytes (GFile         *file,
                     GCancellable  *cancellable,
                     GError       **error)
{
  gchar *contents;
  gsize len;

  g_return_val_if_fail (G_IS_FILE (file), NULL);
  g_return_val_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable), NULL);

  if (g_file_has_uri_scheme (file, "resource"))
    {
      gchar *uri, *unescaped;
      GBytes *bytes;

      uri = g_file_get_uri (file);
      unescaped = g_uri_unescape_string (uri + strlen ("resource://"), NULL);
      g_free (uri);

      bytes = g_resources_lookup_data (unescaped, 0, error);
      g_free (unescaped);

      return bytes;
    }

  /* contents is always \0 terminated, but we don't include that in the bytes */
  if (g_file_load_contents (file, cancellable, &contents, &len, NULL, error))
    return g_bytes_new_take (contents, len);

  return NULL;
}
Beispiel #11
0
GBytes *
meta_output_xrandr_read_edid (MetaOutput *output)
{
  Display *xdisplay = xdisplay_from_output (output);
  Atom edid_atom;
  guint8 *result;
  gsize len;

  edid_atom = XInternAtom (xdisplay, "EDID", FALSE);
  result = get_edid_property (xdisplay, output->winsys_id, edid_atom, &len);

  if (!result)
    {
      edid_atom = XInternAtom (xdisplay, "EDID_DATA", FALSE);
      result = get_edid_property (xdisplay, output->winsys_id, edid_atom, &len);
    }

  if (result)
    {
      if (len > 0 && len % 128 == 0)
        return g_bytes_new_take (result, len);
      else
        g_free (result);
    }

  return NULL;
}
Beispiel #12
0
static void
test_request (const gchar *path)
{
	GcrParser *parser;
	GError *err = NULL;
	guchar *data;
	gsize n_data;
	GtkWidget *dialog;
	GBytes *bytes;

	if (!g_file_get_contents (path, (gchar**)&data, &n_data, NULL))
		g_error ("couldn't read file: %s", path);

	dialog = gtk_dialog_new ();
	g_object_ref_sink (dialog);

	parser = gcr_parser_new ();
	g_signal_connect (parser, "parsed", G_CALLBACK (on_parser_parsed), dialog);
	bytes = g_bytes_new_take (data, n_data);
	if (!gcr_parser_parse_data (parser, data, n_data, &err))
		g_error ("couldn't parse data: %s", err->message);

	g_object_unref (parser);
	g_bytes_unref (bytes);

	gtk_widget_show (dialog);
	g_signal_connect (dialog, "delete-event", G_CALLBACK (gtk_main_quit), NULL);
	gtk_main ();

	g_object_unref (dialog);
}
static void
cockpit_pipe_transport_send (CockpitTransport *transport,
                             guint channel,
                             GBytes *payload)
{
  CockpitPipeTransport *self = COCKPIT_PIPE_TRANSPORT (transport);
  GBytes *prefix;
  gchar *prefix_str;
  gsize prefix_len;
  guint32 size;

  prefix_str = g_strdup_printf ("xxxx%u\n", channel);
  prefix_len = strlen (prefix_str);

  /* See doc/protocol.md */
  size = GUINT32_TO_BE (g_bytes_get_size (payload) + prefix_len - 4);
  memcpy (prefix_str, &size, 4);

  prefix = g_bytes_new_take (prefix_str, prefix_len);

  cockpit_pipe_write (self->pipe, prefix);
  cockpit_pipe_write (self->pipe, payload);
  g_bytes_unref (prefix);

  g_debug ("%s: queued %d byte payload", self->name, (int)g_bytes_get_size (payload));
}
Beispiel #14
0
gboolean
plgi_term_to_gbytes(term_t   t,
                    GBytes **bytes)
{
  GBytes *bytes0;
  term_t list = PL_copy_term_ref(t);
  term_t head = PL_new_term_ref();
  guint8 *data;
  gsize len;
  gint i = 0;

  if ( PL_skip_list(list, 0, &len) != PL_LIST )
  { return PL_type_error("list", t);
  }

  data = g_malloc0(len);

  while ( PL_get_list(list, head, list) )
  { guint8 byte;
    if ( !plgi_term_to_guint8(head, &byte) )
    { g_free(data);
      return FALSE;
    }
    data[i++] = byte;
  }

  bytes0 = g_bytes_new_take(data, len);

  PLGI_debug("    term: 0x%lx  --->  GBytes: %p", t, bytes0);

  *bytes = bytes0;

  return TRUE;
}
Beispiel #15
0
/**
 * mega_aes_key_decrypt_cbc:
 * @aes_key: a #MegaAesKey
 * @cipher: UBase64 encoded ciphertext.
 *
 * Decrypt UBase64 encoded ciphertext blocks using AES key in CBC mode with zero IV.
 *
 * Returns: (transfer full): UBase64 encoded ciphertext.
 */
GBytes* mega_aes_key_decrypt_cbc(MegaAesKey* aes_key, const gchar* cipher)
{
    guchar iv[AES_BLOCK_SIZE] = {0};
    guchar* cipher_raw;
    guchar* plain;
    gsize cipherlen = 0;

    g_return_val_if_fail(MEGA_IS_AES_KEY(aes_key), NULL);
    g_return_val_if_fail(cipher != NULL, NULL);

    cipher_raw = mega_base64urldecode(cipher, &cipherlen);
    if (cipher_raw == NULL)
        return NULL;

    if (cipherlen % 16 != 0)
    {
        g_free(cipher_raw);
        return NULL;
    }

    plain = g_malloc0(cipherlen + 1);
    AES_cbc_encrypt(cipher_raw, plain, cipherlen, &aes_key->priv->dec_key, iv, 0);
    g_free(cipher_raw);

    return g_bytes_new_take(plain, cipherlen);
}
Beispiel #16
0
static void
send_response(SoupWebsocketConnection *ws,
            const gchar *protocol, const gchar *command, JsonObject *payload)
{
    g_return_if_fail(ws);

    JsonObject *response = json_object_new();
    g_assert(response);

    json_object_set_string_member(response, "protocol", protocol);
    json_object_set_string_member(response, "command", command);
    json_object_set_object_member(response, "payload", payload);

    JsonGenerator *generator = json_generator_new();
    JsonNode *node = json_node_new(JSON_NODE_OBJECT);
    json_node_take_object(node, response);
    json_generator_set_root(generator, node);

    gsize len = 0;
    gchar *data = json_generator_to_data(generator, &len);
    GBytes *resp = g_bytes_new_take(data, len);
    g_print ("SEND: %.*s\n", (int)len, data);
    soup_websocket_connection_send(ws, SOUP_WEBSOCKET_DATA_TEXT, resp);

    g_object_unref(generator);
}
Beispiel #17
0
static GBytes *
expand_variables (const gchar *variable,
                  gpointer user_data)
{
  ExpandInfo *expand = user_data;
  CockpitPackage *package;
  gchar *val;

  package = g_hash_table_lookup (expand->listing, variable);
  if (package)
    {
      if (package->checksum)
        {
          return g_bytes_new_with_free_func (package->checksum, strlen (package->checksum),
                                             cockpit_package_unref,
                                             cockpit_package_ref (package));
        }
      else if (expand->host)
        {
          val = g_strdup_printf ("%s@%s", package->name, expand->host);
          return g_bytes_new_take (val, strlen (val));
        }
      else
        {
          return g_bytes_new_with_free_func (package->name, strlen (package->name),
                                             cockpit_package_unref,
                                             cockpit_package_ref (package));
        }
    }
  else
    {
      return g_bytes_new (variable, strlen (variable));
    }
}
Beispiel #18
0
static void
send_login_html (CockpitWebResponse *response,
                 CockpitHandlerData *ws)
{
  static const gchar *marker = "<head>";

  CockpitWebFilter *filter;
  GBytes *environment;
  GError *error = NULL;
  GBytes *bytes;

  GBytes *url_bytes = NULL;
  CockpitWebFilter *filter2 = NULL;
  const gchar *url_root = NULL;
  gchar *base;

  environment = build_environment (ws->os_release);
  filter = cockpit_web_inject_new (marker, environment, 1);
  g_bytes_unref (environment);
  cockpit_web_response_add_filter (response, filter);
  g_object_unref (filter);

  url_root = cockpit_web_response_get_url_root (response);
  if (url_root)
    base = g_strdup_printf ("<base href=\"%s/\">", url_root);
  else
    base = g_strdup ("<base href=\"/\">");

  url_bytes = g_bytes_new_take (base, strlen(base));
  filter2 = cockpit_web_inject_new (marker, url_bytes, 1);
  g_bytes_unref (url_bytes);
  cockpit_web_response_add_filter (response, filter2);
  g_object_unref (filter2);

  cockpit_web_response_set_cache_type (response, COCKPIT_WEB_RESPONSE_NO_CACHE);

  bytes = cockpit_web_response_negotiation (ws->login_html, NULL, NULL, NULL, &error);
  if (error)
    {
      g_message ("%s", error->message);
      cockpit_web_response_error (response, 500, NULL, NULL);
      g_error_free (error);
    }
  else if (!bytes)
    {
      cockpit_web_response_error (response, 404, NULL, NULL);
    }
  else
    {
      /* The login Content-Security-Policy allows the page to have inline <script> and <style> tags. */
      cockpit_web_response_headers (response, 200, "OK", -1,
                                    "Content-Security-Policy",
                                    "default-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:",
                                    NULL);
      if (cockpit_web_response_queue (response, bytes))
        cockpit_web_response_complete (response);

      g_bytes_unref (bytes);
    }
}
static gboolean
on_transport_recv (CockpitTransport *transport,
                   const gchar *channel,
                   GBytes *payload,
                   gpointer user_data)
{
  CockpitWebService *self = user_data;
  WebSocketDataType data_type;
  CockpitSocket *socket;
  gchar *string;
  GBytes *prefix;

  if (!channel)
    return FALSE;

  /* Forward the message to the right socket */
  socket = cockpit_socket_lookup_by_channel (&self->sockets, channel);
  if (socket && web_socket_connection_get_ready_state (socket->connection) == WEB_SOCKET_STATE_OPEN)
    {
      string = g_strdup_printf ("%s\n", channel);
      prefix = g_bytes_new_take (string, strlen (string));
      data_type = GPOINTER_TO_INT (g_hash_table_lookup (socket->channels, channel));
      web_socket_connection_send (socket->connection, data_type, prefix, payload);
      g_bytes_unref (prefix);
      return TRUE;
    }

  return FALSE;
}
Beispiel #20
0
/**
 * CacheUtilHashPassword:
 * @algorithm: Hash algorithm.
 * @salt: Random data, usually stored with the hash.
 * @password: Secret value to hash.
 *
 * Returns: (allow-none): Hash value of concatenated @salt and @password, or
 * #NULL if an argument was invalid.
 */
GBytes *CacheUtilHashPassword(GChecksumType algorithm, GBytes *salt,
                               const char *password) {
  GChecksum *checksum = NULL;
  gssize checksum_len = -1;
  guint8 *result = NULL;
  gsize result_len = 0;

  if (!salt || !password)
    return NULL;

  checksum_len = g_checksum_type_get_length(algorithm);
  if (checksum_len <= 0)
    return NULL;

  checksum = g_checksum_new(algorithm);
  if (!checksum)
    return NULL;

  g_checksum_update(
      checksum, g_bytes_get_data(salt, NULL), g_bytes_get_size(salt));
  g_checksum_update(checksum, (guint8 *) password, strlen(password));

  result = g_malloc(checksum_len);
  result_len = checksum_len;

  g_checksum_get_digest(checksum, result, &result_len);
  g_assert(checksum_len == result_len);

  g_checksum_free(checksum);
  return g_bytes_new_take(result, result_len);
}
Beispiel #21
0
gboolean download_mem(GBytes **data, const gchar *url, gsize limit, GError **error)
{
	RaucTransfer xfer = {0};
	gboolean res = FALSE;
	GError *ierror = NULL;
	char *dl_data = NULL;

	xfer.url = url;
	xfer.limit = limit;

	xfer.dl = open_memstream(&dl_data, &xfer.dl_size);
	if (xfer.dl == NULL) {
		g_set_error(error, G_IO_ERROR, G_IO_ERROR_FAILED, "Failed opening memstream");
		goto out;
	}

	res = transfer(&xfer, &ierror);
	if (!res) {
		g_propagate_error(error, ierror);
		goto out;
	}

	g_clear_pointer(&xfer.dl, fclose);
	*data = g_bytes_new_take(dl_data, xfer.dl_size);
	dl_data = NULL;

out:
	g_clear_pointer(&xfer.dl, fclose);
	g_clear_pointer(&dl_data, free);
	return res;
}
Beispiel #22
0
/**
 * gst_adapter_copy_bytes: (rename-to gst_adapter_copy)
 * @adapter: a #GstAdapter
 * @offset: the bytes offset in the adapter to start from
 * @size: the number of bytes to copy
 *
 * Similar to gst_adapter_copy, but more suitable for language bindings. @size
 * bytes of data starting at @offset will be copied out of the buffers contained
 * in @adapter and into a new #GBytes structure which is returned. Depending on
 * the value of the @size argument an empty #GBytes structure may be returned.
 *
 * Returns: (transfer full): A new #GBytes structure containing the copied data.
 *
 * Since: 1.4
 */
GBytes *
gst_adapter_copy_bytes (GstAdapter * adapter, gsize offset, gsize size)
{
  gpointer data;
  data = g_malloc (size);
  gst_adapter_copy (adapter, data, offset, size);
  return g_bytes_new_take (data, size);
}
Beispiel #23
0
/**
 * CacheUtilRandomBytes:
 * @size: Number of bytes to return.
 *
 * Returns: @size bytes of random data.
 */
GBytes *CacheUtilRandomBytes(gsize size) {
  // Create an array of ints a little longer than @size bytes and fill it with
  // random numbers. Each array element covers 4 bytes of the final result.
  gsize random_ints_len = size / 4 + 1;
  guint32 *random_ints = g_new(guint32, random_ints_len);
  for (guint i = 0; i < random_ints_len; i++) {
    random_ints[i] = g_random_int();
  }
  return g_bytes_new_take(random_ints, size);
}
Beispiel #24
0
/**
 * g_byte_array_free_to_bytes:
 * @array: (transfer full): a #GByteArray
 *
 * Transfers the data from the #GByteArray into a new immutable #GBytes.
 *
 * The #GByteArray is freed unless the reference count of @array is greater
 * than one, the #GByteArray wrapper is preserved but the size of @array
 * will be set to zero.
 *
 * This is identical to using g_bytes_new_take() and g_byte_array_free()
 * together.
 *
 * Since: 2.32
 *
 * Returns: (transfer full): a new immutable #GBytes representing same
 *     byte data that was in the array
 */
GBytes*
g_byte_array_free_to_bytes (GByteArray *array)
{
  gsize length;

  g_return_val_if_fail (array != NULL, NULL);

  length = array->len;
  return g_bytes_new_take (g_byte_array_free (array, FALSE), length);
}
Beispiel #25
0
static GBytes *
gdk_pixbuf_make_bytes (GdkPixbuf  *pixbuf,
                       GError    **error)
{
  gchar *buffer;
  gsize size;

  if (!gdk_pixbuf_save_to_buffer (pixbuf, &buffer, &size, "png", error, NULL))
    return NULL;

  return g_bytes_new_take (buffer, size);
}
Beispiel #26
0
static GBytes *
dfu_patch_calculate_checksum (GBytes *blob)
{
	const guchar *data;
	gsize digest_len = 20;
	gsize sz = 0;
	guint8 *buf = g_malloc0 (digest_len);
	g_autoptr(GChecksum) csum = NULL;
	csum = g_checksum_new (G_CHECKSUM_SHA1);
	data = g_bytes_get_data (blob, &sz);
	g_checksum_update (csum, data, (gssize) sz);
	g_checksum_get_digest (csum, buf, &digest_len);
	return g_bytes_new_take (buf, digest_len);
}
gboolean
_gum_duk_parse_bytes (duk_context * ctx,
                      duk_idx_t index,
                      GBytes ** bytes)
{
  gpointer data;
  duk_size_t size;

  data = duk_get_buffer_data (ctx, index, &size);
  if (data != NULL)
  {
    *bytes = g_bytes_new (data, size);
    return TRUE;
  }
  else if (duk_is_array (ctx, index))
  {
    duk_size_t i;

    duk_get_prop_string (ctx, index, "length");
    size = duk_get_uint (ctx, -1);
    duk_pop (ctx);

    if (size >= GUM_MAX_JS_BYTE_ARRAY_LENGTH)
      return FALSE;

    data = g_malloc (size);

    for (i = 0; i != size; i++)
    {
      duk_get_prop_index (ctx, index, (duk_uarridx_t) i);
      ((guint8 *) data)[i] = duk_get_uint (ctx, -1) & 0xff;
      duk_pop (ctx);
    }

    *bytes = g_bytes_new_take (data, size);
    return TRUE;
  }
  else if (duk_is_null_or_undefined (ctx, index) ||
      duk_is_boolean (ctx, index) ||
      duk_is_number (ctx, index) ||
      duk_is_nan (ctx, index) ||
      duk_is_string (ctx, index) ||
      duk_is_function (ctx, index))
  {
    return FALSE;
  }

  *bytes = g_bytes_new (NULL, 0);
  return TRUE;
}
Beispiel #28
0
/**
 * ostree_bloom_seal:
 * @bloom: an #OstreeBloom
 *
 * Seal a constructed bloom filter, so that elements may no longer be added to
 * it, and queries can now be performed against it. The serialised form of the
 * bloom filter is returned as a bit array. Note that this does not include
 * information about the filter hash function or parameters; the caller is
 * responsible for serialising those separately if appropriate.
 *
 * It is safe to call this function multiple times.
 *
 * Returns: (transfer full): a #GBytes containing the immutable filter data
 * Since: 2017.8
 */
GBytes *
ostree_bloom_seal (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, NULL);
  g_return_val_if_fail (bloom->ref_count >= 1, NULL);

  if (bloom->is_mutable)
    {
      bloom->is_mutable = FALSE;
      bloom->immutable_bytes = g_bytes_new_take (g_steal_pointer (&bloom->mutable_bytes), bloom->n_bytes);
    }

  return g_bytes_ref (bloom->immutable_bytes);
}
Beispiel #29
0
static void
setup (Test *test,
       gconstpointer data)
{
	const gchar *filename = data;
	GError *error = NULL;
	gchar *contents;
	gsize length;

	g_file_get_contents (filename, (gchar**)&contents, &length, &error);
	g_assert_no_error (error);

	test->data = g_bytes_new_take (contents, length);
}
static GBytes *
_json_builder_to_bytes (CockpitDBusJson1 *self,
                        JsonBuilder *builder)
{
  JsonNode *root;
  gsize length;
  gchar *ret;

  root = json_builder_get_root (builder);
  ret = cockpit_json_write (root, &length);
  json_node_free (root);

  return g_bytes_new_take (ret, length);
}