Ejemplo n.º 1
0
static void test_type(const char *type) {
        CVariant *cv;
        GVariant *gv;
        GBytes *cb, *gb;
        const void *cd, *gd;

        test_generate(type, &cv, &gv);

        cb = test_cv_get_data_as_bytes(cv);
        gb = g_variant_get_data_as_bytes(gv);

        if (g_bytes_compare(cb, gb)) {
                fprintf(stderr, "FAILED: %s\n", type);

                cd = g_bytes_get_data(cb, NULL);
                gd = g_bytes_get_data(gb, NULL);

                fprintf(stderr, "Buffers: %p:%zu %p:%zu\n",
                        cd, g_bytes_get_size(cb),
                        gd, g_bytes_get_size(gb));

                test_print_cv(cv);
                assert(0);
        }

        test_compare(cv, gv);

        g_bytes_unref(gb);
        g_bytes_unref(cb);
        g_variant_unref(gv);
        c_variant_free(cv);
}
Ejemplo n.º 2
0
/**
 * _g_bytes_compare_verbose:
 **/
static gchar *
_g_bytes_compare_verbose (GBytes *bytes1, GBytes *bytes2)
{
	const guint8 *data1;
	const guint8 *data2;
	gsize length1;
	gsize length2;
	guint i;

	data1 = g_bytes_get_data (bytes1, &length1);
	data2 = g_bytes_get_data (bytes2, &length2);

	/* not the same length */
	if (length1 != length2) {
		return g_strdup_printf ("got %" G_GSIZE_FORMAT " bytes, "
					"expected %" G_GSIZE_FORMAT,
					length1, length2);
	}

	/* return 00 01 02 03 */
	for (i = 0; i < length1; i++) {
		if (data1[i] != data2[i]) {
			return g_strdup_printf ("got 0x%02x, expected 0x%02x @ 0x%04x",
						data1[i], data2[i], i);
		}
	}
	return NULL;
}
static void
g_tls_client_connection_gnutls_begin_handshake (GTlsConnectionGnutls *conn)
{
  GTlsClientConnectionGnutls *gnutls = G_TLS_CLIENT_CONNECTION_GNUTLS (conn);

  /* Try to get a cached session */
  if (gnutls->priv->session_data_override)
    {
      gnutls_session_set_data (g_tls_connection_gnutls_get_session (conn),
                               g_bytes_get_data (gnutls->priv->session_data, NULL),
                               g_bytes_get_size (gnutls->priv->session_data));
    }
  else if (gnutls->priv->session_id)
    {
      GBytes *session_data;

      session_data = g_tls_backend_gnutls_lookup_session (GNUTLS_CLIENT, gnutls->priv->session_id);
      if (session_data)
	{
	  gnutls_session_set_data (g_tls_connection_gnutls_get_session (conn),
				   g_bytes_get_data (session_data, NULL),
				   g_bytes_get_size (session_data));
          g_clear_pointer (&gnutls->priv->session_data, g_bytes_unref);
          gnutls->priv->session_data = session_data;
	}
    }

  gnutls->priv->cert_requested = FALSE;
}
Ejemplo n.º 4
0
void test_rsa(void)
{
  // my keys
  MegaAesKey* mk = mega_aes_key_new_from_ubase64(MY_MASTER_KEY);
  MegaRsaKey* rk = mega_rsa_key_new();
  
  g_assert(mega_rsa_key_load_enc_privk(rk, MY_PRIVK_ENC, mk));
  g_assert(mega_rsa_key_load_pubk(rk, MY_PUBK));

  GBytes* sid_bytes = mega_rsa_key_decrypt(rk, MY_CSID);
  g_assert_cmpuint(g_bytes_get_size(sid_bytes), >=, 43);
  gchar* sid = mega_base64urlencode(g_bytes_get_data(sid_bytes, NULL), 43);
  g_assert_cmpstr(sid, ==, MY_SID);

  g_assert_cmpstr(mega_rsa_key_get_pubk(rk), ==, MY_PUBK);
  // last block can be different, because it's random padded
  g_assert_cmpstr(trim_last_block(mega_rsa_key_get_enc_privk(rk, mk)), ==, trim_last_block(MY_PRIVK_ENC));

  // test encryption

  guchar plain[16] = {0xff};
  gchar* cipher = mega_rsa_key_encrypt(rk, plain, 16);
  GBytes* plain_bytes = mega_rsa_key_decrypt(rk, cipher);
  g_assert(plain_bytes != NULL);
  g_assert_cmpuint(g_bytes_get_size(plain_bytes), >, 16);
  g_assert(memcmp(g_bytes_get_data(plain_bytes, NULL), plain, 16) == 0);

  // Mega BUG: Plaintext can't start with zero!
  memset(plain, 0, 16);
  cipher = mega_rsa_key_encrypt(rk, plain, 16);
  plain_bytes = mega_rsa_key_decrypt(rk, cipher);
  g_assert(plain_bytes != NULL);
  g_assert_cmpuint(g_bytes_get_size(plain_bytes), >, 16);
  g_assert(memcmp(g_bytes_get_data(plain_bytes, NULL), plain, 16) == 0);

  // generate key

  g_assert(mega_rsa_key_generate(rk));
  gchar* privk1 = mega_rsa_key_get_enc_privk(rk, mk);
  gchar* pubk1 = mega_rsa_key_get_pubk(rk);

  g_assert(mega_rsa_key_generate(rk));
  gchar* privk2 = mega_rsa_key_get_enc_privk(rk, mk);
  gchar* pubk2 = mega_rsa_key_get_pubk(rk);

  g_assert_cmpstr(pubk1, !=, pubk2);
  // last block can be different, because it's random padded
  g_assert_cmpstr(trim_last_block(privk1), !=, trim_last_block(privk2));

  // INVALID USES

  g_assert(!mega_rsa_key_load_enc_privk(rk, MY_CSID, mk));
  g_assert(!mega_rsa_key_load_pubk(rk, MY_CSID));
  g_assert(!mega_rsa_key_load_enc_privk(rk, KEY_INVALID, mk));
  g_assert(!mega_rsa_key_load_pubk(rk, KEY_INVALID));
  g_assert(!mega_rsa_key_load_enc_privk(rk, KEY_NULL, mk));
  g_assert(!mega_rsa_key_load_pubk(rk, KEY_NULL));
}
Ejemplo n.º 5
0
static gboolean
meta_monitor_manager_handle_set_crtc_gamma  (MetaDBusDisplayConfig *skeleton,
                                             GDBusMethodInvocation *invocation,
                                             guint                  serial,
                                             guint                  crtc_id,
                                             GVariant              *red_v,
                                             GVariant              *green_v,
                                             GVariant              *blue_v)
{
  MetaMonitorManager *manager = META_MONITOR_MANAGER (skeleton);
  MetaMonitorManagerClass *klass;
  MetaCRTC *crtc;
  gsize size, dummy;
  unsigned short *red;
  unsigned short *green;
  unsigned short *blue;
  GBytes *red_bytes, *green_bytes, *blue_bytes;

  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];

  red_bytes = g_variant_get_data_as_bytes (red_v);
  green_bytes = g_variant_get_data_as_bytes (green_v);
  blue_bytes = g_variant_get_data_as_bytes (blue_v);

  size = g_bytes_get_size (red_bytes) / sizeof (unsigned short);
  red = (unsigned short*) g_bytes_get_data (red_bytes, &dummy);
  green = (unsigned short*) g_bytes_get_data (green_bytes, &dummy);
  blue = (unsigned short*) g_bytes_get_data (blue_bytes, &dummy);

  klass = META_MONITOR_MANAGER_GET_CLASS (manager);
  if (klass->set_crtc_gamma)
    klass->set_crtc_gamma (manager, crtc, size, red, green, blue);

  meta_dbus_display_config_complete_set_crtc_gamma (skeleton, invocation);

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

  return TRUE;
}
Ejemplo n.º 6
0
static CK_RV
trust_get_hash (GkmXdgTrust *self, GChecksumType ctype, CK_ATTRIBUTE_PTR attr)
{
	GNode *cert;
	GBytes *element;
	CK_RV rv;

	cert = egg_asn1x_node (self->pv->asn, "reference", "certComplete", NULL);
	g_return_val_if_fail (cert, CKR_GENERAL_ERROR);

	/* If it's not stored, then this attribute is not present */
	if (!egg_asn1x_have (cert)) {
		gkm_debug ("CKR_ATTRIBUTE_TYPE_INVALID: %s wants certComplete which is not part of assertion",
		           gkm_log_attr_type (attr->type));
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	element = egg_asn1x_get_element_raw (cert);
	g_return_val_if_fail (element != NULL, CKR_GENERAL_ERROR);

	rv = gkm_attribute_set_checksum (attr, ctype,
	                                 g_bytes_get_data (element, NULL),
	                                 g_bytes_get_size (element));

	g_bytes_unref (element);
	return rv;
}
gboolean
tpaw_xml_validate_from_resource (xmlDoc *doc,
    const gchar *dtd_resourcename)
{
  GBytes *resourcecontents;
  gconstpointer resourcedata;
  gsize resourcesize;
  xmlParserInputBufferPtr buffer;
  xmlValidCtxt  cvp;
  xmlDtd *dtd;
  GError *error = NULL;
  gboolean ret;

  DEBUG ("Loading dtd resource %s", dtd_resourcename);

  resourcecontents = g_resources_lookup_data (dtd_resourcename, G_RESOURCE_LOOKUP_FLAGS_NONE, &error);
  if (error != NULL)
    {
      g_warning ("Unable to load dtd resource '%s': %s", dtd_resourcename, error->message);
      g_error_free (error);
      return FALSE;
    }
  resourcedata = g_bytes_get_data (resourcecontents, &resourcesize);
  buffer = xmlParserInputBufferCreateStatic (resourcedata, resourcesize, XML_CHAR_ENCODING_UTF8);

  memset (&cvp, 0, sizeof (cvp));
  dtd = xmlIOParseDTD (NULL, buffer, XML_CHAR_ENCODING_UTF8);
  ret = xmlValidateDtd (&cvp, doc, dtd);

  xmlFreeDtd (dtd);
  g_bytes_unref (resourcecontents);

  return ret;
}
static void on_sequence_complete(GIO_ASYNCSEQ_HANDLE async_seq_handle, gpointer previous_result)
{
    READ_CONTEXT* context = (READ_CONTEXT*)GIO_Async_Seq_GetContext(async_seq_handle);
    GBytes* data = (GBytes*)previous_result;
    const unsigned char* buffer;
    size_t size;

    if (data != NULL)
    {
        buffer = g_bytes_get_data(data, &size);
    }
    else
    {
        buffer = NULL;
        size = 0;
    }

    /*Codes_SRS_BLEIO_GATT_13_032: [ BLEIO_gatt_read_char_by_uuid shall invoke on_bleio_gatt_attrib_read_complete when the read operation completes. ]*/
    /*Codes_SRS_BLEIO_GATT_13_033: [ BLEIO_gatt_read_char_by_uuid shall pass the value of the callback_context parameter to on_bleio_gatt_attrib_read_complete as the context parameter when it is invoked. ]*/
    /*Codes_SRS_BLEIO_GATT_13_034: [BLEIO_gatt_read_char_by_uuid, when successful, shall supply the data that has been read to the on_bleio_gatt_attrib_read_complete callback along with the value BLEIO_GATT_OK for the result parameter.]*/
    context->on_read_complete(
        (BLEIO_GATT_HANDLE)context->handle_data,
        context->callback_context,
        BLEIO_GATT_OK,
        buffer,
        size
    );

    g_bytes_unref(data);
    free_context(context);
}
Ejemplo n.º 9
0
static void
nmc_convert_bytes_to_string (const GValue *src_value, GValue *dest_value)
{
	GBytes *bytes;
	const guint8 *array;
	gsize length;
	GString *printable;
	guint i = 0;

	bytes = g_value_get_boxed (src_value);

	printable = g_string_new ("[");

	if (bytes) {
		array = g_bytes_get_data (bytes, &length);
		while (i < MIN (length, 35)) {
			if (i > 0)
				g_string_append_c (printable, ' ');
			g_string_append_printf (printable, "0x%02X", array[i++]);
		}
		if (i < length)
			g_string_append (printable, " ... ");
	}
	g_string_append_c (printable, ']');

	g_value_take_string (dest_value, g_string_free (printable, FALSE));
}
Ejemplo n.º 10
0
static GBytes *
check_utf8_and_force_if_necessary (GBytes *input)
{
  const gchar *data;
  const gchar *end;
  gsize length;
  GString *string;

  data = g_bytes_get_data (input, &length);
  if (g_utf8_validate (data, length, &end))
    return g_bytes_ref (input);

  string = g_string_sized_new (length + 16);
  do
    {
      /* Valid part of the string */
      g_string_append_len (string, data, end - data);

      /* Replacement character */
      g_string_append (string, "\xef\xbf\xbd");

      length -= (end - data) + 1;
      data = end + 1;
    }
  while (!g_utf8_validate (data, length, &end));

  if (length)
    g_string_append_len (string, data, length);

  return g_string_free_to_bytes (string);
}
Ejemplo n.º 11
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);
}
Ejemplo n.º 12
0
void
mpid_read_device_file (MPIDDevice *device, const char *device_info_path)
{
	GError *error = NULL;
	GKeyFile *keyfile;
	GBytes *bytes;
	gsize len;
	const void *data;

	keyfile = g_key_file_new ();
	bytes = g_resources_lookup_data (device_info_path, G_RESOURCE_LOOKUP_FLAGS_NONE, &error);
	if (bytes != NULL) {
		data = g_bytes_get_data (bytes, &len);

		if (g_key_file_load_from_data (keyfile, data, len, G_KEY_FILE_NONE, &error) == FALSE) {
			mpid_debug ("unable to read device info resource %s: %s\n", device_info_path, error->message);
			g_clear_error (&error);
			device->error = MPID_ERROR_DEVICE_INFO_MISSING;
			g_bytes_unref (bytes);
			return;
		}
	} else if (g_key_file_load_from_file (keyfile, device_info_path, G_KEY_FILE_NONE, &error) == FALSE) {
		mpid_debug ("unable to read device info file %s: %s\n", device_info_path, error->message);
		g_clear_error (&error);
		device->error = MPID_ERROR_DEVICE_INFO_MISSING;
		return;
	}

	mpid_read_keyfile (device, keyfile);
	g_key_file_free (keyfile);
}
Ejemplo n.º 13
0
/**
 * fu_sign_process_file_cab:
 **/
