示例#1
0
static void
add_oauth_to_environment (JsonObject *environment)
{
  static const gchar *url;
  JsonObject *object;

  url = cockpit_conf_string ("OAuth", "URL");

  if (url)
    {
      object = json_object_new ();
      json_object_set_string_member (object, "URL", url);
      json_object_set_string_member (object, "ErrorParam",
                                     cockpit_conf_string ("oauth", "ErrorParam"));
      json_object_set_string_member (object, "TokenParam",
                                     cockpit_conf_string ("oauth", "TokenParam"));
      json_object_set_object_member (environment, "OAuth", object);
  }
}
示例#2
0
文件: ui.c 项目: imgflo/imgflo
void
ui_net_state_changed(Network *network, gboolean running,
                     gboolean processing, gpointer user_data) {
    g_return_if_fail(network);

    g_assert(user_data);
    UiConnection *self = (UiConnection *)user_data;

    // TODO: send timestamp/uptime
    JsonObject *info = json_object_new();
    json_object_set_string_member(info, "graph", network->graph->id);
    json_object_set_boolean_member(info, "started", running);
    json_object_set_boolean_member(info, "running", processing);

    const gchar * cmd = (running) ? "started" : "stopped";
    if (self->connection) {
        send_response(self->connection, "network", cmd, info);
    }
}
示例#3
0
static CockpitChannel *
mock_echo_channel_open (CockpitTransport *transport,
                        const gchar *channel_id)
{
  CockpitChannel *channel;
  JsonObject *options;

  g_assert (channel_id != NULL);

  options = json_object_new ();
  channel = g_object_new (mock_echo_channel_get_type (),
                          "transport", transport,
                          "id", channel_id,
                          "options", options,
                          NULL);

  json_object_unref (options);
  return channel;
}
示例#4
0
文件: ui.c 项目: imgflo/imgflo
void
ui_log_handler(const gchar *log_domain, GLogLevelFlags log_level,
                const gchar *message, gpointer user_data) {
    UiConnection *ui = (UiConnection *)user_data;
    g_assert(ui);

    // note, this does not catch errors like
    // g_return_if_fail, as that goes right to g_critical
    // same with unexpected failures inside GEGL and libsoup
    if (ui->connection) {
        const gboolean is_error = (log_level&G_LOG_LEVEL_CRITICAL) || (log_level&G_LOG_LEVEL_WARNING);
        const gboolean is_debug = (log_level&G_LOG_LEVEL_DEBUG) == G_LOG_LEVEL_DEBUG;
        const gchar *cmd = (is_error) ? "error" : "output";
        JsonObject *msg = json_object_new();
        json_object_set_string_member(msg, "message", message);
        if (!is_debug) { // TODO: make configureable?
            send_response_nodebug(ui->connection, "network", cmd, msg);
        }
    }
}
/**
 * couchdb_document_contact_address_new:
 * @uuid: A unique ID
 * @street: Street
 * @ext_street: Extra information for the street
 * @city: City
 * @state: State or region
 * @country: Country
 * @postalcode: Postal code
 * @pobox: Post Office box
 * @description: Description for thos address
 *
 * Returns a #CouchdbStructField representing the given address.
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing
 * the given address information.
 */
CouchdbStructField *
couchdb_document_contact_address_new (const char *uuid,
				      const char *street,
				      const char *ext_street,
				      const char *city,
				      const char *state,
				      const char *country,
				      const char *postalcode,
				      const char *pobox,
				      const char *description)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (street)
		couchdb_document_contact_address_set_street (sf, street);
	if (ext_street)
		couchdb_document_contact_address_set_ext_street (sf, ext_street);
	if (city)
		couchdb_document_contact_address_set_city (sf, city);
	if (state)
		couchdb_document_contact_address_set_state (sf, state);
	if (country)
		couchdb_document_contact_address_set_country (sf, country);
	if (postalcode)
		couchdb_document_contact_address_set_postalcode (sf, postalcode);
	if (pobox)
		couchdb_document_contact_address_set_pobox (sf, pobox);
	if (description)
		couchdb_document_contact_address_set_description (sf, description);

	return sf;
}
示例#6
0
/**
 * json_builder_begin_object:
 * @builder: a #JsonBuilder
 *
 * Opens a subobject inside the given @builder. When done adding members to
 * the subobject, json_builder_end_object() must be called.
 *
 * Can be called for first or only if the call is associated to an object member
 * or an array element.
 *
 * Return value: (transfer none): the #JsonBuilder, or %NULL if the call was inconsistent
 */
