void
couchdb_document_contact_set_urls (CouchdbDocumentContact *document, GSList *list)
{
	GSList *l;
	JsonObject *urls_json;

	g_return_if_fail (COUCHDB_IS_DOCUMENT_CONTACT (document));

	urls_json = json_object_new ();
	for (l = list; l != NULL; l = l->next) {
		const gchar *address_str;
		CouchdbStructField *sf = (CouchdbStructField *) l->data;

		address_str = couchdb_document_contact_url_get_address (sf);
		if (address_str) {
			JsonObject *this_url;

			this_url = json_object_new ();
			json_object_set_string_member (this_url, "address", address_str);
			json_object_set_string_member (this_url, "description",
						       couchdb_document_contact_url_get_description (sf));

			json_object_set_object_member (urls_json,
						       couchdb_struct_field_get_uuid (sf),
						       this_url);
		}
	}

	json_object_set_object_member (couchdb_document_get_json_object (COUCHDB_DOCUMENT (document)),
				       "urls", urls_json);
}
static JsonObject *trg_prefs_get_tree_view_props(TrgTreeView * tv)
{
    TrgTreeViewPrivate *priv = TRG_TREE_VIEW_GET_PRIVATE(tv);
    JsonObject *root = trg_prefs_get_root(priv->prefs);
    const gchar *className = priv->configId
        && strlen(priv->configId) >
        0 ? priv->configId : G_OBJECT_TYPE_NAME(tv);
    JsonObject *obj;
    JsonObject *tvProps = NULL;

    if (!json_object_has_member(root, TRG_PREFS_KEY_TREE_VIEWS)) {
        obj = json_object_new();
        json_object_set_object_member(root, TRG_PREFS_KEY_TREE_VIEWS, obj);
    } else {
        obj =
            json_object_get_object_member(root, TRG_PREFS_KEY_TREE_VIEWS);
    }

    if (!json_object_has_member(obj, className)) {
        tvProps = json_object_new();
        json_object_set_object_member(obj, className, tvProps);
    } else {
        tvProps = json_object_get_object_member(obj, className);
    }

    return tvProps;
}
void
couchdb_document_contact_set_phone_numbers (CouchdbDocumentContact *document, GSList *list)
{
	GSList *l;
	JsonObject *phone_numbers;

	g_return_if_fail (COUCHDB_IS_DOCUMENT_CONTACT (document));

	phone_numbers = json_object_new ();
	for (l = list; l != NULL; l = l->next) {
		const gchar *number_str;
		CouchdbStructField *sf = (CouchdbStructField *) l->data;

		number_str = couchdb_document_contact_phone_get_number (sf);
		if (number_str) {
			JsonObject *this_phone;

			this_phone = json_object_new ();
			json_object_set_string_member (this_phone, "number", number_str);
			json_object_set_string_member (this_phone, "description",
						       couchdb_document_contact_phone_get_description (sf));
			json_object_set_int_member (this_phone, "priority",
						    couchdb_document_contact_phone_get_priority (sf));

			json_object_set_object_member (phone_numbers,
						       couchdb_struct_field_get_uuid (sf),
						       this_phone);
		}
	}

	json_object_set_object_member (couchdb_document_get_json_object (COUCHDB_DOCUMENT (document)),
				       "phone_numbers", phone_numbers);
}
void
desktopcouch_document_contact_set_im_addresses (CouchdbDocument *document, GSList *list)
{
	GSList *l;
	JsonObject *im_addresses_json;

	g_return_if_fail (COUCHDB_IS_DOCUMENT (document));

	im_addresses_json = json_object_new ();
	for (l = list; l != NULL; l = l->next) {
		const gchar *address_str;
		CouchdbStructField *sf = (CouchdbStructField *) l->data;

		address_str = desktopcouch_document_contact_im_get_address (sf);
		if (address_str != NULL) {
			JsonObject *this_address;

			this_address = json_object_new ();
			json_object_set_string_member (this_address, "address", address_str);
			json_object_set_string_member (this_address, "description",
						       desktopcouch_document_contact_im_get_description (sf));
			json_object_set_string_member (this_address, "protocol",
						       desktopcouch_document_contact_im_get_protocol (sf));

			json_object_set_object_member (im_addresses_json,
						       couchdb_struct_field_get_uuid (sf),
						       this_address);
		}
	}

	json_object_set_object_member (couchdb_document_get_json_object (document), "im_addresses", im_addresses_json);
}
Exemple #5
0
void
send_edge_data_changed(Network *network, const GraphEdge *edge, gpointer user_data) {
    UiConnection *ui = (UiConnection *)user_data;

     // FIXME: remove once noflo-ui no longer needs it
    gchar *src_port = g_utf8_strup(edge->src_port, -1);
    gchar *tgt_port = g_utf8_strup(edge->tgt_port, -1);
    gchar *edge_id = g_strdup_printf("%s() %s -> %s %s()",
                                     edge->src_name, src_port,
                                     tgt_port, edge->tgt_name);
    g_free(src_port);
    g_free(tgt_port);

    gchar *url = ui_get_process_url(ui, network, edge->src_name);
    JsonObject *payload = graph_edge_to_json(edge);
    json_object_set_string_member(payload, "graph", network->graph->id);
    json_object_set_string_member(payload, "id", edge_id);

    JsonObject *data = json_object_new();
    json_object_set_object_member(payload, "data", data);
    json_object_set_string_member(data, "url", url);
    json_object_set_string_member(data, "type", "previewurl");

    g_free(url);

    if (ui->connection) {
        send_response(ui->connection, "network", "data", payload);
    }
}
Exemple #6
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);
}
Exemple #7
0
void
cometd_msg_set_advice(JsonNode* msg, const cometd_advice* advice)
{
    g_return_if_fail(JSON_NODE_HOLDS_OBJECT (msg));

    if (!advice) return;

    JsonObject* advice_obj = json_object_new();

    char* reconnect = NULL;
    switch (advice->reconnect)
    {
    case COMETD_RECONNECT_NONE:
        reconnect = "none";
        break;
    case COMETD_RECONNECT_RETRY:
        reconnect = "retry";
        break;
    case COMETD_RECONNECT_HANDSHAKE:
        reconnect = "handshake";
        break;
    }

    json_object_set_string_member(advice_obj, "reconnect", reconnect);
    json_object_set_int_member(advice_obj, "interval", advice->interval);

    JsonObject* obj = json_node_get_object(msg);
    json_object_set_object_member(obj, COMETD_MSG_ADVICE_FIELD, advice_obj);
}
Exemple #8
0
JsonNode*
cometd_new_handshake_message(const cometd* h)
{
  gint64 seed = ++(h->conn->msg_id_seed);

  JsonNode*   root = json_node_new(JSON_NODE_OBJECT);
  JsonObject* obj  = json_object_new();

  json_object_set_int_member   (obj, COMETD_MSG_ID_FIELD,          seed);
  json_object_set_string_member(obj, COMETD_MSG_CHANNEL_FIELD,     COMETD_CHANNEL_META_HANDSHAKE);
  json_object_set_string_member(obj, COMETD_MSG_VERSION_FIELD,     COMETD_VERSION);
  json_object_set_string_member(obj, COMETD_MSG_MIN_VERSION_FIELD, COMETD_MIN_VERSION);

  // construct advice - TODO: these values should not be hardcoded
  JsonObject* advice = json_object_new();
  json_object_set_int_member(advice, "timeout",  60000);
  json_object_set_int_member(advice, "interval", 0);
  json_object_set_object_member(obj, COMETD_MSG_ADVICE_FIELD, advice);

  // construct supported transports
  JsonArray* json_transports = json_array_new();

  GList* entry = h->config->transports;
  while (entry){
    cometd_transport* t = entry->data;
    json_array_add_string_element(json_transports, t->name);
    entry = g_list_next(entry);
  }
  json_object_set_array_member(obj, "supportedConnectionTypes", json_transports);

  // call extensions with message - TODO: implement extensions first
  json_node_take_object(root, obj);

  return root;
}
static void
on_web_socket_open (WebSocketConnection *connection,
                    gpointer user_data)
{
  CockpitWebSocketStream *self = COCKPIT_WEB_SOCKET_STREAM (user_data);
  CockpitChannel *channel = COCKPIT_CHANNEL (user_data);
  JsonObject *object;
  JsonObject *headers;
  GHashTableIter iter;
  gpointer key, value;

  headers = json_object_new ();

  g_hash_table_iter_init (&iter, web_socket_client_get_headers (WEB_SOCKET_CLIENT (self->client)));
  while (g_hash_table_iter_next (&iter, &key, &value))
    json_object_set_string_member (headers, key, value);

  object = json_object_new ();
  json_object_set_object_member (object, "headers", headers);

  cockpit_channel_control (channel, "response", object);
  json_object_unref (object);

  cockpit_channel_ready (channel, NULL);
}
Exemple #10
0
static GBytes *
build_environment (GHashTable *os_release)
{
  /*
   * We don't include entirety of os-release into the
   * environment for the login.html page. There could
   * be unexpected things in here.
   *
   * However since we are displaying branding based on
   * the OS name variant flavor and version, including
   * the corresponding information is not a leak.
   */
  static const gchar *release_fields[] = {
    "NAME", "ID", "PRETTY_NAME", "VARIANT", "VARIANT_ID", "CPE_NAME",
  };

  static const gchar *prefix = "\n    <script>\nvar environment = ";
  static const gchar *suffix = ";\n    </script>";

  GByteArray *buffer;
  GBytes *bytes;
  JsonObject *object;
  const gchar *value;
  gchar *hostname;
  JsonObject *osr;
  gint i;

  object = json_object_new ();
  add_page_to_environment (object);

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

  if (os_release)
    {
      osr = json_object_new ();
      for (i = 0; i < G_N_ELEMENTS (release_fields); i++)
        {
          value = g_hash_table_lookup (os_release, release_fields[i]);
          if (value)
            json_object_set_string_member (osr, release_fields[i], value);
        }
      json_object_set_object_member (object, "os-release", osr);
    }

  add_oauth_to_environment (object);

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

  buffer = g_bytes_unref_to_array (bytes);
  g_byte_array_prepend (buffer, (const guint8 *)prefix, strlen (prefix));
  g_byte_array_append (buffer, (const guint8 *)suffix, strlen (suffix));
  return g_byte_array_free_to_bytes (buffer);
}
/*!
 * Get container stats (cpu, memory, etc) in json format.
 * \param config \ref clr_oci_config.
 * \param state \ref oci_state.
 *
 * \return json string on success, else NULL
 */