static gboolean
fu_sign_process_file_cab (FuSignPrivate *priv,
			  const gchar *fn_src,
			  const gchar *fn_dst,
			  GError **error)
{
	gsize fw_len = 0;
	_cleanup_bytes_unref_ GBytes *fw = NULL;
	_cleanup_bytes_unref_ GBytes *sig = NULL;
	_cleanup_free_ gchar *fw_data = NULL;
	_cleanup_free_ gchar *fn_bin_asc = NULL;
	_cleanup_object_unref_ FuCab *cab = NULL;
	_cleanup_object_unref_ GFile *src = NULL;
	_cleanup_object_unref_ GFile *dst = NULL;
	const gchar *fn_bin;

	g_info ("processing %s", fn_src);

	/* open the .cab file and extract firmware */
	cab = fu_cab_new ();
	src = g_file_new_for_path (fn_src);
	if (!fu_cab_load_file (cab, src, NULL, error))
		return FALSE;
	if (!fu_cab_extract (cab, FU_CAB_EXTRACT_FLAG_ALL, error))
		return FALSE;

	/* sign the .bin */
	fn_bin = fu_cab_get_filename_firmware (cab);
	g_info ("signing %s with key %s", fn_bin, priv->key_id);
	if (!g_file_get_contents (fn_bin, &fw_data, &fw_len, error))
		return FALSE;
	fw = g_bytes_new_static (fw_data, fw_len);
	sig = fu_keyring_sign_data (priv->keyring, fw, error);
	if (sig == NULL)
		return FALSE;

	/* write new detached signature */
	fn_bin_asc = g_strdup_printf ("%s.asc", fn_bin);
	g_debug ("writing to %s", fn_bin_asc);
	if (!g_file_set_contents (fn_bin_asc,
				  g_bytes_get_data (sig, NULL),
				  g_bytes_get_size (sig),
				  error))
		return FALSE;

	/* add to file list */
	fu_cab_add_file (cab, fn_bin_asc);

	/* add the detached signature to the .cab file */
	g_debug ("saving %s", fn_dst);
	dst = g_file_new_for_path (fn_dst);
	if (!fu_cab_save_file (cab, dst, NULL, error))
		return FALSE;

	/* delete the working space */
	g_unlink (fn_bin_asc);
	if (!fu_cab_delete_temp_files (cab, error))
		return FALSE;
	return TRUE;
}
Ejemplo n.º 14
0
/**
 * fu_sign_process_file_xml:
 **/