JsonBuilder *
json_builder_begin_object (JsonBuilder *builder)
{
  JsonObject *object;
  JsonBuilderState *state;
  JsonBuilderState *cur_state;

  g_return_val_if_fail (JSON_IS_BUILDER (builder), NULL);
  g_return_val_if_fail (builder->priv->root == NULL, NULL);
  g_return_val_if_fail (g_queue_is_empty (builder->priv->stack) || json_builder_is_valid_add_mode (builder), NULL);

  object = json_object_new ();
  cur_state = g_queue_peek_head (builder->priv->stack);
  if (cur_state)
    {
      switch (cur_state->mode)
        {
        case JSON_BUILDER_MODE_ARRAY:
          json_array_add_object_element (cur_state->data.array, json_object_ref (object));
          break;

        case JSON_BUILDER_MODE_MEMBER:
          json_object_set_object_member (cur_state->data.object, cur_state->member_name, json_object_ref (object));
          g_free (cur_state->member_name);
          cur_state->member_name = NULL;
          cur_state->mode = JSON_BUILDER_MODE_OBJECT;
          break;

        default:
          g_assert_not_reached ();
        }
    }

  state = g_slice_new (JsonBuilderState);
  state->data.object = object;
  state->member_name = NULL;
  state->mode = JSON_BUILDER_MODE_OBJECT;
  g_queue_push_head (builder->priv->stack, state);

  return builder;
}
示例#7
0
/**
 * cockpit_channel_done:
 * @self: the channel
 *
 * Send an EOF to the other side. This should only be called once.
 * Whether an EOF should be sent or not depends on the payload type.
 */
void
cockpit_channel_done (CockpitChannel *self)
{
  JsonObject *object;
  GBytes *message;

  g_return_if_fail (COCKPIT_IS_CHANNEL (self));
  g_return_if_fail (self->priv->sent_done == FALSE);

  self->priv->sent_done = TRUE;

  object = json_object_new ();
  json_object_set_string_member (object, "command", "done");
  json_object_set_string_member (object, "channel", self->priv->id);

  message = cockpit_json_write_bytes (object);
  json_object_unref (object);

  cockpit_transport_send (self->priv->transport, NULL, message);
  g_bytes_unref (message);
}
示例#8
0
文件: stub.c 项目: AmartC/cockpit
static void
send_init_command (CockpitTransport *transport)
{
  const gchar *checksum;
  JsonObject *object;
  GBytes *bytes;

  object = json_object_new ();
  json_object_set_string_member (object, "command", "init");
  json_object_set_int_member (object, "version", 1);

  checksum = cockpit_packages_get_checksum (packages);
  if (checksum)
    json_object_set_string_member (object, "checksum", checksum);

  bytes = cockpit_json_write_bytes (object);
  json_object_unref (object);

  cockpit_transport_send (transport, NULL, bytes);
  g_bytes_unref (bytes);
}
/**
 * couchdb_document_contact_email_new:
 * @uuid: A unique ID
 * @address: Email address
 * @description: Description for this email address
 *
 * Returns a #CouchdbStructField object representing an email address:
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing an
 * email address.
 */
CouchdbStructField *
couchdb_document_contact_email_new (const char *uuid, const char *address, const char *description)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (address)
		couchdb_document_contact_email_set_address (sf, address);
	if (description)
		couchdb_document_contact_email_set_description (sf, description);

	return sf;
}
示例#10
0
static void
cockpit_channel_real_close (CockpitChannel *self,
                            const gchar *problem)
{
  JsonObject *object;
  GBytes *message;

  if (self->priv->sent_close)
    return;

  self->priv->sent_close = TRUE;

  if (!self->priv->transport_closed)
    {
      flush_buffer (self);

      if (self->priv->close_options)
        {
          object = self->priv->close_options;
          self->priv->close_options = NULL;
        }
      else
        {
          object = json_object_new ();
        }

      json_object_set_string_member (object, "command", "close");
      json_object_set_string_member (object, "channel", self->priv->id);
      if (problem)
        json_object_set_string_member (object, "problem", problem);

      message = cockpit_json_write_bytes (object);
      json_object_unref (object);

      cockpit_transport_send (self->priv->transport, NULL, message);
      g_bytes_unref (message);
    }

  g_signal_emit (self, cockpit_channel_sig_closed, 0, problem);
}
示例#11
0
static void
send_close_channel (CockpitPortal *self,
                    const gchar *channel_id,
                    const gchar *problem)
{
  JsonObject *object;
  GBytes *bytes;

  g_debug ("sending close for portal channel: %s: %s", channel_id, problem);

  object = json_object_new ();
  json_object_set_string_member (object, "command", "close");
  json_object_set_string_member (object, "channel", channel_id);
  json_object_set_string_member (object, "problem", problem);

  bytes = cockpit_json_write_bytes (object);
  json_object_unref (object);

  if (self->transport)
    cockpit_transport_send (self->transport, NULL, bytes);
  g_bytes_unref (bytes);
}
示例#12
0
PurpleCmdRet flist_reward_cmd(PurpleConversation *convo, const gchar *cmd, gchar **args, gchar **error, void *data) {
    PurpleConnection *pc = purple_conversation_get_gc(convo);
    FListAccount *fla = pc->proto_data;
    const gchar *character;
    JsonObject *json;
    FListFlags flags;

    flags = flist_get_flags(fla, NULL, fla->proper_character);
    if(!(flags & (FLIST_FLAG_ADMIN | FLIST_FLAG_GLOBAL_OP))) {
        *error = g_strdup(_("You must be a global operator to reward a user."));
        return PURPLE_CMD_STATUS_FAILED;
    }

    character = args[0];

    json = json_object_new();
    json_object_set_string_member(json, "character", character);
    flist_request(pc, FLIST_REWARD, json);
    json_object_unref(json);

    return PURPLE_CMD_STATUS_OK;
}
示例#13
0
PurpleCmdRet flist_broadcast_cmd(PurpleConversation *convo, const gchar *cmd, gchar **args, gchar **error, void *data) {
    PurpleConnection *pc = purple_conversation_get_gc(convo);
    FListAccount *fla = pc->proto_data;
    const gchar *message;
    JsonObject *json;
    FListFlags flags;

    flags = flist_get_flags(fla, NULL, fla->proper_character);
    if(!(flags & (FLIST_FLAG_ADMIN))) {
        *error = g_strdup(_("You must be an administrator to send a global broadcast."));
        return PURPLE_CMD_STATUS_FAILED;
    }

    message = args[0];

    json = json_object_new();
    json_object_set_string_member(json, "message", message);
    flist_request(pc, FLIST_BROADCAST, json);
    json_object_unref(json);

    return PURPLE_CMD_STATUS_OK;
}
/**
 * couchdb_document_contact_phone_new:
 * @uuid: A unique ID
 * @number: A phone number
 * @description: Description for this phone number
 * @priority: Priority of this phone number
 *
 * Returns a #CouchdbStructField representing the given phone number.
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing
 * the given phone number information.
 */