static gchar*
get_container_stats(struct clr_oci_config *config,
	struct oci_state *state)
{
	JsonObject  *root = NULL;
	JsonObject  *data = NULL;
	JsonObject  *resources = NULL;
	gchar       *stats_str = NULL;
	gsize        str_len = 0;


	if(config->state.status != OCI_STATUS_RUNNING){
		goto out;
	}

	root = json_object_new ();
	data = json_object_new ();
	resources = json_object_new ();

	/* Get CPU stats*/
	//FIXME: Implment cpu usage
	json_object_set_object_member (resources, "cpu_stats", json_object_new());

	/* Get Memory stats*/
	//FIXME: Implment memory usage
	json_object_set_object_member (resources, "memory_stats", json_object_new());

	/* Add resoruces node to data node */
	/* 
	   FIXME:
	   We dont use cgroups but, let use  CgroupStats node name
	   to make docker happy
        */
	json_object_set_object_member (data, "CgroupStats", resources);

	/* Add root elements */
	json_object_set_string_member (root, "type", "stats");
	json_object_set_string_member (root, "id", config->optarg_container_id);
	json_object_set_string_member (root, "id", config->optarg_container_id);
	json_object_set_object_member (root, "data", data);
	stats_str = clr_oci_json_obj_to_string (root, false, &str_len);

out:
	return stats_str;
}
/**
 * couchdb_struct_field_set_struct_field:
 * @sf: A #CouchdbStructField object
 * @field: Name of the field
 * @calue: Value to set the field to
 *
 * Set the value of a string field in the given struct field.
 */