static gboolean
fu_sign_process_file_xml (FuSignPrivate *priv,
			  const gchar *fn_src,
			  const gchar *fn_dst,
			  GError **error)
{
	gsize xml_len = 0;
	_cleanup_bytes_unref_ GBytes *xml = NULL;
	_cleanup_bytes_unref_ GBytes *sig = NULL;
	_cleanup_free_ gchar *xml_data = NULL;

	/* sign the firmware */
	g_info ("signing %s with key %s", fn_src, priv->key_id);
	if (!g_file_get_contents (fn_src, &xml_data, &xml_len, error))
		return FALSE;
	xml = g_bytes_new_static (xml_data, xml_len);
	sig = fu_keyring_sign_data (priv->keyring, xml, error);
	if (sig == NULL)
		return FALSE;

	/* write new detached signature */
	g_debug ("writing to %s", fn_dst);
	if (!g_file_set_contents (fn_dst,
				  g_bytes_get_data (sig, NULL),
				  g_bytes_get_size (sig),
				  error))
		return FALSE;
	return TRUE;
}
gboolean
_ostree_static_delta_part_execute (OstreeRepo      *repo,
                                   GVariant        *header,
                                   GBytes          *part_bytes,
                                   GCancellable    *cancellable,
                                   GError         **error)
{
  gboolean ret = FALSE;
  gsize partlen;
  const guint8*partdata;
  gs_unref_bytes GBytes *part_payload_bytes = NULL;
  gs_unref_bytes GBytes *payload_data = NULL;
  gs_unref_variant GVariant *payload = NULL;
  guint8 comptype;

  partdata = g_bytes_get_data (part_bytes, &partlen);
  
  if (partlen < 1)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Corrupted 0 length delta part");
      goto out;
    }
        
  /* First byte is compression type */
  comptype = partdata[0];
  /* Then the rest may be compressed or uncompressed */
  part_payload_bytes = g_bytes_new_from_bytes (part_bytes, 1, partlen - 1);
  switch (comptype)
    {
    case 0:
      /* No compression */
      payload_data = g_bytes_ref (part_payload_bytes);
      break;
    case 'x':
      {
        gs_unref_object GConverter *decomp =
          (GConverter*) _ostree_lzma_decompressor_new ();

        if (!decompress_all (decomp, part_payload_bytes, &payload_data,
                             cancellable, error))
          goto out;
      }
      break;
    default:
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Invalid compression type '%u'", comptype);
      goto out;
    }
        
  payload = g_variant_new_from_bytes (G_VARIANT_TYPE (OSTREE_STATIC_DELTA_PART_PAYLOAD_FORMAT_V0),
                                      payload_data, FALSE);
  if (!_ostree_static_delta_part_execute_raw (repo, header, payload,
                                              cancellable, error))
    goto out;

  ret = TRUE;
 out:
  return ret;
}
Ejemplo n.º 16
0
static const GstCencKeyPair*
gst_cenc_decrypt_lookup_key (GstCencDecrypt * self, GstBuffer * kid)
{
  GstMapInfo info;
  const GstCencKeyPair *kp=NULL;
  int i;
  gsize sz;

  /*
    GstMapInfo info;
    gchar *id_string;
    gst_buffer_map (kid, &info, GST_MAP_READ);
    id_string = gst_cenc_create_uuid_string (info.data);
    GST_DEBUG_OBJECT (self, "Looking up key ID: %s", id_string);
    g_free (id_string);
    gst_buffer_unmap (kid, &info);
  */
  for (i = 0; kp==NULL && i < self->keys->len; ++i) {
    const GstCencKeyPair *k;
    k = g_ptr_array_index (self->keys, i);
    if(gst_buffer_memcmp (kid, 0, g_bytes_get_data (k->key_id, NULL), KEY_LENGTH)==0){
      kp=k;
    }
  }
  if (!kp) {
    kp = gst_cenc_decrypt_get_key (self, kid);
  }

  return kp;
}
Ejemplo n.º 17
0
/**
 * gcr_fingerprint_from_attributes:
 * @attrs: attributes for key or certificate
 * @checksum_type: the type of fingerprint to create
 * @n_fingerprint: the length of fingerprint returned
 *
 * Create a key fingerprint for a certificate, public key or private key.
 * Note that this is not a fingerprint of certificate data, which you would
 * use gcr_certificate_get_fingerprint() for.
 *
 * Returns: (transfer full) (allow-none) (array length=n_fingerprint): the
 *          fingerprint or %NULL if the input was invalid.
 */
