예제 #1
0
파일: plist.c 프로젝트: RobertAudi/mpfc
/* 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;
}
예제 #2
0
static gboolean
on_rejected_certificate (GTlsConnection *conn,
                         GTlsCertificate *peer_cert,
                         GTlsCertificateFlags errors,
                         gpointer user_data)
{
  CockpitChannel *channel = user_data;
  JsonObject *close_options = NULL; // owned by channel
  gchar *pem_data = NULL;

  g_return_val_if_fail (peer_cert != NULL, FALSE);
  g_object_get (peer_cert, "certificate-pem", &pem_data, NULL);
  close_options = cockpit_channel_close_options (channel);
  json_object_set_string_member (close_options, "rejected-certificate", pem_data);

  g_free (pem_data);
  return FALSE;
}
예제 #3
0
static void
send_login_response (CockpitWebResponse *response,
                     CockpitCreds *creds,
                     GHashTable *headers)
{
  JsonObject *object;
  GBytes *content;

  object = json_object_new ();
  json_object_set_string_member (object, "user", cockpit_creds_get_user (creds));

  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);
}
예제 #4
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);
    }
}
예제 #5
0
JsonObject* ease_background_to_json (EaseBackground* self) {
#line 350 "ease-background.c"
	JsonObject* result = NULL;
	JsonObject* obj;
	char* _tmp3_;
#line 115 "ease-background.vala"
	g_return_val_if_fail (self != NULL, NULL);
#line 117 "ease-background.vala"
	obj = json_object_new ();
#line 119 "ease-background.vala"
	if (self->priv->_image != NULL) {
#line 360 "ease-background.c"
		char* _tmp0_;
#line 121 "ease-background.vala"
		json_object_set_string_member (obj, EASE_THEME_BACKGROUND_IMAGE, ease_image_get_filename (self->priv->_image));
#line 122 "ease-background.vala"
		json_object_set_string_member (obj, EASE_THEME_BACKGROUND_IMAGE_FILL, _tmp0_ = ease_image_fill_type_to_string (ease_image_get_fill (self->priv->_image)));
#line 366 "ease-background.c"
		_g_free0 (_tmp0_);
#line 124 "ease-background.vala"
		json_object_set_string_member (obj, EASE_THEME_BACKGROUND_IMAGE_SOURCE, ease_image_get_source (self->priv->_image));
#line 370 "ease-background.c"
	}
#line 127 "ease-background.vala"
	if (self->priv->_color != NULL) {
#line 374 "ease-background.c"
		char* _tmp1_;
#line 129 "ease-background.vala"
		json_object_set_string_member (obj, EASE_THEME_BACKGROUND_COLOR, _tmp1_ = ease_color_to_string (self->priv->_color));
#line 378 "ease-background.c"
		_g_free0 (_tmp1_);
	}
#line 131 "ease-background.vala"
	if (self->priv->_gradient != NULL) {
#line 383 "ease-background.c"
		char* _tmp2_;
#line 133 "ease-background.vala"
		json_object_set_string_member (obj, EASE_THEME_BACKGROUND_GRADIENT, _tmp2_ = ease_gradient_to_string (self->priv->_gradient));
#line 387 "ease-background.c"
		_g_free0 (_tmp2_);
	}
#line 136 "ease-background.vala"
	json_object_set_string_member (obj, EASE_THEME_BACKGROUND_TYPE, _tmp3_ = ease_background_type_to_string (self->priv->_background_type));
#line 392 "ease-background.c"
	_g_free0 (_tmp3_);
	result = obj;
#line 138 "ease-background.vala"
	return result;
#line 397 "ease-background.c"
}
예제 #6
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);
        }
    }
}
예제 #7
0
static const gchar *
process_transport_init (CockpitWebService *self,
                        CockpitTransport *transport,
                        JsonObject *options)
{
  JsonObject *object;
  GBytes *payload;
  gint64 version;

  if (!cockpit_json_get_int (options, "version", -1, &version))
    {
      g_warning ("invalid version field in init message");
      return "protocol-error";
    }

  if (version == 1)
    {
      g_debug ("received init message");
      self->init_received = TRUE;
      g_object_set_data_full (G_OBJECT (transport), "init",
                              json_object_ref (options),
                              (GDestroyNotify) json_object_unref);

      /* Always send an init message down the new transport */
      object = cockpit_transport_build_json ("command", "init", NULL);
      json_object_set_int_member (object, "version", 1);
      json_object_set_string_member (object, "host", "localhost");
      payload = cockpit_json_write_bytes (object);
      json_object_unref (object);
      cockpit_transport_send (transport, NULL, payload);
      g_bytes_unref (payload);
    }
  else
    {
      g_message ("unsupported version of cockpit protocol: %" G_GINT64_FORMAT, version);
      return "not-supported";
    }

  g_signal_emit (self, sig_transport_init, 0);
  return NULL;
}
예제 #8
0
파일: ui.c 프로젝트: imgflo/imgflo
void
send_ports(Network *network, SoupWebsocketConnection *ws) {
    g_return_if_fail(network);
    g_return_if_fail(network->graph);
    GHashTableIter iter;
    gpointer key = NULL;
    gpointer value = NULL;

    JsonObject *payload = json_object_new();
    json_object_set_string_member(payload, "graph", network->graph->id);

    // Inports
    JsonArray *inports = json_array_new();
    json_object_set_array_member(payload, "inPorts", inports);
    g_hash_table_iter_init(&iter, network->graph->inports);
    while (g_hash_table_iter_next(&iter, &key, &value)) {
        const gchar *exported_port = (const gchar *)(key);
        JsonObject *port = json_object_new();
        json_object_set_string_member(port, "id", exported_port);
        json_object_set_string_member(port, "type", "any"); // TODO: should be that of the target
        json_object_set_string_member(port, "description", "");
        json_object_set_boolean_member(port, "addressable", FALSE);
        json_object_set_boolean_member(port, "required", FALSE);
        json_array_add_object_element(inports, port);
    }

    // Outports
    JsonArray *outports = json_array_new();
    json_object_set_array_member(payload, "outPorts", outports);
    g_hash_table_iter_init(&iter, network->graph->outports);
    while (g_hash_table_iter_next(&iter, &key, &value)) {
        const gchar *exported_port = (const gchar *)(key);
        JsonObject *port = json_object_new();
        json_object_set_string_member(port, "id", exported_port);
        json_object_set_string_member(port, "type", "any"); // TODO: should be that of the target
        json_object_set_string_member(port, "description", "");
        json_object_set_boolean_member(port, "addressable", FALSE);
        json_object_set_boolean_member(port, "required", FALSE);
        json_array_add_object_element(outports, port);
    }

    send_response(ws, "runtime", "ports", payload);
}
예제 #9
0
static const gchar *
prepare_for_close_with_errno (CockpitFswrite *self,
                              const gchar *diagnostic,
                              int err)
{
  JsonObject *options;

  if (err == EPERM || err == EACCES)
    {
      g_debug ("%s: %s: %s", self->path, diagnostic, strerror (err));
      return "not-authorized";
    }
  else
    {
      g_message ("%s: %s: %s", self->path, diagnostic, strerror (err));

      options = cockpit_channel_close_options (COCKPIT_CHANNEL (self));
      json_object_set_string_member (options, "message", strerror (err));
      return "internal-error";
    }
}
예제 #10
0
static gboolean
process_ping (CockpitChannel *self,
              JsonObject *ping)
{
  GBytes *payload;

  if (self->priv->throttled)
    {
      g_debug ("%s: received ping while throttled", self->priv->id);
      g_queue_push_tail (self->priv->throttled, json_object_ref (ping));
      return FALSE;
    }
  else
    {
      g_debug ("%s: replying to ping with pong", self->priv->id);
      json_object_set_string_member (ping, "command", "pong");
      payload = cockpit_json_write_bytes (ping);
      cockpit_transport_send (self->priv->transport, NULL, payload);
      g_bytes_unref (payload);
      return TRUE;
    }
}
예제 #11
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;
}
예제 #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
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);
}
예제 #14
0
static void
on_enumerator_ready (GObject *source_object,
                     GAsyncResult *res,
                     gpointer user_data)
{
  GError *error = NULL;
  GFileEnumerator *enumerator;
  JsonObject *options;
  const gchar *problem;

  enumerator = g_file_enumerate_children_finish (G_FILE (source_object), res, &error);
  if (enumerator == NULL)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        {
          CockpitFslist *self = COCKPIT_FSLIST (user_data);
          problem = error_to_problem (error);
          if (problem)
            g_debug ("%s: couldn't list directory: %s", self->path, error->message);
          else
            g_warning ("%s: couldn't list directory: %s", self->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), problem ? problem : "internal-error");
        }
      g_clear_error (&error);
      return;
    }

  CockpitFslist *self = COCKPIT_FSLIST (user_data);

  g_file_enumerator_next_files_async (enumerator,
                                      10,
                                      G_PRIORITY_DEFAULT,
                                      self->cancellable,
                                      on_files_listed,
                                      self);
}
void
desktopcouch_document_contact_set_addresses (CouchdbDocument *document, GSList *list)
{
	GSList *l;
	JsonObject *addresses;

	g_return_if_fail (COUCHDB_IS_DOCUMENT (document));

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

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

			this_address = json_object_new ();
			json_object_set_string_member (this_address, "street", street_str);
			json_object_set_string_member (this_address, "city",
						       desktopcouch_document_contact_address_get_city (sf));
			json_object_set_string_member (this_address, "state",
						       desktopcouch_document_contact_address_get_state (sf));
			json_object_set_string_member (this_address, "country",
						       desktopcouch_document_contact_address_get_country (sf));
			json_object_set_string_member (this_address, "postalcode",
						       desktopcouch_document_contact_address_get_postalcode (sf));
			json_object_set_string_member (this_address, "pobox",
						       desktopcouch_document_contact_address_get_pobox (sf));
			json_object_set_string_member (this_address, "description",
						       desktopcouch_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 (document), "addresses", addresses);
}
예제 #16
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);
}
예제 #17
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;
}
예제 #18
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);
}
예제 #19
0
static void
cockpit_fslist_prepare (CockpitChannel *channel)
{
  CockpitFslist *self = COCKPIT_FSLIST (channel);
  const gchar *problem = "protocol-error";
  JsonObject *options;
  GError *error = NULL;
  GFile *file = NULL;
  gboolean watch;

  COCKPIT_CHANNEL_CLASS (cockpit_fslist_parent_class)->prepare (channel);

  options = cockpit_channel_get_options (channel);
  if (!cockpit_json_get_string (options, "path", NULL, &self->path))
    {
      g_warning ("invalid \"path\" option for fslist1 channel");
      goto out;
    }
  if (self->path == NULL || *(self->path) == 0)
    {
      g_warning ("missing \"path\" option for fslist1 channel");
      goto out;
    }

  if (!cockpit_json_get_bool (options, "watch", TRUE, &watch))
    {
      g_warning ("invalid \"watch\" option for fslist1 channel");
      goto out;
    }

  self->cancellable = g_cancellable_new ();

  file = g_file_new_for_path (self->path);
  g_file_enumerate_children_async (file,
                                   G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_TYPE,
                                   G_FILE_QUERY_INFO_NONE,
                                   G_PRIORITY_DEFAULT,
                                   self->cancellable,
                                   on_enumerator_ready,
                                   self);

  if (watch)
    {
      self->monitor = g_file_monitor_directory (file, 0, NULL, &error);
      if (self->monitor == NULL)
        {
          g_message ("%s: couldn't monitor directory: %s", self->path, error->message);
          options = cockpit_channel_close_options (channel);
          json_object_set_string_member (options, "message", error->message);
          problem = "internal-error";
          goto out;
        }

      self->sig_changed = g_signal_connect (self->monitor, "changed", G_CALLBACK (on_changed), self);
    }

  cockpit_channel_ready (channel);
  problem = NULL;

out:
  g_clear_error (&error);
  if (file)
    g_object_unref (file);
  if (problem)
    cockpit_channel_close (channel, problem);
}
예제 #20
0
static void
send_meta (CockpitInternalMetrics *self)
{
  JsonArray *metrics;
  JsonObject *metric;
  JsonObject *root;
  struct timeval now_timeval;
  gint64 now;

  gettimeofday (&now_timeval, NULL);
  now = timestamp_from_timeval (&now_timeval);

  root = json_object_new ();
  json_object_set_int_member (root, "timestamp", now);
  json_object_set_int_member (root, "now", now);
  json_object_set_int_member (root, "interval", self->interval);

  metrics = json_array_new ();
  for (int i = 0; i < self->n_metrics; i++)
    {
      MetricInfo *info = &self->metrics[i];
      metric = json_object_new ();

      /* Name and derivation mode
       */
      json_object_set_string_member (metric, "name", info->desc->name);
      if (info->derive)
        json_object_set_string_member (metric, "derive", info->derive);

      /* Instances
       */
      if (info->desc->instanced)
        {
          GHashTableIter iter;
          gpointer key, value;
          int index;
          JsonArray *instances = json_array_new ();

          g_hash_table_iter_init (&iter, info->instances);
          index = 0;
          while (g_hash_table_iter_next (&iter, &key, &value))
            {
              const gchar *name = key;
              InstanceInfo *inst = value;

              /* HACK: We can't use json_builder_add_string_value here since
                 it turns empty strings into 'null' values inside arrays.

                 https://bugzilla.gnome.org/show_bug.cgi?id=730803
              */
              {
                JsonNode *string_element = json_node_alloc ();
                json_node_init_string (string_element, name);
                json_array_add_element (instances, string_element);
              }

              inst->index = index++;
            }
          json_object_set_array_member (metric, "instances", instances);
        }

      /* Units and semantics
       */
      json_object_set_string_member (metric, "units", info->desc->units);
      json_object_set_string_member (metric, "semantics", info->desc->semantics);

      json_array_add_object_element (metrics, metric);
    }

  json_object_set_array_member (root, "metrics", metrics);

  cockpit_metrics_send_meta (COCKPIT_METRICS (self), root, FALSE);

  json_object_unref (root);
}
int
main (int argc, char *argv[])
{
  GError *error = NULL;
  GOptionContext *context;
  JsonGenerator *gen;
  JsonNode *root;
  JsonObject *obj;
  JsonArray *array;
  int i;
  char *data;

  context = g_option_context_new ("- ISOM parsing test");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gst_init_get_option_group ());
  if (!g_option_context_parse (context, &argc, &argv, &error)) {
    g_print ("option parsing failed: %s", error->message);
    exit (1);
  }
  g_option_context_free (context);

  if (argc < 2) {
    g_print ("need filename\n");
    exit (1);
  }

  array = json_array_new ();
  for (i = 1; i < argc; i++) {
    GssIsomParser *file;
    GssIsomTrack *video_track;
    GssIsomTrack *audio_track;
    JsonObject *object;
    JsonObject *o;
    gboolean ret;

    file = gss_isom_parser_new ();

    ret = gss_isom_parser_parse_file (file, argv[i]);
    if (!ret) {
      g_print ("parse failed");
      continue;
    }

    video_track = gss_isom_movie_get_video_track (file->movie);
    audio_track = gss_isom_movie_get_audio_track (file->movie);

    object = json_object_new ();
    json_object_set_string_member (object, "filename", argv[i]);
    if (video_track) {
      char *codec;

      o = json_object_new ();
      json_object_set_int_member (o, "track_id", video_track->tkhd.track_id);
      json_object_set_int_member (o, "bitrate", video_track->esds.avg_bitrate);
      codec = g_strdup_printf ("avc1.%02x%02x%02x",
          video_track->esds.codec_data[1],
          video_track->esds.codec_data[2], video_track->esds.codec_data[3]);
      json_object_set_string_member (o, "codec", codec);
      g_free (codec);
      json_object_set_string_member (o, "iv", random_iv_string ());
      json_object_set_object_member (object, "video", o);
    }
    if (audio_track) {
      o = json_object_new ();
      json_object_set_int_member (o, "track_id", audio_track->tkhd.track_id);
      json_object_set_int_member (o, "bitrate", audio_track->esds.avg_bitrate);
      json_object_set_string_member (o, "codec", "mp4a.40.2");  /* AAC LC */
      json_object_set_string_member (o, "iv", random_iv_string ());
      json_object_set_object_member (object, "audio", o);
    }

    json_array_add_object_element (array, object);

    gss_isom_parser_free (file);
  }

  obj = json_object_new ();
  json_object_set_int_member (obj, "version", 0);
  json_object_set_array_member (obj, "media", array);

  root = json_node_new (JSON_NODE_OBJECT);
  json_node_take_object (root, obj);
  gen = g_object_new (JSON_TYPE_GENERATOR,
      "root", root, "pretty", TRUE, "indent", 2, NULL);
  data = json_generator_to_data (gen, NULL);
  g_object_unref (gen);
  json_node_free (root);

  g_print ("%s\n", data);

  return 0;
}
예제 #22
0
파일: ui.c 프로젝트: imgflo/imgflo
static void
ui_connection_handle_message(UiConnection *self,
                const gchar *protocol, const gchar *command, JsonObject *payload,
                SoupWebsocketConnection *ws)
{
    if (g_strcmp0(protocol, "graph") == 0) {
        handle_graph_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "network") == 0) {
        handle_network_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "list") == 0) {
        gint no_components = 0;
        gchar **operation_names = library_list_components(self->component_lib, &no_components);
        for (int i=0; i<no_components; i++) {
            const gchar *op = operation_names[i];
            if (op) {
                JsonObject *component = library_get_component(self->component_lib, op);
                send_response(ws, "component", "component", component);
            }
        }
        g_strfreev(operation_names);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "source") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");
        gchar *actual_name = library_set_source(self->component_lib,
            name,
            json_object_get_string_member(payload, "code")
        );
        if (actual_name) {
            JsonObject *component = library_get_component(self->component_lib, name);
            send_response(ws, "component", "component", component);
        } else {
            // TODO: error response
        }
        g_free(actual_name);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "getsource") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");


        JsonObject *source_info = json_object_new();
        // TODO: generalize for subgraphs-as-components
        if (g_strcmp0(name, self->main_network) == 0) {

            json_object_set_string_member(source_info, "name", "main"); // FIXME: dont hardcode
            json_object_set_string_member(source_info, "library", "default"); // FIXME: dont hardcode

            Network *n = g_hash_table_lookup(self->network_map, self->main_network);
            g_assert(n);
            JsonObject *g = graph_save_json(n->graph);
            gsize len = 0;
            gchar *code = json_stringify(g, &len);
            g_assert(len);
            json_object_set_string_member(source_info, "language", "json");
            json_object_set_string_member(source_info, "code", code);
        } else {
            json_object_set_string_member(source_info, "name", name);
            gchar *code = library_get_source(self->component_lib, name);
            json_object_set_string_member(source_info, "library", "imgflo");
            json_object_set_string_member(source_info, "language", "c");
            json_object_set_string_member(source_info, "code", code);
        }

        send_response(ws, "component", "source", source_info);

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "getruntime") == 0) {

        JsonObject *runtime = json_object_new();
        json_object_set_string_member(runtime, "version", "0.4"); // protocol version
        json_object_set_string_member(runtime, "type", "imgflo");
        json_object_set_string_member(runtime, "graph", self->main_network);

        JsonArray *capabilities = json_array_new();
        json_array_add_string_element(capabilities, "protocol:component");
        json_array_add_string_element(capabilities, "protocol:graph");
        json_array_add_string_element(capabilities, "protocol:runtime");
        json_array_add_string_element(capabilities, "protocol:network");
        json_array_add_string_element(capabilities, "component:getsource");
        json_array_add_string_element(capabilities, "component:setsource");
        json_object_set_array_member(runtime, "capabilities", capabilities);

        send_response(ws, "runtime", "runtime", runtime);

        if (self->main_network) {
            send_ports(g_hash_table_lookup(self->network_map, self->main_network), ws);
        }

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "packet") == 0) {
        gchar *graph_id = g_strdup(json_object_get_string_member(payload, "graph"));
        const gchar *port = json_object_get_string_member(payload, "port");
        const gchar *event = json_object_get_string_member(payload, "event");
        if (!graph_id) {
            // NoFlo RemoteSubGraph currently does not send graph info
            graph_id = g_strdup(self->main_network);
        }
        Network *network = (graph_id) ? g_hash_table_lookup(self->network_map, graph_id) : NULL;
        g_free(graph_id);
        g_return_if_fail(network);

        if (g_strcmp0(event, "data") == 0) {
            GValue data = G_VALUE_INIT;
            json_node_get_value(json_object_get_member(payload, "payload"), &data);
            network_send_packet(network, port, &data);
        } else {
            // TODO: support connect/disconnect?
            imgflo_warning("Unknown runtime:packet event: %s", event);
        }
    } else {
        imgflo_warning("Unhandled message: protocol='%s', command='%s'", protocol, command);
    }
}
예제 #23
0
파일: melo_jsonrpc.c 프로젝트: dillya/melo
/* Params utils */
static gboolean
melo_jsonrpc_add_node (JsonNode *node, JsonObject *schema,
                       JsonObject *obj, JsonArray *array)
{
  GType vtype = G_TYPE_INVALID;
  const gchar *s_name;
  const gchar *s_type;
  JsonNodeType type;

  /* Get name and type from schema */
  s_name = json_object_get_string_member (schema, "name");
  s_type = json_object_get_string_member (schema, "type");
  if (!s_name || !s_type)
    return FALSE;

  /* Get type */
  type = json_node_get_node_type (node);
  if (type == JSON_NODE_VALUE)
    vtype = json_node_get_value_type (node);

  /* Check type:
   * We check only first letter of the type string.
   */
  switch (s_type[0]) {
    case 'b':
      /* Boolean: check type */
      if (vtype != G_TYPE_BOOLEAN)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gboolean v;
        v = json_node_get_boolean (node);
        if (obj)
          json_object_set_boolean_member (obj, s_name, v);
        else
          json_array_add_boolean_element (array, v);
        break;
      }
      break;
    case 'i':
      /* Integer: check type */
      if (vtype != G_TYPE_INT64)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gint64 v;
        v = json_node_get_int (node);
        if (obj)
          json_object_set_int_member (obj, s_name, v);
        else
          json_array_add_int_element (array, v);
      }
      break;
    case 'd':
      /* Double: check type */
      if (vtype != G_TYPE_DOUBLE)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gdouble v;
        v = json_node_get_double (node);
        if (obj)
          json_object_set_double_member (obj, s_name, v);
        else
          json_array_add_double_element (array, v);
      }
      break;
    case 's':
      /* String: check type */
      if (vtype != G_TYPE_STRING)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        const gchar *v;
        v = json_node_get_string (node);
        if (obj)
          json_object_set_string_member (obj, s_name, v);
        else
          json_array_add_string_element (array, v);
      }
      break;
    case 'o':
      /* Object: check type */
      if (type != JSON_NODE_OBJECT)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        JsonObject *v;
        v = json_node_dup_object (node);
        if (obj)
          json_object_set_object_member (obj, s_name, v);
        else
          json_array_add_object_element (array, v);
      }
      break;
    case 'a':
      /* Array: check type */
      if (type != JSON_NODE_ARRAY)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        JsonArray *v;
        v = json_node_dup_array (node);
        if (obj)
          json_object_set_array_member (obj, s_name, v);
        else
          json_array_add_array_element (array, v);
      }
      break;
    default:
      return FALSE;
  }
  return TRUE;
}
예제 #24
0
JsonNode*
cometd_new_handshake_message(const cometd* h)
{
                                                                                                                                                                                      
  gint64 seed = ++(h->conn->msg_id_seed);
  

  /////////////////Data Concatenation/////////////                                                                                                                                                                                               

  JsonObject* dataObject = json_object_new();
  JsonNode*   dataNode = json_node_new(JSON_NODE_OBJECT);
  JsonNode*   dataRoot = json_node_init_object(dataNode, dataObject);

  dataObject = json_node_get_object(dataRoot);

  json_object_set_string_member(dataObject, "login", "test2");
  json_object_set_string_member(dataObject, "password", "password");

  ////////////////Data Concatenation////////////                                                                                                                                                                                                 

  /////////////////Auth/////////////////                                                                                                                                                                                                         

  // I begin from the most inner JsonObject of my Json File                                                                                                                                                                                      

  //here i initialize my Root JsonNode with an object in it and a JsonObject to be able to get the object from the JsonNode                                                                                                                      

  JsonObject* authObject = json_object_new();
  JsonNode*   authNode = json_node_new(JSON_NODE_OBJECT);
  JsonNode*   authRoot = json_node_init_object(authNode, authObject);

  // Here i retrieve the initialized JsonObject that is inside my JsonNode                                                                                                                                                                       
  authObject = json_node_get_object(authRoot);

  // And here some few insertion of strings in the object                                                                                                                                                                                        
  json_object_set_string_member(authObject, "action", "authenticate");
  json_object_set_string_member(authObject, "type", "GmY-HuzW.KZyH.simple");
  json_object_set_string_member(authObject, "resource", "zetapushTuto");
  json_object_set_member(authObject, "data", dataRoot);

  ///////////////Auth/////////////////                                                                                                                                                                                                           



  //////////////First Concatenation : Authentication///////////////                                                                                                                                                                              
  //Here i make the authentication of my first JsonObject with a upper membrane.                                                                                                                                                                 

  JsonObject *extMembrane = json_object_new();
  JsonNode   *contactMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *secondRootMembrane = json_node_init_object(contactMembrane, extMembrane);

  extMembrane = json_node_get_object(secondRootMembrane);

  json_object_set_member(extMembrane, "authentication", authRoot);
  /////////////First Concatenation////////////////                                                                                                                                                                                               

  ////////////Second Concatenation : Ext///////////////                                                                                                                                                                                          
  // Here i finnaly concatenante my last JsonObject and encapsulate the overall file inside the root JsonNode                                                                                                                                    
  JsonObject *rootObjectMembrane = json_object_new();
  JsonNode   *initRootMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *rootMembrane = json_node_init_object(initRootMembrane, rootObjectMembrane);

   rootObjectMembrane = json_node_get_object(rootMembrane);

   json_object_set_member(rootObjectMembrane, "ext", secondRootMembrane);


  // I still needs to create a object under Ext JsonNode, then an JsonArray to supportedConnectionTypes                                                                                                                                          
  //Then add the advice object with "timeout" and "interval"                                                                                                                                                                                     

  json_object_set_int_member(rootObjectMembrane, "id", seed);
  json_object_set_string_member(rootObjectMembrane, "version", "1.0");
  json_object_set_string_member(rootObjectMembrane, "minimumVersion", "1.0");
  json_object_set_string_member(rootObjectMembrane, "channel", "/meta/handshake");

  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_array_add_string_element(json_transports, "long-polling");
  json_object_set_array_member(rootObjectMembrane, "supportedConnectionTypes", json_transports);

  //////////Advice////////                                                                                                                                                                                                                       
  JsonObject *adviceMembrane = json_object_new();
  JsonNode   *adviceNodeMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *adviceRootMembrane = json_node_init_object(adviceNodeMembrane, adviceMembrane);
  gint64 interval = 0;
  gint64 timeout = 60000;
  adviceMembrane = json_node_get_object(adviceRootMembrane);
  json_object_set_int_member(adviceMembrane, "timeout", timeout);
  json_object_set_int_member(adviceMembrane, "interval", interval);
  json_object_set_member(rootObjectMembrane, "advice", adviceRootMembrane);

  /////////Advice////////                                                                                                                                                                                                                        



   ////////////Second Concatenation//////////////
  
  // call extensions with message - TODO: implement extensions first
  //json_node_take_object(root, obj);
  return rootMembrane;
}
예제 #25
0
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;
}
예제 #26
0
static gboolean
relay_headers (CockpitHttpStream *self,
               CockpitChannel *channel,
               GByteArray *buffer)
{
  GHashTable *headers = NULL;
  gchar *version = NULL;
  gchar *reason = NULL;
  JsonObject *object;
  const gchar *data;
  JsonObject *heads;
  GHashTableIter iter;
  GBytes *message;
  gpointer key;
  gpointer value;
  guint status;
  gsize length;
  gssize offset;
  gssize offset2;

  data = (const gchar *)buffer->data;
  length = buffer->len;

  offset = web_socket_util_parse_status_line (data, length, &version, &status, &reason);
  if (offset == 0)
    return FALSE; /* want more data */

  if (offset < 0)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: received response with bad HTTP status line", self->name);
      goto out;
    }

  offset2 = web_socket_util_parse_headers (data + offset, length - offset, &headers);
  if (offset2 == 0)
    return FALSE; /* want more data */

  if (offset2 < 0)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: received response with bad HTTP headers", self->name);
      goto out;
    }

  g_debug ("%s: response: %u %s", self->name, status, reason);
  g_hash_table_iter_init (&iter, headers);
  while (g_hash_table_iter_next (&iter, &key, &value))
    g_debug ("%s: header: %s %s", self->name, (gchar *)key, (gchar *)value);

  if (!parse_transfer_encoding (self, channel, headers) ||
      !parse_content_length (self, channel, status, headers) ||
      !parse_keep_alive (self, channel, version, headers))
    goto out;

  cockpit_pipe_skip (buffer, offset + offset2);

  if (!self->binary)
    {
      g_hash_table_remove (headers, "Content-Length");
      g_hash_table_remove (headers, "Range");
    }
  g_hash_table_remove (headers, "Connection");
  g_hash_table_remove (headers, "Transfer-Encoding");

  /* Now serialize all the rest of this into JSON */
  object = json_object_new ();
  json_object_set_int_member (object, "status", status);
  json_object_set_string_member (object, "reason", reason);

  heads = json_object_new();
  g_hash_table_iter_init (&iter, headers);
  while (g_hash_table_iter_next (&iter, &key, &value))
    json_object_set_string_member (heads, key, value);

  json_object_set_object_member (object, "headers", heads);

  if (self->headers_inline)
    {
      message = cockpit_json_write_bytes (object);
      cockpit_channel_send (channel, message, TRUE);
      g_bytes_unref (message);
    }
  else
    {
      cockpit_channel_control (channel, "response", object);
    }

  json_object_unref (object);