void
couchdb_struct_field_set_struct_field (CouchdbStructField *sf, const char *field, CouchdbStructField *value)
{
	g_return_if_fail (sf != NULL);
	g_return_if_fail (field != NULL);
	g_return_if_fail (value != NULL);

	json_object_set_object_member (sf->json_object, field, json_object_ref (value->json_object));
}
void
couchdb_document_contact_set_addresses (CouchdbDocumentContact *document, GSList *list)
{
	GSList *l;
	JsonObject *addresses;

	g_return_if_fail (COUCHDB_IS_DOCUMENT_CONTACT (document));

	addresses = json_object_new ();
	for (l = list; l != NULL; l = l->next) {
		const gchar *street_str;
		CouchdbStructField *sf = (CouchdbStructField *) l->data;

		street_str = couchdb_document_contact_address_get_street (sf);
		if (street_str) {
			JsonObject *this_address;

			this_address = json_object_new ();

			json_object_set_string_member (this_address, "address1", street_str);
			json_object_set_string_member (this_address, "address2",
						       couchdb_document_contact_address_get_ext_street (sf));
			json_object_set_string_member (this_address, "city",
						       couchdb_document_contact_address_get_city (sf));
			json_object_set_string_member (this_address, "state",
						       couchdb_document_contact_address_get_state (sf));
			json_object_set_string_member (this_address, "country",
						       couchdb_document_contact_address_get_country (sf));
			json_object_set_string_member (this_address, "postalcode",
						       couchdb_document_contact_address_get_postalcode (sf));
			json_object_set_string_member (this_address, "pobox",
						       couchdb_document_contact_address_get_pobox (sf));
			json_object_set_string_member (this_address, "description",
						       couchdb_document_contact_address_get_description (sf));

			json_object_set_object_member (addresses,
						       couchdb_struct_field_get_uuid (sf),
						       this_address);
		}
	}

	json_object_set_object_member (couchdb_document_get_json_object (COUCHDB_DOCUMENT (document)),
				       "addresses", addresses);
}
static JsonNode *base_request(gchar * method)
{
    JsonNode *root = json_node_new(JSON_NODE_OBJECT);
    JsonObject *object = json_object_new();
    JsonObject *args = json_object_new();

    json_object_set_string_member(object, PARAM_METHOD, method);
    json_object_set_object_member(object, PARAM_ARGUMENTS, args);
    json_node_take_object(root, object);

    return root;
}
Exemple #15
0
gchar *
form_response(const gchar *protocol, const gchar *command, JsonObject *payload)
{
    JsonObject *response = json_object_new();

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

    gsize len = 0;
    gchar *data = json_stringify(response, &len);
    return data;
}
Exemple #16
0
void
cockpit_channel_close_obj_option (CockpitChannel *self,
                                  const gchar *name,
                                  JsonObject *object)
{
  g_return_if_fail (COCKPIT_IS_CHANNEL (self));
  g_return_if_fail (name != NULL);
  g_return_if_fail (object != NULL);

  if (!self->priv->close_options)
    self->priv->close_options = json_object_new ();
  json_object_set_object_member (self->priv->close_options, name,
                                 json_object_ref (object));
}
Exemple #17
0
static void
skypeweb_xfer_send_init(PurpleXfer *xfer)
{
	PurpleConnection *pc = purple_account_get_connection(purple_xfer_get_account(xfer));
	SkypeWebAccount *sa = purple_connection_get_protocol_data(pc);
	gchar *basename = g_path_get_basename(purple_xfer_get_local_filename(xfer));
	gchar *id, *post, *headers;
	SkypeWebFileTransfer *swft = purple_xfer_get_protocol_data(xfer);
	JsonObject *obj = json_object_new();
	JsonObject *permissions = json_object_new();
	JsonArray *userpermissions = json_array_new();
	
	purple_xfer_set_filename(xfer, basename);
	purple_xfer_ref(xfer);
	
	json_object_set_string_member(obj, "type", "sharing/file");
	json_object_set_string_member(obj, "filename", basename);
	
	if (SKYPEWEB_BUDDY_IS_MSN(swft->from)) {
		id = g_strconcat("1:", swft->from, NULL);
	} else {
		id = g_strconcat("8:", swft->from, NULL);
	}
	json_array_add_string_element(userpermissions, "read");
	json_object_set_array_member(permissions, id, userpermissions);
	json_object_set_object_member(obj, "permissions", permissions);
	
	post = skypeweb_jsonobj_to_string(obj);
	//POST to api.asm.skype.com  /v1/objects
	//{"type":"sharing/file","permissions":{"8:eionrobb":["read"]},"filename":"GiantLobsterMoose.txt"}
	
	headers = g_strdup_printf("POST /v1/objects HTTP/1.0\r\n"
			"Connection: close\r\n"
			"Authorization: skype_token %s\r\n" //slightly different to normal!
			"Host: " SKYPEWEB_XFER_HOST "\r\n"
			"Content-Length: %d\r\n"
			"Content-Type: application/json\r\n"
			"\r\n\r\n%s",
			sa->skype_token, 
			strlen(post), post);
	
	skypeweb_fetch_url_request(sa, "https://" SKYPEWEB_XFER_HOST, TRUE, NULL, FALSE, headers, FALSE, -1, skypeweb_got_object_for_file, swft);
	
	g_free(post);
	json_object_unref(obj);
	g_free(id);
	g_free(basename);
}
static void
on_web_socket_open (WebSocketConnection *connection,
                    CockpitWebService *self)
{
  CockpitSocket *socket;
  JsonArray *capabilities;
  GBytes *command;
  JsonObject *object;
  JsonObject *info;

  g_info ("New connection to session from %s", cockpit_creds_get_rhost (self->creds));

  socket = cockpit_socket_lookup_by_connection (&self->sockets, connection);
  g_return_if_fail (socket != NULL);

  object = json_object_new ();
  json_object_set_string_member (object, "command", "init");
  json_object_set_int_member (object, "version", 1);
  json_object_set_string_member (object, "channel-seed", socket->id);
  json_object_set_string_member (object, "host", "localhost");
  json_object_set_string_member (object, "csrf-token", cockpit_creds_get_csrf_token (self->creds));

  capabilities = json_array_new ();
  json_array_add_string_element (capabilities, "multi");
  json_array_add_string_element (capabilities, "credentials");
  json_array_add_string_element (capabilities, "binary");
  json_object_set_array_member (object, "capabilities", capabilities);

  info = json_object_new ();
  json_object_set_string_member (info, "version", PACKAGE_VERSION);
  json_object_set_string_member (info, "build", COCKPIT_BUILD_INFO);
  json_object_set_object_member (object, "system", info);

  command = cockpit_json_write_bytes (object);
  json_object_unref (object);

  web_socket_connection_send (connection, WEB_SOCKET_DATA_TEXT, self->control_prefix, command);
  g_bytes_unref (command);

  /* Do we have an authorize password? if so tell the frontend */
  if (cockpit_creds_get_password (self->creds))
    send_socket_hints (self, "credential", "password");

  g_signal_connect (connection, "message",
                    G_CALLBACK (on_web_socket_message), self);
}
Exemple #19
0
static GBytes *
build_environment (GHashTable *os_release)
{
  static const gchar *prefix = "\n    <script>\nvar environment = ";
  static const gchar *suffix = ";\n    </script>";
  GByteArray *buffer;
  GHashTableIter iter;
  GBytes *bytes;
  JsonObject *object;
  const gchar *title;
  gchar *hostname;
  gpointer key, value;
  JsonObject *osr;

  object = json_object_new ();

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

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

  if (os_release)
    {
      osr = json_object_new ();
      g_hash_table_iter_init (&iter, os_release);
      while (g_hash_table_iter_next (&iter, &key, &value))
        json_object_set_string_member (osr, key, value);
      json_object_set_object_member (object, "os-release", osr);
    }

  add_oauth_to_environment (object);

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

  buffer = g_bytes_unref_to_array (bytes);
  g_byte_array_prepend (buffer, (const guint8 *)prefix, strlen (prefix));
  g_byte_array_append (buffer, (const guint8 *)suffix, strlen (suffix));
  return g_byte_array_free_to_bytes (buffer);
}
Exemple #20
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);
  }
}
Exemple #21
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;
}
Exemple #22
0
/* Export play list to a json object */
JsonArray *plist_export_to_json( plist_t *pl )
{
	JsonArray *js_plist = json_array_new();
	for ( int i = 0; i < pl->m_len; i ++ )
	{
		song_t *s = pl->m_list[i];
		JsonObject *js_song = json_object_new();

		json_object_set_string_member(js_song, "name", song_get_name(s));
		json_object_set_int_member(js_song, "length", s->m_full_len);
		json_object_set_int_member(js_song, "start_time", s->m_start_time);
		json_object_set_int_member(js_song, "end_time", s->m_end_time);

		if (s->m_default_title)
			json_object_set_string_member(js_song, "title", s->m_default_title);

		if (s->m_info && (s->m_info->m_flags & SI_INITIALIZED))
		{
			song_info_t *si = s->m_info;
			JsonObject *js_si = json_object_new();
			json_object_set_string_member(js_si, "artist",		si->m_artist);
			json_object_set_string_member(js_si, "name",		si->m_name);
			json_object_set_string_member(js_si, "album",		si->m_album);
			json_object_set_string_member(js_si, "year",		si->m_year);
			json_object_set_string_member(js_si, "comments",	si->m_comments);
			json_object_set_string_member(js_si, "track",		si->m_track);
			if (si->m_own_data)
				json_object_set_string_member(js_si, "own_data",	si->m_own_data);
			json_object_set_object_member(js_song, "song_info", js_si);

			if (s->m_flags & SONG_STATIC_INFO)
				json_object_set_int_member(js_song, "static_info", 1);
		}

		json_array_add_object_element(js_plist, js_song);
	}
	return js_plist;
}
Exemple #23
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);
}
static GBytes *
substitute_environment (const gchar *variable,
                        gpointer user_data)
{
  GHashTable *os_release = user_data;
  GHashTableIter iter;
  GBytes *ret = NULL;
  JsonObject *object;
  gchar *hostname;
  gpointer key, value;
  JsonObject *osr;

  if (g_str_equal (variable, "environment"))
    {
      object = json_object_new ();
      hostname = g_malloc0 (HOST_NAME_MAX + 1);
      gethostname (hostname, HOST_NAME_MAX);
      hostname[HOST_NAME_MAX] = '\0';
      json_object_set_string_member (object, "hostname", hostname);
      g_free (hostname);

      if (os_release)
        {
          osr = json_object_new ();
          g_hash_table_iter_init (&iter, os_release);
          while (g_hash_table_iter_next (&iter, &key, &value))
            json_object_set_string_member (osr, key, value);
          json_object_set_object_member (object, "os-release", osr);
        }

      ret = cockpit_json_write_bytes (object);
      json_object_unref (object);
    }

  return ret;
}
Exemple #25
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);
}
/**
 * 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;
}
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);
}
Exemple #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;
}
Exemple #29
0
GHashTable *
cockpit_package_listing (JsonArray **json)
{
  JsonArray *root = NULL;
  GHashTable *listing;
  CockpitPackage *package;
  GHashTable *ids;
  JsonObject *object;
  JsonArray *id;
  GList *names, *l;
  GList *packages;
  const gchar *name;
  JsonNode *node;
  JsonArray *array;
  guint i, length;

  listing = g_hash_table_new_full (g_str_hash, g_str_equal,
                                   NULL, cockpit_package_unref);

  build_package_listing (listing);

  /* Add aliases to the listing */
  packages = g_hash_table_get_values (listing);
  packages = g_list_sort (packages, compar_packages);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;

      node = json_object_get_member (package->manifest, "alias");
      if (node)
        {
          /*
           * Process and remove "alias" from the manifest, as it results in
           * confusing and duplicated information for the front end.
           */
          package->alias = node = json_node_copy (node);
          json_object_remove_member (package->manifest, "alias");

          if (JSON_NODE_HOLDS_ARRAY (node))
            {
              array = json_node_get_array (node);
              length = json_array_get_length (array);
              for (i = 0; i < length; i++)
                add_alias_to_listing (listing, package, json_array_get_element (array, i));
            }
          else
            {
              add_alias_to_listing (listing, package, node);
            }
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Now wrap up the checksums */
  finish_checksums (listing);

  /* Add checksums to the listing */
  packages = g_hash_table_get_values (listing);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;
      if (package->checksum && !g_hash_table_contains (listing, package->checksum))
        {
          g_hash_table_replace (listing, package->checksum, cockpit_package_ref (package));
          g_debug ("%s: package has checksum: %s", package->name, package->checksum);
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Build JSON packages block */
  if (json)
    {
      *json = root = json_array_new ();
      ids = g_hash_table_new (g_direct_hash, g_direct_equal);
      names = g_hash_table_get_keys (listing);
      names = g_list_sort (names, (GCompareFunc)strcmp);

      for (l = names; l != NULL; l = g_list_next (l))
        {
          name = l->data;
          package = g_hash_table_lookup (listing, name);
          id = g_hash_table_lookup (ids, package);
          if (!id)
            {
              object = json_object_new ();
              id = json_array_new();

              /* The actual package name always comes first */
              json_object_set_array_member (object, "id", id);
              json_array_add_string_element (id, package->name);
              g_hash_table_insert (ids, package, id);

              json_object_set_object_member (object, "manifest", json_object_ref (package->manifest));
              json_array_add_object_element (root, object);
            }

          /* Other ways to refer to the package */
          if (!g_str_equal (name, package->name))
              json_array_add_string_element (id, name);
        }

      g_list_free (names);
      g_hash_table_destroy (ids);
    }

  return listing;
}
static int 
pb_send_im(PurpleConnection *pc, const gchar *who, const gchar *message, PurpleMessageFlags flags)
{
	PushBulletAccount *pba = pc->proto_data;
	gchar *stripped, *postdata;
	gchar *guid;
	
	if (g_str_has_prefix(message, "?OTR"))
		return 0;
	
	if (PB_IS_SMS(who))
	{
		JsonObject *root = json_object_new();
		JsonObject *data = json_object_new();
		JsonArray *addresses = json_array_new();
		
		json_array_add_string_element(addresses, who);
		json_object_set_array_member(data, "addresses", addresses);
		
		guid = pb_get_next_id(pba);
		json_object_set_string_member(data, "guid", guid);
		json_object_set_string_member(data, "target_device_iden", pba->main_sms_device);
		json_object_set_boolean_member(data, "encrypted", FALSE);
		
		stripped = g_strstrip(purple_markup_strip_html(message));
		json_object_set_string_member(data, "message", stripped);
		g_free(stripped);
		
		json_object_set_object_member(root, "data", data);
		
		postdata = pb_jsonobj_to_string(root);
		pb_fetch_url(pba, "https://api.pushbullet.com/v3/create-text", postdata, NULL, NULL);
		g_free(postdata);
		
		json_object_unref(root);
		
		g_hash_table_insert(pba->sent_messages_hash, guid, guid);
		return 1;
	}
	
	if (!strchr(who, '@')) {
		return -1;
	}
	
	//<IMG ID="5"> - embedded image i.e. MMS
	
	/* Image flow:
	POST to https://api.pushbullet.com/v3/start-upload {"name":"imagename.jpg","size":12345,"type":"image/jpeg"}
	=> {"id":"abcde","piece_size":5242880,"piece_urls":["https://upload.pushbullet.com/upload-piece/12345/0"]}
	
	POST data in chunks to the pieces_urls
	
	POST to https://api.pushbullet.com/v3/finish-upload {"id":"abcde"} (from earlier)
	=> {"file_name":"imagename.jpg","file_type":"image/jpeg","file_url":"..urltoimage..."}
	
	POST to https://api.pushbullet.com/v2/pushes {"type":"file","file_name":"filename.jpg","file_url":"..urltoimage...","file_type":"image/jpeg","email":"touser"}
	*/
	
	{
		JsonObject *root = json_object_new();
		
		guid = pb_get_next_id(pba);
		json_object_set_string_member(root, "guid", guid);
		json_object_set_string_member(root, "type", "note");
		json_object_set_string_member(root, "title", "");
		json_object_set_string_member(root, "url", "");
		json_object_set_string_member(root, "email", who);
		
		stripped = g_strstrip(purple_markup_strip_html(message));
		json_object_set_string_member(root, "body", stripped);
		g_free(stripped);
		
		postdata = pb_jsonobj_to_string(root);
		pb_fetch_url(pba, "https://api.pushbullet.com/v2/pushes", postdata, NULL, NULL);
		g_free(postdata);
		
		json_object_unref(root);
		
		g_hash_table_insert(pba->sent_messages_hash, guid, guid);
		return 1;
	}
	
	return -1;
}