guchar *
gcr_fingerprint_from_attributes (GckAttributes *attrs,
                                 GChecksumType checksum_type,
                                 gsize *n_fingerprint)
{
	gpointer fingerprint = NULL;
	GBytes *info;
	GNode *asn;

	g_return_val_if_fail (attrs != NULL, NULL);
	g_return_val_if_fail (n_fingerprint, NULL);

	asn = _gcr_subject_public_key_for_attributes (attrs);

	if (asn != NULL) {
		info = egg_asn1x_encode (asn, NULL);
		fingerprint = gcr_fingerprint_from_subject_public_key_info (g_bytes_get_data (info, NULL),
		                                                            g_bytes_get_size (info),
		                                                            checksum_type,
		                                                            n_fingerprint);
		g_bytes_unref (info);
	}

	egg_asn1x_destroy (asn);
	return fingerprint;
}
Ejemplo n.º 18
0
static gboolean
is_binary_data (GBytes *bytes)
{
  gsize length;
  gconstpointer data = g_bytes_get_data (bytes, &length);
  return (memchr (data, '\0', length) != NULL);
}
Ejemplo n.º 19
0
/**
 * dfu_firmware_from_dfuse: (skip)
 * @firmware: a #DfuFirmware
 * @bytes: data to parse
 * @flags: some #DfuFirmwareParseFlags
 * @error: a #GError, or %NULL
 *
 * Unpacks into a firmware object from DfuSe data.
 *
 * Returns: %TRUE for success
 **/