CouchdbStructField *
couchdb_document_contact_phone_new (const char *uuid, const char *number, const char *description, gint priority)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (number)
		couchdb_document_contact_phone_set_number (sf, number);
	if (description)
		couchdb_document_contact_phone_set_description (sf, description);
	couchdb_document_contact_phone_set_priority (sf, priority);

	return sf;
}
示例#15
0
gchar *
error_to_json (int code, const char *msg, gsize *len)
{
    JsonObject *object = json_object_new ();
    JsonNode *root = json_node_new (JSON_NODE_OBJECT);
    JsonGenerator *generator = json_generator_new ();
    gchar *data;

    json_object_set_int_member (object, "err_code", code);
    json_object_set_string_or_null_member (object, "err_msg", msg);
    
    json_node_take_object (root, object);
    json_generator_set_root (generator, root);

    g_object_set (generator, "pretty", FALSE, NULL);
    data = json_generator_to_data (generator, len);

    json_node_free (root);
    g_object_unref (generator);

    return data;
}
示例#16
0
static void
postal_http_reply_error (PostalHttp   *http,
                         SoupMessage  *message,
                         const GError *error)
{
   JsonGenerator *g;
   JsonObject *obj;
   JsonNode *node;
   gchar *json_buf;
   gsize length;

   g_assert(SOUP_IS_MESSAGE(message));
   g_assert(error);

   obj = json_object_new();
   json_object_set_string_member(obj, "message", error->message);
   json_object_set_string_member(obj, "domain", g_quark_to_string(error->domain));
   json_object_set_int_member(obj, "code", error->code);

   node = json_node_new(JSON_NODE_OBJECT);
   json_node_set_object(node, obj);
   json_object_unref(obj);

   g = json_generator_new();
   json_generator_set_indent(g, 2);
   json_generator_set_pretty(g, TRUE);
   json_generator_set_root(g, node);
   json_node_free(node);
   json_buf = json_generator_to_data(g, &length);
   g_object_unref(g);

   soup_message_set_response(message,
                             "application/json",
                             SOUP_MEMORY_TAKE,
                             json_buf,
                             length);
   soup_message_set_status(message, get_status_code(error));
   soup_server_unpause_message(http->priv->server, message);
}
示例#17
0
static void
cockpit_channel_real_close (CockpitChannel *self,
                            const gchar *problem)
{
  const gchar *reason = problem;
  JsonObject *object;
  GBytes *message;

  if (self->priv->closed)
    return;

  self->priv->closed = TRUE;

  if (reason == NULL)
    reason = "";

  if (self->priv->close_options)
    {
      object = self->priv->close_options;
      self->priv->close_options = NULL;
    }
  else
    {
      object = json_object_new ();
    }

  json_object_set_string_member (object, "command", "close");
  json_object_set_string_member (object, "channel", self->priv->id);
  json_object_set_string_member (object, "reason", reason);

  message = cockpit_json_write_bytes (object);
  json_object_unref (object);

  cockpit_transport_send (self->priv->transport, 0, message);
  g_bytes_unref (message);

  g_signal_emit (self, cockpit_channel_sig_closed, 0, problem);
}
示例#18
0
/**
 * cockpit_text_stream_open:
 * @transport: the transport to send/receive messages on
 * @channel_id: the channel id
 * @unix_path: the UNIX socket path to communicate with
 *
 * This function is mainly used by tests. The usual way
 * to get a #CockpitTextStream is via cockpit_channel_open()
 *
 * Returns: (transfer full): the new channel
 */
CockpitChannel *
cockpit_text_stream_open (CockpitTransport *transport,
                          const gchar *channel_id,
                          const gchar *unix_path)
{
  CockpitChannel *channel;
  JsonObject *options;

  g_return_val_if_fail (channel_id != NULL, NULL);

  options = json_object_new ();
  json_object_set_string_member (options, "unix", unix_path);
  json_object_set_string_member (options, "payload", "text-stream");

  channel = g_object_new (COCKPIT_TYPE_TEXT_STREAM,
                          "transport", transport,
                          "id", channel_id,
                          "options", options,
                          NULL);

  json_object_unref (options);
  return channel;
}
示例#19
0
/**
 * cockpit_fswatch_open:
 * @transport: the transport to send/receive messages on
 * @channel_id: the channel id
 * @path: the path name of the file to read
 *
 * This function is mainly used by tests. The usual way
 * to get a #CockpitFswatch is via cockpit_channel_open()
 *
 * Returns: (transfer full): the new channel
 */