out:
  if (headers)
    g_hash_table_unref (headers);
  g_free (version);
  g_free (reason);

  return TRUE;
}
예제 #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
JsonNode *torrent_get(gint64 id)
{
    JsonNode *root = base_request(METHOD_TORRENT_GET);
    JsonObject *args = node_get_arguments(root);
    JsonArray *fields = json_array_new();

    if (id == TORRENT_GET_TAG_MODE_UPDATE) {
        json_object_set_string_member(args, PARAM_IDS,
                                      FIELD_RECENTLY_ACTIVE);
    } else if (id >= 0) {
        JsonArray *ids = json_array_new();
        json_array_add_int_element(ids, id);
        json_object_set_array_member(args, PARAM_IDS, ids);
    }

    json_array_add_string_element(fields, FIELD_ETA);
    json_array_add_string_element(fields, FIELD_PEERS);
    json_array_add_string_element(fields, FIELD_PEERSFROM);
    json_array_add_string_element(fields, FIELD_FILES);
    json_array_add_string_element(fields, FIELD_PEERS_SENDING_TO_US);
    json_array_add_string_element(fields, FIELD_PEERS_GETTING_FROM_US);
    json_array_add_string_element(fields, FIELD_PEERS_CONNECTED);
    /*json_array_add_string_element(fields, FIELD_HAVEVALID);
       json_array_add_string_element(fields, FIELD_HAVEUNCHECKED); */
    json_array_add_string_element(fields, FIELD_RATEUPLOAD);
    json_array_add_string_element(fields, FIELD_RATEDOWNLOAD);
    json_array_add_string_element(fields, FIELD_STATUS);
    json_array_add_string_element(fields, FIELD_ISFINISHED);
    json_array_add_string_element(fields, FIELD_ISPRIVATE);
    json_array_add_string_element(fields, FIELD_ADDED_DATE);
    json_array_add_string_element(fields, FIELD_DOWNLOADEDEVER);
    json_array_add_string_element(fields, FIELD_UPLOADEDEVER);
    json_array_add_string_element(fields, FIELD_SIZEWHENDONE);
    json_array_add_string_element(fields, FIELD_QUEUE_POSITION);
    json_array_add_string_element(fields, FIELD_ID);
    json_array_add_string_element(fields, FIELD_NAME);
    json_array_add_string_element(fields, FIELD_PERCENTDONE);
    json_array_add_string_element(fields, FIELD_COMMENT);
    json_array_add_string_element(fields, FIELD_TOTAL_SIZE);
    json_array_add_string_element(fields, FIELD_LEFT_UNTIL_DONE);
    json_array_add_string_element(fields, FIELD_ANNOUNCE_URL);
    json_array_add_string_element(fields, FIELD_ERROR_STRING);
    json_array_add_string_element(fields, FIELD_SWARM_SPEED);
    json_array_add_string_element(fields, FIELD_TRACKER_STATS);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_DIR);
    json_array_add_string_element(fields, FIELD_HASH_STRING);
    json_array_add_string_element(fields, FIELD_DONE_DATE);
    json_array_add_string_element(fields, FIELD_HONORS_SESSION_LIMITS);
    json_array_add_string_element(fields, FIELD_UPLOAD_LIMIT);
    json_array_add_string_element(fields, FIELD_UPLOAD_LIMITED);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_LIMIT);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_LIMITED);
    json_array_add_string_element(fields, FIELD_BANDWIDTH_PRIORITY);
    json_array_add_string_element(fields, FIELD_SEED_RATIO_LIMIT);
    json_array_add_string_element(fields, FIELD_SEED_RATIO_MODE);
    json_array_add_string_element(fields, FIELD_PEER_LIMIT);
    json_array_add_string_element(fields, FIELD_ACTIVITY_DATE);
    json_array_add_string_element(fields, FIELD_ERRORSTR);
    json_array_add_string_element(fields, FIELD_WANTED);
    json_array_add_string_element(fields, FIELD_PRIORITIES);
    json_array_add_string_element(fields, FIELD_RECHECK_PROGRESS);
    json_object_set_array_member(args, PARAM_FIELDS, fields);
    return root;
}
예제 #29
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;
}
예제 #30
0
} END_TEST