gboolean
dfu_firmware_from_dfuse (DfuFirmware *firmware,
			 GBytes *bytes,
			 DfuFirmwareParseFlags flags,
			 GError **error)
{
	DfuSePrefix *prefix;
	gsize len;
	guint32 offset = sizeof(DfuSePrefix);
	guint8 *data;

	/* check the prefix (BE) */
	data = (guint8 *) g_bytes_get_data (bytes, &len);
	prefix = (DfuSePrefix *) data;
	if (memcmp (prefix->sig, "DfuSe", 5) != 0) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INTERNAL,
				     "invalid DfuSe prefix");
		return FALSE;
	}

	/* check the version */
	if (prefix->ver != 0x01) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INTERNAL,
			     "invalid DfuSe version, got %02x",
			     prefix->ver);
		return FALSE;
	}

	/* check image size */
	if (GUINT32_FROM_LE (prefix->image_size) != len) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INTERNAL,
			     "invalid DfuSe image size, "
			     "got %" G_GUINT32_FORMAT ", "
			     "expected %" G_GSIZE_FORMAT,
			     GUINT32_FROM_LE (prefix->image_size),
			     len);
		return FALSE;
	}

	/* parse the image targets */
	len -= sizeof(DfuSePrefix);
	for (guint i = 0; i < prefix->targets; i++) {
		guint consumed;
		g_autoptr(DfuImage) image = NULL;
		image = dfu_image_from_dfuse (data + offset, (guint32) len,
					      &consumed, error);
		if (image == NULL)
			return FALSE;
		dfu_firmware_add_image (firmware, image);
		offset += consumed;
		len -= consumed;
	}
	return TRUE;
}
Ejemplo n.º 20
0
/**
 * g_variant_new_from_bytes:
 * @type: a #GVariantType
 * @bytes: a #GBytes
 * @trusted: if the contents of @bytes are trusted
 *
 * Constructs a new serialised-mode #GVariant instance.  This is the
 * inner interface for creation of new serialised values that gets
 * called from various functions in gvariant.c.
 *
 * A reference is taken on @bytes.
 *
 * Returns: a new #GVariant with a floating reference
 *
 * Since: 2.36
 */