CockpitChannel *
cockpit_fswatch_open (CockpitTransport *transport,
                      const gchar *channel_id,
                      const gchar *path)
{
  CockpitChannel *channel;
  JsonObject *options;

  g_return_val_if_fail (channel_id != NULL, NULL);

  options = json_object_new ();
  json_object_set_string_member (options, "path", path);
  json_object_set_string_member (options, "payload", "fswatch1");

  channel = g_object_new (COCKPIT_TYPE_FSWATCH,
                          "transport", transport,
                          "id", channel_id,
                          "options", options,
                          NULL);

  json_object_unref (options);
  return channel;
}
示例#20
0
static void
add_page_to_environment (JsonObject *object)
{
  static gint page_login_to = -1;
  JsonObject *page;
  const gchar *value;

  page = json_object_new ();

  value = cockpit_conf_string ("WebService", "LoginTitle");
  if (value)
    json_object_set_string_member (page, "title", value);

  if (page_login_to < 0)
    {
      page_login_to = cockpit_conf_bool ("WebService", "LoginTo",
                                         g_file_test (cockpit_ws_ssh_program,
                                                      G_FILE_TEST_IS_EXECUTABLE));
    }

  json_object_set_boolean_member (page, "connect", page_login_to);
  json_object_set_object_member (object, "page", page);
}
示例#21
0
文件: json.c 项目: yairgd/nodes
/**
 * Created  07/25/2015
 * @brief   main json parser function
 * @param   text: string contains json text
 * @return  0 - succes, pointer to json object - succes
 */
json_object_t * json_parser(const char *text)
{
	struct yy_buffer_state * my_string_buffer;
	/* 
	 * initiate stacks and json object 
	 * TODO: add no memory exception
	 */
	stack_new(&stack_array,1024*100);
	stack_new(&stack_object,1024*100);
	json_object = json_object_new();
	json_array = json_array_new();

	/* 
	 * set the pointer for the folloinwg variables in the file yjson.y since, in both files
	 * the current one and yjson.y the following valiables to set are declared as static
	 */
	set_stack_array(stack_array);
	set_stack_object(stack_object);
	set_json_object(json_object);
	set_json_array(json_array);


	// run flex code from file
	my_string_buffer  = yy_scan_string(text);

	yy_switch_to_buffer( my_string_buffer ); // switch flex to the buffer we just created
	yyparse(); 
//	yy_delete_buffer(my_string_buffer );

	

	// pop top module from stack andfree it
	stack_free(stack_array);
	stack_free(stack_object);
	return json_object;
}
示例#22
0
static void
send_login_response (CockpitWebResponse *response,
                     CockpitCreds *creds,
                     GHashTable *headers)
{
  JsonObject *object;
  JsonObject *login_data;
  GBytes *content;

  object = json_object_new ();
  json_object_set_string_member (object, "user", cockpit_creds_get_user (creds));
  json_object_set_string_member (object, "csrf-token", cockpit_creds_get_csrf_token (creds));

  login_data = cockpit_creds_get_login_data (creds);
  if (login_data)
      json_object_set_object_member (object, "login-data", json_object_ref (login_data));

  content = cockpit_json_write_bytes (object);
  json_object_unref (object);

  g_hash_table_replace (headers, g_strdup ("Content-Type"), g_strdup ("application/json"));
  cockpit_web_response_content (response, headers, content, NULL);
  g_bytes_unref (content);
}
示例#23
0
文件: stub.c 项目: dperpeet/cockpit
static void
send_init_command (CockpitTransport *transport,
                   gboolean interactive)
{
  const gchar *checksum;
  JsonObject *object;
  GBytes *bytes;

  object = json_object_new ();
  json_object_set_string_member (object, "command", "init");
  json_object_set_int_member (object, "version", 1);

  /*
   * When in interactive mode pretend we received an init
   * message, and don't print one out.
   */
  if (interactive)
    {
      json_object_set_string_member (object, "host", "localhost");
    }
  else
    {
      checksum = cockpit_packages_get_checksum (packages);
      if (checksum)
        json_object_set_string_member (object, "checksum", checksum);
    }

  bytes = cockpit_json_write_bytes (object);
  json_object_unref (object);

  if (interactive)
    cockpit_transport_emit_recv (transport, NULL, bytes);
  else
    cockpit_transport_send (transport, NULL, bytes);
  g_bytes_unref (bytes);
}
示例#24
0
json_value *caryll_gpos_mark_to_ligature_to_json(otl_subtable *st) {
	subtable_gpos_mark_to_ligature *subtable = &(st->gpos_mark_to_ligature);
	json_value *_subtable = json_object_new(3);
	json_value *_marks = json_object_new(subtable->marks->numGlyphs);
	json_value *_bases = json_object_new(subtable->bases->numGlyphs);
	for (uint16_t j = 0; j < subtable->marks->numGlyphs; j++) {
		json_value *_mark = json_object_new(3);
		sds markClassName =
		    sdscatfmt(sdsempty(), "ac_%i", subtable->markArray->records[j].markClass);
		json_object_push(_mark, "class",
		                 json_string_new_length((uint32_t)sdslen(markClassName), markClassName));
		sdsfree(markClassName);
		json_object_push(_mark, "x", json_integer_new(subtable->markArray->records[j].anchor.x));
		json_object_push(_mark, "y", json_integer_new(subtable->markArray->records[j].anchor.y));
		json_object_push(_marks, subtable->marks->glyphs[j].name, preserialize(_mark));
	}
	for (uint16_t j = 0; j < subtable->bases->numGlyphs; j++) {
		mark_to_ligature_base *base = subtable->ligArray[j];
		json_value *_base = json_array_new(base->componentCount);
		for (uint16_t k = 0; k < base->componentCount; k++) {
			json_value *_bk = json_object_new(subtable->classCount);
			for (uint16_t m = 0; m < subtable->classCount; m++) {
				if (base->anchors[k][m].present) {
					json_value *_anchor = json_object_new(2);
					json_object_push(_anchor, "x", json_integer_new(base->anchors[k][m].x));
					json_object_push(_anchor, "y", json_integer_new(base->anchors[k][m].y));
					sds markClassName = sdscatfmt(sdsempty(), "ac_%i", m);
					json_object_push_length(_bk, (uint32_t)sdslen(markClassName), markClassName,
					                        _anchor);
					sdsfree(markClassName);
				}
			}
			json_array_push(_base, _bk);
		}
		json_object_push(_bases, subtable->bases->glyphs[j].name, preserialize(_base));
	}
	json_object_push(_subtable, "classCount", json_integer_new(subtable->classCount));
	json_object_push(_subtable, "marks", _marks);
	json_object_push(_subtable, "bases", _bases);
	return _subtable;
}
示例#25
0
/**
 * push_gcm_client_deliver_async:
 * @client: (in): A #PushGcmClient.
 * @identities: (element-type PushGcmIdentity*): A #GList of #PushGcmIdentity.
 * @message: A #PushGcmMessage.
 * @cancellable: (allow-none): A #GCancellable or %NULL.
 * @callback: A #GAsyncReadyCallback.
 * @user_data: User data for @callback.
 *
 * Asynchronously deliver a #PushGcmMessage to one or more GCM enabled
 * devices.
 */