/* FIXME: more tests required for:
 *
 * - object containing an array (of various types).
 * - object containing an object (containing various types).
 * - object containing a double.
 */
START_TEST(test_cc_oci_json_obj_to_string) {
	gchar *str;
	JsonObject *obj;
	gboolean ret;
	gchar **fields;
	gchar *value;

	ck_assert (! cc_oci_json_obj_to_string (NULL, false, NULL));
	ck_assert (! cc_oci_json_obj_to_string (NULL, true, NULL));

	obj = json_object_new ();

	/* empty object, non-pretty */
	str = cc_oci_json_obj_to_string (obj, false, NULL);
	ck_assert (str);

	ret = g_regex_match_simple (
			/* pair of braces containing optional
			 * whitespace.
			 */
			"{\\s*}",
			str, 0, 0);
	ck_assert (ret);
	g_free (str);

	/* empty object, pretty */
	str = cc_oci_json_obj_to_string (obj, true, NULL);
	ck_assert (str);

	ret = g_regex_match_simple (
			/* pair of braces containing optional
			 * whitespace.
			 */
			"{\\s*}",
			str, 0, 0);
	ck_assert (ret);
	g_free (str);

	/* non-empty object, non-pretty */
	json_object_set_string_member (obj, "test-string-set", "foo");
	json_object_set_string_member (obj, "test-string-empty", "");

	json_object_set_boolean_member (obj, "test-bool-false", false);
	json_object_set_boolean_member (obj, "test-bool-true", true);

	json_object_set_int_member (obj, "test-int-max", G_MAXINT64);
	json_object_set_int_member (obj, "test-int-min", G_MININT64);


	json_object_set_null_member (obj, "test-null");

	str = cc_oci_json_obj_to_string (obj, false, NULL);
	ck_assert (str);

	fields = g_strsplit (str, ",", -1);
	ck_assert (fields);

	g_free (str);

	ck_assert (strv_contains_regex (fields, "test-string-set\\S*foo"));
	ck_assert (strv_contains_regex (fields, "test-string-empty\\S*\"\""));

	ck_assert (strv_contains_regex (fields, "test-bool-true\\S*true"));
	ck_assert (strv_contains_regex (fields, "test-bool-false\\S*false"));

	value = g_strdup_printf ("test-int-max\\S*"
			"%" G_GINT64_FORMAT,
			G_MAXINT64);
	ck_assert (value);

	ck_assert (strv_contains_regex (fields, value));
	g_free (value);

	value = g_strdup_printf ("test-int-min\\S*"
			"%" G_GINT64_FORMAT,
			G_MININT64);
	ck_assert (value);

	ck_assert (strv_contains_regex (fields, value));
	g_free (value);

	g_strfreev (fields);

	/* clean up */
	json_object_unref (obj);

} END_TEST