GVariant *
g_variant_new_from_bytes (const GVariantType *type,
                          GBytes             *bytes,
                          gboolean            trusted)
{
  GVariant *value;
  guint alignment;
  gsize size;

  value = g_variant_alloc (type, TRUE, trusted);

  value->contents.serialised.bytes = g_bytes_ref (bytes);

  g_variant_type_info_query (value->type_info,
                             &alignment, &size);

  if (size && g_bytes_get_size (bytes) != size)
    {
      /* Creating a fixed-sized GVariant with a bytes of the wrong
       * size.
       *
       * We should do the equivalent of pulling a fixed-sized child out
       * of a brozen container (ie: data is NULL size is equal to the correct
       * fixed size).
       */
      value->contents.serialised.data = NULL;
      value->size = size;
    }
  else
    {
      value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
    }

  return value;
}
Ejemplo n.º 21
0
/**
 * cockpit_transport_parse_frame:
 * @message: message to parse
 * @channel: location to return the channel
 *
 * Parse a message into a channel and payload.
 * @channel will be set to NULL if a control channel
 * message. @channel must be freed.
 *
 * Will return NULL if invalid message.
 *
 * Returns: (transfer full): the payload or NULL.
 */
GBytes *
cockpit_transport_parse_frame (GBytes *message,
                               gchar **channel)
{
  const gchar *data;
  gsize length;
  const gchar *line;
  gsize channel_len;

  g_return_val_if_fail (message != NULL, NULL);

  data = g_bytes_get_data (message, &length);
  line = memchr (data, '\n', length);
  if (!line)
    {
      g_warning ("Received invalid message without channel prefix");
      return NULL;
    }

  channel_len = line - data;
  if (memchr (data, '\0', channel_len) != NULL)
    {
      g_warning ("Received massage with invalid channel prefix");
      return NULL;
    }

  if (channel_len)
    *channel = g_strndup (data, channel_len);
  else
    *channel = NULL;

  channel_len++;
  return g_bytes_new_from_bytes (message, channel_len, length - channel_len);
}
Ejemplo n.º 22
0
guint32
fu_wac_calculate_checksum32le_bytes (GBytes *blob)
{
	gsize len = 0;
	const guint8 *data = g_bytes_get_data (blob, &len);
	return fu_wac_calculate_checksum32le (data, len);
}
Ejemplo n.º 23
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);
}
Ejemplo n.º 24
0
static void
_gth_window_add_css_provider (GtkWidget  *widget,
			      const char *path)
{
	GBytes         *bytes;
	gconstpointer   css_data;
	gsize           css_data_size;
	GtkCssProvider *css_provider;
	GError         *error = NULL;


	bytes = g_resources_lookup_data (path, 0, &error);
	if (bytes == NULL) {
		g_warning ("%s", error->message);
		g_error_free (error);
		return;
	}

	css_data = g_bytes_get_data (bytes, &css_data_size);
	css_provider = gtk_css_provider_new ();
	if (! gtk_css_provider_load_from_data (css_provider, css_data, css_data_size, &error)) {
		g_warning ("%s", error->message);
		g_error_free (error);
	}
	gtk_style_context_add_provider_for_screen (gtk_widget_get_screen (widget),
						   GTK_STYLE_PROVIDER (css_provider),
						   GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

	g_object_unref (css_provider);
	g_bytes_unref (bytes);
}
Ejemplo n.º 25
0
Archivo: ui.c Proyecto: imgflo/imgflo
static void
on_web_socket_message(SoupWebsocketConnection *ws,
                      SoupWebsocketDataType type,
                      GBytes *message,
                      void *user_data)
{
	const gchar *data;
	gsize len;

	data = g_bytes_get_data (message, &len);
	imgflo_debug("RECV: %.*s\n", (int)len, data);

    JsonParser *parser = json_parser_new();
    gboolean success = json_parser_load_from_data(parser, data, len, NULL);
    if (success) {
        JsonNode *r = json_parser_get_root(parser);
        g_assert(JSON_NODE_HOLDS_OBJECT(r));
        JsonObject *root = json_node_get_object(r);

        const gchar *protocol = json_object_get_string_member(root, "protocol");
        const gchar *command = json_object_get_string_member(root, "command");

        JsonNode *pnode = json_object_get_member(root, "payload");
        JsonObject *payload = JSON_NODE_HOLDS_OBJECT(pnode) ? json_object_get_object_member(root, "payload") : NULL;

        UiConnection *ui = (UiConnection *)user_data;
        ui_connection_handle_message(ui, protocol, command, payload, ws);

    } else {
        imgflo_warning("Unable to parse WebSocket message as JSON");
    }

    g_object_unref(parser);
}
Ejemplo n.º 26
0
static void
on_mechanism_check (GObject *source,
                    GAsyncResult *result,
                    gpointer user_data)
{
	GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
	CompleteClosure *closure = g_simple_async_result_get_op_res_gpointer (res);

	closure->mechanism.type =  _gcr_key_mechanisms_check_finish (closure->request->private_key,
	                                                             result, NULL);
	if (closure->mechanism.type == GCK_INVALID) {
		g_simple_async_result_set_error (res, GCK_ERROR, CKR_KEY_TYPE_INCONSISTENT,
		                                 _("The key cannot be used to sign the request"));
		g_simple_async_result_complete (res);

	} else {
		closure->tbs = prepare_to_be_signed (closure->request, &closure->mechanism);
		gck_session_sign_async (closure->session,
		                        closure->request->private_key,
		                        &closure->mechanism,
		                        g_bytes_get_data (closure->tbs, NULL),
		                        g_bytes_get_size (closure->tbs),
		                        closure->cancellable,
		                        on_certificate_request_signed,
		                        g_object_ref (res));
	}

	g_object_unref (res);
}
static gnutls_datum_t
g_tls_server_connection_gnutls_db_retrieve (void            *user_data,
					    gnutls_datum_t   key)
{
  GBytes *session_id, *session_data;
  gnutls_datum_t data;

  session_id = g_bytes_new (key.data, key.size);
  session_data = g_tls_backend_gnutls_lookup_session (GNUTLS_SERVER, session_id);
  g_bytes_unref (session_id);

  if (session_data)
    {
      data.size = g_bytes_get_size (session_data);
      data.data = gnutls_malloc (data.size);
      memcpy (data.data, g_bytes_get_data (session_data, NULL), data.size);
      g_bytes_unref (session_data);
    }
  else
    {
      data.size = 0;
      data.data = NULL;
    }

  return data;
}
static gboolean
add_wep_key (NMSupplicantConfig *self,
             const char *key,
             const char *name,
             NMWepKeyType wep_type)
{
    GBytes *bytes;
    gboolean success = FALSE;
    size_t key_len = key ? strlen (key) : 0;

    if (!key || !key_len)
        return TRUE;

    if (wep_type == NM_WEP_KEY_TYPE_UNKNOWN) {
        if (nm_utils_wep_key_valid (key, NM_WEP_KEY_TYPE_KEY))
            wep_type = NM_WEP_KEY_TYPE_KEY;
        else if (nm_utils_wep_key_valid (key, NM_WEP_KEY_TYPE_PASSPHRASE))
            wep_type = NM_WEP_KEY_TYPE_PASSPHRASE;
    }

    if (   (wep_type == NM_WEP_KEY_TYPE_UNKNOWN)
            || (wep_type == NM_WEP_KEY_TYPE_KEY)) {
        if ((key_len == 10) || (key_len == 26)) {
            bytes = nm_utils_hexstr2bin (key);
            if (bytes) {
                success = nm_supplicant_config_add_option (self,
                          name,
                          g_bytes_get_data (bytes, NULL),
                          g_bytes_get_size (bytes),
                          TRUE);
                g_bytes_unref (bytes);
            }
            if (!success) {
                nm_log_warn (LOGD_SUPPLICANT, "Error adding %s to supplicant config.", name);
                return FALSE;
            }
        } else if ((key_len == 5) || (key_len == 13)) {
            if (!nm_supplicant_config_add_option (self, name, key, key_len, TRUE)) {
                nm_log_warn (LOGD_SUPPLICANT, "Error adding %s to supplicant config.", name);
                return FALSE;
            }
        } else {
            nm_log_warn (LOGD_SUPPLICANT, "Invalid WEP key '%s'", name);
            return FALSE;
        }
    } else if (wep_type == NM_WEP_KEY_TYPE_PASSPHRASE) {
        guint8 digest[16];
        size_t digest_len = sizeof (digest);

        success = wep128_passphrase_hash (key, key_len, digest, &digest_len);
        if (success)
            success = nm_supplicant_config_add_option (self, name, (const char *) digest, digest_len, TRUE);
        if (!success) {
            nm_log_warn (LOGD_SUPPLICANT, "Error adding %s to supplicant config.", name);
            return FALSE;
        }
    }

    return TRUE;
}
Ejemplo n.º 29
0
static void
on_istream_read_complete (GObject           *src,
			  GAsyncResult      *res,
			  gpointer           user_data)
{
  HotSshTab *self = user_data;
  HotSshTabPrivate *priv = hotssh_tab_get_instance_private (self);
  gs_unref_bytes GBytes *result = NULL;
  GError *local_error = NULL;
  const guint8 *buf;
  gsize len;

  result = g_input_stream_read_bytes_finish ((GInputStream*)src, res, &local_error);
  if (!result)
    goto out;

  buf = g_bytes_get_data (result, &len);
  g_debug ("read %u bytes", (guint)len);
  
  vte_terminal_feed ((VteTerminal*)priv->terminal, (char*)buf, len);

  g_input_stream_read_bytes_async ((GInputStream*)src, 8192, G_PRIORITY_DEFAULT,
				   priv->cancellable, on_istream_read_complete, self);

 out:
  if (local_error)
    page_transition_take_error (self, local_error);
}
Ejemplo n.º 30
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);
}