void
push_gcm_client_deliver_async (PushGcmClient       *client,
                               GList               *identities,
                               PushGcmMessage      *message,
                               GCancellable        *cancellable,
                               GAsyncReadyCallback  callback,
                               gpointer             user_data)
{
   PushGcmClientPrivate *priv;
   GSimpleAsyncResult *simple;
   SoupMessage *request;
   const gchar *registration_id;
   const gchar *collapse_key;
   JsonGenerator *g;
   JsonObject *obj;
   JsonObject *data;
   JsonObject *mdata;
   JsonArray *ar;
   JsonNode *node;
   GList *iter;
   GList *list;
   gchar *str;
   gsize length;
   guint time_to_live;

   ENTRY;

   g_return_if_fail(PUSH_IS_GCM_CLIENT(client));
   g_return_if_fail(identities);
   g_return_if_fail(PUSH_IS_GCM_MESSAGE(message));
   g_return_if_fail(!cancellable || G_IS_CANCELLABLE(cancellable));
   g_return_if_fail(callback);

   priv = client->priv;

   request = soup_message_new("POST", PUSH_GCM_CLIENT_URL);
   ar = json_array_new();

   for (iter = identities; iter; iter = iter->next) {
      g_assert(PUSH_IS_GCM_IDENTITY(iter->data));
      registration_id = push_gcm_identity_get_registration_id(iter->data);
      json_array_add_string_element(ar, registration_id);
   }

   str = g_strdup_printf("key=%s", priv->auth_token);
   soup_message_headers_append(request->request_headers, "Authorization", str);
   g_free(str);

   soup_message_headers_append(request->request_headers,
                               "Accept",
                               "application/json");

   data = json_object_new();

   if ((collapse_key = push_gcm_message_get_collapse_key(message))) {
      json_object_set_string_member(data, "collapse_key", collapse_key);
   }

   json_object_set_boolean_member(data,
                                  "delay_while_idle",
                                  push_gcm_message_get_delay_while_idle(message));

   json_object_set_boolean_member(data,
                                  "dry_run",
                                  push_gcm_message_get_dry_run(message));

   if ((time_to_live = push_gcm_message_get_time_to_live(message))) {
      json_object_set_int_member(data, "time_to_live", time_to_live);
   }

   if ((mdata = push_gcm_message_get_data(message))) {
      json_object_set_object_member(data, "data", mdata);
   }

   obj = json_object_new();
   json_object_set_array_member(obj, "registration_ids", ar);
   json_object_set_object_member(obj, "data", data);

   node = json_node_new(JSON_NODE_OBJECT);
   json_node_set_object(node, obj);
   json_object_unref(obj);

   g = json_generator_new();
   json_generator_set_pretty(g, TRUE);
   json_generator_set_indent(g, 2);
   json_generator_set_root(g, node);
   str = json_generator_to_data(g, &length);
   json_node_free(node);
   g_object_unref(g);

   g_print("REQUEST: \"%s\"\n", str);

   soup_message_set_request(request,
                            "application/json",
                            SOUP_MEMORY_TAKE,
                            str,
                            length);

   simple = g_simple_async_result_new(G_OBJECT(client), callback, user_data,
                                      push_gcm_client_deliver_async);

   /*
    * Keep the list of identities around until we receive our result.
    * We need them to key with the resulting array.
    */
   list = g_list_copy(identities);
   g_list_foreach(list, (GFunc)g_object_ref, NULL);
   g_object_set_data_full(G_OBJECT(simple),
                          "identities",
                          list,
                          _push_gcm_identities_free);

   soup_session_queue_message(SOUP_SESSION(client),
                              request,
                              push_gcm_client_deliver_cb,
                              simple);

   EXIT;
}
示例#26
0
static JsonNode *
builder_options_serialize_property (JsonSerializable *serializable,
                                    const gchar      *property_name,
                                    const GValue     *value,
                                    GParamSpec       *pspec)
{
  if (strcmp (property_name, "arch") == 0)
    {
      BuilderOptions *self = BUILDER_OPTIONS (serializable);
      JsonNode *retval = NULL;

      if (self->arch && g_hash_table_size (self->arch) > 0)
        {
          JsonObject *object;
          GHashTableIter iter;
          gpointer key, value;

          object = json_object_new ();

          g_hash_table_iter_init (&iter, self->arch);
          while (g_hash_table_iter_next (&iter, &key, &value))
            {
              JsonNode *child = json_gobject_serialize (value);
              json_object_set_member (object, (char *)key, child);
            }

          retval = json_node_init_object (json_node_alloc (), object);
          json_object_unref (object);
        }

      return retval;
    }
  else if (strcmp (property_name, "env") == 0)
    {
      BuilderOptions *self = BUILDER_OPTIONS (serializable);
      JsonNode *retval = NULL;

      if (self->env && g_strv_length (self->env) > 0)
        {
          JsonObject *object;
          int i;

          object = json_object_new ();

          for (i = 0; self->env[i] != NULL; i++)
            {
              JsonNode *str = json_node_new (JSON_NODE_VALUE);
              const char *equal;
              g_autofree char *member = NULL;

              equal = strchr (self->env[i], '=');
              if (equal)
                {
                  json_node_set_string (str, equal + 1);
                  member = g_strndup (self->env[i], equal - self->env[i]);
                }
              else
                {
                  json_node_set_string (str, "");
                  member = g_strdup (self->env[i]);
                }

              json_object_set_member (object, member, str);
            }

          retval = json_node_init_object (json_node_alloc (), object);
          json_object_unref (object);
        }

      return retval;
    }
  else
    return json_serializable_default_serialize_property (serializable,
                                                         property_name,
                                                         value,
                                                         pspec);
}
示例#27
0
void
cockpit_channel_response_serve (CockpitWebService *service,
                                GHashTable *in_headers,
                                CockpitWebResponse *response,
                                const gchar *where,
                                const gchar *path)
{
  CockpitChannelResponse *chesp = NULL;
  CockpitTransport *transport = NULL;
  CockpitCacheType cache_type = COCKPIT_WEB_RESPONSE_CACHE_PRIVATE;
  const gchar *host = NULL;
  const gchar *pragma;
  gchar *quoted_etag = NULL;
  GHashTable *out_headers = NULL;
  gchar *val = NULL;
  gboolean handled = FALSE;
  GHashTableIter iter;
  const gchar *checksum;
  JsonObject *object = NULL;
  JsonObject *heads;
  gchar *channel = NULL;
  gchar *language = NULL;
  gpointer key;
  gpointer value;

  g_return_if_fail (COCKPIT_IS_WEB_SERVICE (service));
  g_return_if_fail (in_headers != NULL);
  g_return_if_fail (COCKPIT_IS_WEB_RESPONSE (response));
  g_return_if_fail (path != NULL);

  if (where == NULL)
    {
      host = "localhost";
    }
  else if (where[0] == '@')
    {
      host = where + 1;
    }
  else if (where[0] == '$')
    {
      quoted_etag = g_strdup_printf ("\"%s\"", where);
      cache_type = COCKPIT_WEB_RESPONSE_CACHE_FOREVER;
      pragma = g_hash_table_lookup (in_headers, "Pragma");

      if ((!pragma || !strstr (pragma, "no-cache")) &&
          (g_strcmp0 (g_hash_table_lookup (in_headers, "If-None-Match"), where) == 0 ||
           g_strcmp0 (g_hash_table_lookup (in_headers, "If-None-Match"), quoted_etag) == 0))
        {
          cockpit_web_response_headers (response, 304, "Not Modified", 0, "ETag", quoted_etag, NULL);
          cockpit_web_response_complete (response);
          handled = TRUE;
          goto out;
        }

      transport = cockpit_web_service_find_transport (service, where + 1);
      if (!transport)
        goto out;

      host = cockpit_web_service_get_host (service, transport);
      if (!host)
        {
          g_warn_if_reached ();
          goto out;
        }
    }
  else
    {
      goto out;
    }

  cockpit_web_response_set_cache_type (response, cache_type);
  object = cockpit_transport_build_json ("command", "open",
                                         "payload", "http-stream1",
                                         "internal", "packages",
                                         "method", "GET",
                                         "host", host,
                                         "path", path,
                                         "binary", "raw",
                                         NULL);

  if (!transport)
    {
      transport = cockpit_web_service_ensure_transport (service, object);
      if (!transport)
        goto out;
    }

  if (where)
    {
      /*
       * Maybe send back a redirect to the checksum url. We only do this if actually
       * accessing a file, and not a some sort of data like '/checksum', or a root path
       * like '/'
       */
      if (where[0] == '@' && strchr (path, '.'))
        {
          checksum = cockpit_web_service_get_checksum (service, transport);
          if (checksum)
            {
              handled = redirect_to_checksum_path (service, response, checksum, path);
              goto out;
            }
        }
    }

  out_headers = cockpit_web_server_new_table ();

  channel = cockpit_web_service_unique_channel (service);
  json_object_set_string_member (object, "channel", channel);

  if (quoted_etag)
    {
      /*
       * If we have a checksum, then use it as an ETag. It is intentional that
       * a cockpit-bridge version could (in the future) override this.
       */
      g_hash_table_insert (out_headers, g_strdup ("ETag"), quoted_etag);
      quoted_etag = NULL;
    }

  heads = json_object_new ();

  g_hash_table_iter_init (&iter, in_headers);
  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      val = NULL;

      if (g_ascii_strcasecmp (key, "Host") == 0 ||
          g_ascii_strcasecmp (key, "Cookie") == 0 ||
          g_ascii_strcasecmp (key, "Referer") == 0 ||
          g_ascii_strcasecmp (key, "Connection") == 0 ||
          g_ascii_strcasecmp (key, "Pragma") == 0 ||
          g_ascii_strcasecmp (key, "Cache-Control") == 0 ||
          g_ascii_strcasecmp (key, "User-Agent") == 0 ||
          g_ascii_strcasecmp (key, "Accept-Charset") == 0 ||
          g_ascii_strcasecmp (key, "Accept-Ranges") == 0 ||
          g_ascii_strcasecmp (key, "Content-Length") == 0 ||
          g_ascii_strcasecmp (key, "Content-MD5") == 0 ||
          g_ascii_strcasecmp (key, "Content-Range") == 0 ||
          g_ascii_strcasecmp (key, "Range") == 0 ||
          g_ascii_strcasecmp (key, "TE") == 0 ||
          g_ascii_strcasecmp (key, "Trailer") == 0 ||
          g_ascii_strcasecmp (key, "Upgrade") == 0 ||
          g_ascii_strcasecmp (key, "Transfer-Encoding") == 0)
        continue;

      json_object_set_string_member (heads, key, value);
      g_free (val);
    }

  /* Parse the language out of the CockpitLang cookie */
  language = cockpit_web_server_parse_cookie (in_headers, "CockpitLang");
  if (language)
    json_object_set_string_member (heads, "Accept-Language", language);

  json_object_set_string_member (heads, "Host", host);
  json_object_set_object_member (object, "headers", heads);

  chesp = cockpit_channel_response_create (service, response, transport,
                                           cockpit_web_response_get_path (response),
                                           out_headers, object);

  if (!where)
    chesp->inject = cockpit_channel_inject_new (service, path);

  handled = TRUE;

out:
  g_free (language);
  if (object)
    json_object_unref (object);
  g_free (quoted_etag);
  if (out_headers)
    g_hash_table_unref (out_headers);
  g_free (channel);

  if (!handled)
    cockpit_web_response_error (response, 404, NULL, NULL);
}
示例#28
0
static GBytes *
build_environment (CockpitWebService *service,
                   JsonObject *modules)
{
  const gchar *user;
  CockpitCreds *creds;
  JsonObject *env;
  JsonObject *localhost;
  JsonObject *languages;
  JsonObject *language;
  struct passwd *pwd;
  gchar *hostname;
  GBytes *bytes;
  guint n;

  const struct {
    const gchar *name;
    const gchar *code;
  } supported_languages[] = {
    { NC_("display-language", "English"), "" },
    { NC_("display-language", "Danish"),  "da" },
    { NC_("display-language", "German"),  "de" },
  };

  env = json_object_new ();
  if (service)
    {
      creds = cockpit_web_service_get_creds (service);
      user = cockpit_creds_get_user (creds);
      json_object_set_string_member (env, "user", user);
      pwd = cockpit_getpwnam_a (user, NULL);
      if (pwd)
        {
          json_object_set_string_member (env, "name", pwd->pw_gecos);
          free (pwd);
        }
    }

  localhost = json_object_new ();

  /* This awkwardly takes the localhost reference */
  json_object_set_object_member (env, "localhost", localhost);

  hostname = g_malloc0 (HOST_NAME_MAX + 1);
  gethostname (hostname, HOST_NAME_MAX);
  hostname[HOST_NAME_MAX] = '\0';

  json_object_set_string_member (env, "hostname", hostname);

  /* Only include version info if logged in */
  if (service)
    {
      json_object_set_string_member (localhost, "version", PACKAGE_VERSION);
      json_object_set_string_member (localhost, "build_info", COCKPIT_BUILD_INFO);
    }

  languages = json_object_new ();

  /* This awkwardly takes the languages reference */
  json_object_set_object_member (localhost, "languages", languages);

  for (n = 0; n < G_N_ELEMENTS (supported_languages); n++)
    {
      language = json_object_new ();
      json_object_set_object_member (languages, supported_languages[n].code, language);
      json_object_set_string_member (language, "name", supported_languages[n].name);
    }

  if (modules)
    json_object_set_object_member (localhost, "modules", json_object_ref (modules));

  bytes = cockpit_json_write_bytes (env);
  json_object_unref (env);

  return bytes;
}
示例#29
0
static JsonObject *
json_gobject_dump (GObject *gobject)
{
  JsonSerializableIface *iface = NULL;
  JsonSerializable *serializable = NULL;
  gboolean list_properties = FALSE;
  gboolean serialize_property = FALSE;
  gboolean get_property = FALSE;
  JsonObject *object;
  GParamSpec **pspecs;
  guint n_pspecs, i;

  if (JSON_IS_SERIALIZABLE (gobject))
    {
      serializable = JSON_SERIALIZABLE (gobject);
      iface = JSON_SERIALIZABLE_GET_IFACE (gobject);
      list_properties = (iface->list_properties != NULL);
      serialize_property = (iface->serialize_property != NULL);
      get_property = (iface->get_property != NULL);
    }

  object = json_object_new ();

  if (list_properties)
    pspecs = json_serializable_list_properties (serializable, &n_pspecs);
  else
    pspecs = g_object_class_list_properties (G_OBJECT_GET_CLASS (gobject), &n_pspecs);

  for (i = 0; i < n_pspecs; i++)
    {
      GParamSpec *pspec = pspecs[i];
      GValue value = { 0, };
      JsonNode *node = NULL;

      /* read only what we can */
      if (!(pspec->flags & G_PARAM_READABLE))
        continue;

      g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (pspec));

      if (get_property)
        json_serializable_get_property (serializable, pspec, &value);
      else
        g_object_get_property (gobject, pspec->name, &value);

      /* if there is a serialization vfunc, then it is completely responsible
       * for serializing the property, possibly by calling the implementation
       * of the default JsonSerializable interface through chaining up
       */
      if (serialize_property)
        {
          node = json_serializable_serialize_property (serializable,
                                                       pspec->name,
                                                       &value,
                                                       pspec);
        }
      /* skip if the value is the default for the property */
      else if (!g_param_value_defaults (pspec, &value))
        node = json_serialize_pspec (&value, pspec);

      if (node)
        json_object_set_member (object, pspec->name, node);

      g_value_unset (&value);
    }

  g_free (pspecs);

  return object;
}
示例#30
0
static void
on_files_listed (GObject *source_object,
                 GAsyncResult *res,
                 gpointer user_data)
{
  GError *error = NULL;
  JsonObject *options;
  GList *files;

  files = g_file_enumerator_next_files_finish (G_FILE_ENUMERATOR (source_object), res, &error);
  if (error)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        {
          CockpitFslist *self = COCKPIT_FSLIST (user_data);
          g_message ("%s: couldn't process files %s", COCKPIT_FSLIST(user_data)->path, error->message);
          options = cockpit_channel_close_options (COCKPIT_CHANNEL (self));
          json_object_set_string_member (options, "message", error->message);
          cockpit_channel_close (COCKPIT_CHANNEL (self), "internal-error");
        }
      g_clear_error (&error);
      return;
    }

  CockpitFslist *self = COCKPIT_FSLIST (user_data);

  if (files == NULL)
    {
      JsonObject *msg;
      GBytes *msg_bytes;

      msg = json_object_new ();
      json_object_set_string_member (msg, "event", "present-done");
      msg_bytes = cockpit_json_write_bytes (msg);
      json_object_unref (msg);
      cockpit_channel_send (COCKPIT_CHANNEL(self), msg_bytes, FALSE);
      g_bytes_unref (msg_bytes);

      g_clear_object (&self->cancellable);
      g_object_unref (source_object);

      if (self->monitor == NULL)
        {
          cockpit_channel_done (COCKPIT_CHANNEL (self));
          cockpit_channel_close (COCKPIT_CHANNEL (self), NULL);
        }
      return;
    }

  for (GList *l = files; l; l = l->next)
    {
      GFileInfo *info = G_FILE_INFO (l->data);
      JsonObject *msg;
      GBytes *msg_bytes;

      msg = json_object_new ();
      json_object_set_string_member (msg, "event", "present");
      json_object_set_string_member
        (msg, "path", g_file_info_get_attribute_byte_string (info, G_FILE_ATTRIBUTE_STANDARD_NAME));
      json_object_set_string_member
        (msg, "type", cockpit_file_type_to_string (g_file_info_get_file_type (info)));
      msg_bytes = cockpit_json_write_bytes (msg);
      json_object_unref (msg);
      cockpit_channel_send (COCKPIT_CHANNEL(self), msg_bytes, FALSE);
      g_bytes_unref (msg_bytes);
    }

  g_list_free_full (files, g_object_unref);

  g_file_enumerator_next_files_async (G_FILE_ENUMERATOR (source_object),
                                      10,
                                      G_PRIORITY_DEFAULT,
                                      self->cancellable,
                                      on_files_listed,
                                      self);
}