コード例 #1
0
static gboolean
send_review_request (GsPlugin *plugin,
		     const gchar *method, const gchar *path,
		     JsonBuilder *request,
		     gboolean do_sign,
		     guint *status_code,
		     JsonParser **result,
		     GCancellable *cancellable, GError **error)
{
	g_autofree gchar *uri = NULL;
	g_autoptr(SoupMessage) msg = NULL;

	uri = g_strdup_printf ("%s%s",
			       UBUNTU_REVIEWS_SERVER, path);
	msg = soup_message_new (method, uri);

	if (request != NULL) {
		g_autoptr(JsonGenerator) generator = NULL;
		gchar *data;
		gsize length;

		generator = json_generator_new ();
		json_generator_set_root (generator, json_builder_get_root (request));
		data = json_generator_to_data (generator, &length);
		soup_message_set_request (msg, "application/json", SOUP_MEMORY_TAKE, data, length);
	}

	if (do_sign)
		sign_message (msg,
			      OA_PLAINTEXT,
			      gs_plugin_get_auth_by_id (plugin, "ubuntuone"));

	*status_code = soup_session_send_message (gs_plugin_get_soup_session (plugin), msg);

	if (*status_code == SOUP_STATUS_UNAUTHORIZED) {
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_AUTH_REQUIRED,
				     "Requires authentication with @ubuntuone");
		return FALSE;
	}

	if (result != NULL) {
		g_autoptr(JsonParser) parser = NULL;
		const gchar *content_type;

		content_type = soup_message_headers_get_content_type (msg->response_headers, NULL);
		if (g_strcmp0 (content_type, "application/json") != 0) {
			g_set_error (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     "Got unknown content type %s from reviews.ubuntu.com",
				     content_type);
			return FALSE;
		}

		parser = json_parser_new ();
		if (!json_parser_load_from_data (parser, msg->response_body->data, -1, error)) {
			return FALSE;
		}
		*result = g_steal_pointer (&parser);
	}

	return TRUE;
}
コード例 #2
0
ファイル: cmd_watchdog.c プロジェクト: gsr-shanks/restraint
int main(int argc, char *argv[]) {

    GError *error = NULL;

    gchar *server = NULL;
    gchar *form_data;
    gchar *form_seconds;
    SoupURI *watchdog_uri = NULL;
    guint ret = 0;
    guint64 seconds;

    gchar *prefix = NULL;
    gchar *server_recipe_key = NULL;
    gchar *server_recipe = NULL;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    GOptionEntry entries[] = {
        {"server", 's', 0, G_OPTION_ARG_STRING, &server,
            "Server to connect to", "URL" },
        { NULL }
    };
    GOptionContext *context = g_option_context_new("<time>");
    g_option_context_set_summary(context,
            "Adjust watchdog on lab controller. if you don't specify the\n"
            "the server url you must have RECIPEID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPEID");
    g_option_context_add_main_entries(context, entries, NULL);
    gboolean parse_succeeded = g_option_context_parse(context, &argc, &argv, &error);

    if (argc < 2 || !parse_succeeded) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Wrong arguments");
        cmd_usage(context);
        goto cleanup;
    }

    seconds = parse_time_string (argv[1], &error);
    if (error) {
        cmd_usage(context);
        goto cleanup;
     }

    prefix = getenv("HARNESS_PREFIX") ? getenv("HARNESS_PREFIX") : "";
    server_recipe_key = g_strdup_printf ("%sRECIPE_URL", prefix);
    server_recipe = getenv(server_recipe_key);
    g_free(server_recipe_key);

    if (!server && server_recipe) {
        server = g_strdup_printf ("%s/watchdog", server_recipe);
    }

    if (!server) {
        cmd_usage(context);
        goto cleanup;
    }

    watchdog_uri = soup_uri_new (server);
    if (!watchdog_uri) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Malformed server url: %s", server);
        goto cleanup;
    }
    session = soup_session_new_with_options("timeout", 3600, NULL);
    SoupMessage *server_msg = soup_message_new_from_uri ("POST", watchdog_uri);
    form_seconds = g_strdup_printf ("%" PRIu64, seconds);
    g_hash_table_insert (data_table, "seconds", form_seconds);
    form_data = soup_form_encode_hash (data_table);
    g_free (form_seconds);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));

    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
    } else {
        g_warning ("Failed to adjust watchdog, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }
    g_object_unref(server_msg);

    soup_session_abort(session);
    g_object_unref(session);

cleanup:
    g_hash_table_destroy(data_table);
    g_option_context_free(context);
    if (server != NULL) {
        g_free(server);
    }
    if (watchdog_uri != NULL) {
        soup_uri_free (watchdog_uri);
    }
    if (error) {
        int retcode = error->code;
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        g_clear_error(&error);
        return retcode;
    } else {
        return EXIT_SUCCESS;
    }
}
コード例 #3
0
static GPtrArray *
gs_plugin_odrs_fetch_for_app (GsPlugin *plugin, GsApp *app, GError **error)
{
	GsPluginData *priv = gs_plugin_get_data (plugin);
	const gchar *version;
	guint status_code;
	g_autofree gchar *cachefn_basename = NULL;
	g_autofree gchar *cachefn = NULL;
	g_autofree gchar *data = NULL;
	g_autofree gchar *uri = NULL;
	g_autoptr(GFile) cachefn_file = NULL;
	g_autoptr(GPtrArray) reviews = NULL;
	g_autoptr(JsonBuilder) builder = NULL;
	g_autoptr(JsonGenerator) json_generator = NULL;
	g_autoptr(JsonNode) json_root = NULL;
	g_autoptr(SoupMessage) msg = NULL;

	/* look in the cache */
	cachefn_basename = g_strdup_printf ("%s.json", gs_app_get_id (app));
	cachefn = gs_utils_get_cache_filename ("reviews",
					       cachefn_basename,
					       GS_UTILS_CACHE_FLAG_WRITEABLE,
					       error);
	if (cachefn == NULL)
		return NULL;
	cachefn_file = g_file_new_for_path (cachefn);
	if (gs_utils_get_file_age (cachefn_file) < ODRS_REVIEW_CACHE_AGE_MAX) {
		g_autofree gchar *json_data = NULL;
		if (!g_file_get_contents (cachefn, &json_data, NULL, error))
			return NULL;
		g_debug ("got review data for %s from %s",
			 gs_app_get_id (app), cachefn);
		return gs_plugin_odrs_parse_reviews (plugin,
						     json_data, -1,
						     error);
	}

	/* not always available */
	version = gs_app_get_version (app);
	if (version == NULL)
		version = "unknown";

	/* create object with review data */
	builder = json_builder_new ();
	json_builder_begin_object (builder);
	json_builder_set_member_name (builder, "user_hash");
	json_builder_add_string_value (builder, priv->user_hash);
	json_builder_set_member_name (builder, "app_id");
	json_builder_add_string_value (builder, gs_app_get_id (app));
	json_builder_set_member_name (builder, "locale");
	json_builder_add_string_value (builder, gs_plugin_get_locale (plugin));
	json_builder_set_member_name (builder, "distro");
	json_builder_add_string_value (builder, priv->distro);
	json_builder_set_member_name (builder, "version");
	json_builder_add_string_value (builder, version);
	json_builder_set_member_name (builder, "limit");
	json_builder_add_int_value (builder, ODRS_REVIEW_NUMBER_RESULTS_MAX);
	json_builder_end_object (builder);

	/* export as a string */
	json_root = json_builder_get_root (builder);
	json_generator = json_generator_new ();
	json_generator_set_pretty (json_generator, TRUE);
	json_generator_set_root (json_generator, json_root);
	data = json_generator_to_data (json_generator, NULL);
	if (data == NULL)
		return NULL;
	uri = g_strdup_printf ("%s/fetch", priv->review_server);
	msg = soup_message_new (SOUP_METHOD_POST, uri);
	soup_message_set_request (msg, "application/json; charset=utf-8",
				  SOUP_MEMORY_COPY, data, strlen (data));
	status_code = soup_session_send_message (gs_plugin_get_soup_session (plugin), msg);
	if (status_code != SOUP_STATUS_OK) {
		if (!gs_plugin_odrs_parse_success (msg->response_body->data,
						   msg->response_body->length,
						   error))
			return NULL;
		/* not sure what to do here */
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_DOWNLOAD_FAILED,
				     "status code invalid");
		gs_utils_error_add_unique_id (error, priv->cached_origin);
		return NULL;
	}
	reviews = gs_plugin_odrs_parse_reviews (plugin,
						msg->response_body->data,
						msg->response_body->length,
						error);
	if (reviews == NULL)
		return NULL;
	g_debug ("odrs returned: %s", msg->response_body->data);

	/* save to the cache */
	if (!g_file_set_contents (cachefn,
				  msg->response_body->data,
				  msg->response_body->length,
				  error))
		return NULL;

	/* success */
	return g_steal_pointer (&reviews);
}
コード例 #4
0
ファイル: auth-test.c プロジェクト: Conservatory/quark
static void
do_async_auth_test (const char *base_uri)
{
	SoupSession *session;
	SoupMessage *msg1, *msg2, *msg3, msg2_bak;
	guint auth_id;
	char *uri;
	SoupAuth *auth = NULL;
	int remaining;
	gboolean been_there;

	debug_printf (1, "\nTesting async auth:\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	remaining = 0;

	uri = g_strconcat (base_uri, "Basic/realm1/", NULL);

	msg1 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg1), "id", GINT_TO_POINTER (1));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), &auth);
	g_object_ref (msg1);
	remaining++;
	soup_session_queue_message (session, msg1, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	/* async_authenticate will pause msg1 and quit loop */

	msg2 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg2), "id", GINT_TO_POINTER (2));
	soup_session_send_message (session, msg2);

	if (msg2->status_code == SOUP_STATUS_UNAUTHORIZED)
		debug_printf (1, "  msg2 failed as expected\n");
	else {
		debug_printf (1, "  msg2 got wrong status! (%u)\n",
			      msg2->status_code);
		errors++;
	}

	/* msg2 should be done at this point; assuming everything is
	 * working correctly, the session won't look at it again; we
	 * ensure that if it does, it will crash the test program.
	 */
	memcpy (&msg2_bak, msg2, sizeof (SoupMessage));
	memset (msg2, 0, sizeof (SoupMessage));

	msg3 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg3), "id", GINT_TO_POINTER (3));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), NULL);
	g_object_ref (msg3);
	remaining++;
	soup_session_queue_message (session, msg3, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	/* async_authenticate will pause msg3 and quit loop */

	/* Now do the auth, and restart */
	if (auth) {
		soup_auth_authenticate (auth, "user1", "realm1");
		g_object_unref (auth);
		soup_session_unpause_message (session, msg1);
		soup_session_unpause_message (session, msg3);

		g_main_loop_run (loop);

		/* async_finished will quit the loop */
	} else {
		debug_printf (1, "  msg1 didn't get authenticate signal!\n");
		errors++;
	}

	if (msg1->status_code == SOUP_STATUS_OK)
		debug_printf (1, "  msg1 succeeded\n");
	else {
		debug_printf (1, "  msg1 FAILED! (%u %s)\n",
			      msg1->status_code, msg1->reason_phrase);
		errors++;
	}
	if (msg3->status_code == SOUP_STATUS_OK)
		debug_printf (1, "  msg3 succeeded\n");
	else {
		debug_printf (1, "  msg3 FAILED! (%u %s)\n",
			      msg3->status_code, msg3->reason_phrase);
		errors++;
	}

	soup_test_session_abort_unref (session);

	g_object_unref (msg1);
	g_object_unref (msg3);
	memcpy (msg2, &msg2_bak, sizeof (SoupMessage));
	g_object_unref (msg2);

	/* Test that giving the wrong password doesn't cause multiple
	 * authenticate signals the second time.
	 */
	debug_printf (1, "\nTesting async auth with wrong password (#522601):\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	remaining = 0;
	auth = NULL;

	msg1 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg1), "id", GINT_TO_POINTER (1));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), &auth);
	g_object_ref (msg1);
	remaining++;
	soup_session_queue_message (session, msg1, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);
	soup_auth_authenticate (auth, "user1", "wrong");
	g_object_unref (auth);
	soup_session_unpause_message (session, msg1);

	been_there = FALSE;
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate_assert_once),
				    &been_there);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	if (!been_there) {
		debug_printf (1, "  authenticate not emitted?\n");
		errors++;
	}

	soup_test_session_abort_unref (session);
	g_object_unref (msg1);

	/* Test that giving no password doesn't cause multiple
	 * authenticate signals the second time.
	 */
	debug_printf (1, "\nTesting async auth with no password (#583462):\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	remaining = 0;

	/* Send a message that doesn't actually authenticate
	 */
	msg1 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg1), "id", GINT_TO_POINTER (1));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), NULL);
	g_object_ref (msg1);
	remaining++;
	soup_session_queue_message (session, msg1, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);
	soup_session_unpause_message (session, msg1);
	g_main_loop_run (loop);
	g_object_unref(msg1);

	/* Now send a second message */
	msg1 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg1), "id", GINT_TO_POINTER (2));
	g_object_ref (msg1);
	been_there = FALSE;
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate_assert_once_and_stop),
				    &been_there);
	remaining++;
	soup_session_queue_message (session, msg1, async_finished, &remaining);
	g_main_loop_run (loop);
	soup_session_unpause_message (session, msg1);

	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	soup_test_session_abort_unref (session);
	g_object_unref (msg1);

	g_free (uri);
}
コード例 #5
0
ファイル: auth-test.c プロジェクト: Conservatory/quark
static void
do_batch_tests (const gchar *base_uri_str, gint ntests)
{
	SoupSession *session;
	SoupMessage *msg;
	char *expected;
	SoupURI *base_uri;
	int i;

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	g_signal_connect (session, "authenticate",
			  G_CALLBACK (authenticate), &i);

	base_uri = soup_uri_new (base_uri_str);

	for (i = 0; i < ntests; i++) {
		SoupURI *soup_uri = soup_uri_new_with_base (base_uri, current_tests[i].url);

		debug_printf (1, "Test %d: %s\n", i + 1, current_tests[i].explanation);

		if (current_tests[i].url_auth) {
			gchar *username = g_strdup_printf ("user%c", current_tests[i].provided[0]);
			gchar *password = g_strdup_printf ("realm%c", current_tests[i].provided[0]);
			soup_uri_set_user (soup_uri, username);
			soup_uri_set_password (soup_uri, password);
			g_free (username);
			g_free (password);
		}

		msg = soup_message_new_from_uri (SOUP_METHOD_GET, soup_uri);
		soup_uri_free (soup_uri);
		if (!msg) {
			fprintf (stderr, "auth-test: Could not parse URI\n");
			exit (1);
		}

		debug_printf (1, "  GET %s\n", soup_uri_to_string (soup_message_get_uri (msg), FALSE));

		expected = g_strdup (current_tests[i].expected);
		soup_message_add_status_code_handler (
			msg, "got_headers", SOUP_STATUS_UNAUTHORIZED,
			G_CALLBACK (handler), expected);
		soup_message_add_status_code_handler (
			msg, "got_headers", SOUP_STATUS_OK,
			G_CALLBACK (handler), expected);
		soup_session_send_message (session, msg);
		if (msg->status_code != SOUP_STATUS_UNAUTHORIZED &&
		    msg->status_code != SOUP_STATUS_OK) {
			debug_printf (1, "  %d %s !\n", msg->status_code,
				      msg->reason_phrase);
			errors++;
		}
		if (*expected) {
			debug_printf (1, "  expected %d more round(s)\n",
				      (int)strlen (expected));
			errors++;
		}
		g_free (expected);

		if (msg->status_code != current_tests[i].final_status) {
			debug_printf (1, "  expected %d\n",
				      current_tests[i].final_status);
		}

		debug_printf (1, "\n");

		g_object_unref (msg);
	}
	soup_uri_free (base_uri);

	soup_test_session_abort_unref (session);
}
コード例 #6
0
ファイル: auth-test.c プロジェクト: simonmiddleton/libsoup
static void
do_async_auth_good_password_test (void)
{
	SoupSession *session;
	SoupMessage *msg1, *msg2, *msg3, msg2_bak;
	guint auth_id;
	char *uri;
	SoupAuth *auth = NULL;
	int remaining;

	SOUP_TEST_SKIP_IF_NO_APACHE;

	loop = g_main_loop_new (NULL, TRUE);
	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	uri = g_strconcat (base_uri, "Basic/realm1/", NULL);
	remaining = 0;

	msg1 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg1), "id", GINT_TO_POINTER (1));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), &auth);
	g_object_ref (msg1);
	remaining++;
	soup_session_queue_message (session, msg1, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	/* async_authenticate will pause msg1 and quit loop */

	msg2 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg2), "id", GINT_TO_POINTER (2));
	soup_session_send_message (session, msg2);

	soup_test_assert_message_status (msg2, SOUP_STATUS_UNAUTHORIZED);

	/* msg2 should be done at this point; assuming everything is
	 * working correctly, the session won't look at it again; we
	 * ensure that if it does, it will crash the test program.
	 */
	memcpy (&msg2_bak, msg2, sizeof (SoupMessage));
	memset (msg2, 0, sizeof (SoupMessage));

	msg3 = soup_message_new ("GET", uri);
	g_object_set_data (G_OBJECT (msg3), "id", GINT_TO_POINTER (3));
	auth_id = g_signal_connect (session, "authenticate",
				    G_CALLBACK (async_authenticate), NULL);
	g_object_ref (msg3);
	remaining++;
	soup_session_queue_message (session, msg3, async_finished, &remaining);
	g_main_loop_run (loop);
	g_signal_handler_disconnect (session, auth_id);

	/* async_authenticate will pause msg3 and quit loop */

	/* Now do the auth, and restart */
	if (auth) {
		soup_auth_authenticate (auth, "user1", "realm1");
		g_object_unref (auth);
		soup_session_unpause_message (session, msg1);
		soup_session_unpause_message (session, msg3);

		g_main_loop_run (loop);

		/* async_finished will quit the loop */
	} else
		soup_test_assert (auth, "msg1 didn't get authenticate signal");

	soup_test_assert_message_status (msg1, SOUP_STATUS_OK);
	soup_test_assert_message_status (msg3, SOUP_STATUS_OK);

	soup_test_session_abort_unref (session);

	g_object_unref (msg1);
	g_object_unref (msg3);
	memcpy (msg2, &msg2_bak, sizeof (SoupMessage));
	g_object_unref (msg2);

	g_free (uri);
	g_main_loop_unref (loop);
}
コード例 #7
0
static gboolean
ai_app_validate_image_check (AsImage *im, AsAppValidateHelper *helper)
{
	AsImageAlphaFlags alpha_flags;
	const gchar *url;
	gboolean require_correct_aspect_ratio = FALSE;
	gdouble desired_aspect = 1.777777778;
	gdouble screenshot_aspect;
	guint status_code;
	guint screenshot_height;
	guint screenshot_width;
	guint ss_size_height_max = 900;
	guint ss_size_height_min = 351;
	guint ss_size_width_max = 1600;
	guint ss_size_width_min = 624;
	g_autoptr(GdkPixbuf) pixbuf = NULL;
	g_autoptr(GInputStream) stream = NULL;
	g_autoptr(SoupMessage) msg = NULL;
	g_autoptr(SoupURI) base_uri = NULL;

	/* make the requirements more strict */
	if ((helper->flags & AS_APP_VALIDATE_FLAG_STRICT) > 0) {
		require_correct_aspect_ratio = TRUE;
	}

	/* relax the requirements a bit */
	if ((helper->flags & AS_APP_VALIDATE_FLAG_RELAX) > 0) {
		ss_size_height_max = 1800;
		ss_size_height_min = 150;
		ss_size_width_max = 3200;
		ss_size_width_min = 300;
	}

	/* have we got network access */
	if ((helper->flags & AS_APP_VALIDATE_FLAG_NO_NETWORK) > 0)
		return TRUE;

	/* GET file */
	url = as_image_get_url (im);
	g_debug ("checking %s", url);
	base_uri = soup_uri_new (url);
	if (!SOUP_URI_VALID_FOR_HTTP (base_uri)) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_URL_NOT_FOUND,
				     "<screenshot> url not valid [%s]", url);
		return FALSE;
	}
	msg = soup_message_new_from_uri (SOUP_METHOD_GET, base_uri);
	if (msg == NULL) {
		g_warning ("Failed to setup message");
		return FALSE;
	}

	/* send sync */
	status_code = soup_session_send_message (helper->session, msg);
	if (SOUP_STATUS_IS_TRANSPORT_ERROR(status_code)) {
		ai_app_validate_add (helper,
			AS_PROBLEM_KIND_URL_NOT_FOUND,
			"<screenshot> failed to connect: %s [%s]",
			soup_status_get_phrase(status_code), url);
		return FALSE;
	} else if (status_code != SOUP_STATUS_OK) {
		ai_app_validate_add (helper,
			AS_PROBLEM_KIND_URL_NOT_FOUND,
			"<screenshot> failed to download (HTTP %d: %s) [%s]",
			status_code, soup_status_get_phrase(status_code), url);
		return FALSE;
	}

	/* check if it's a zero sized file */
	if (msg->response_body->length == 0) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_FILE_INVALID,
				     "<screenshot> url is a zero length file [%s]",
				     url);
		return FALSE;
	}

	/* create a buffer with the data */
	stream = g_memory_input_stream_new_from_data (msg->response_body->data,
						      (gssize) msg->response_body->length,
						      NULL);
	if (stream == NULL) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_URL_NOT_FOUND,
				     "<screenshot> failed to load data [%s]",
				     url);
		return FALSE;
	}

	/* load the image */
	pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, NULL);
	if (pixbuf == NULL) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_FILE_INVALID,
				     "<screenshot> failed to load [%s]",
				     url);
		return FALSE;
	}

	/* check width matches */
	screenshot_width = (guint) gdk_pixbuf_get_width (pixbuf);
	screenshot_height = (guint) gdk_pixbuf_get_height (pixbuf);
	if (as_image_get_width (im) != 0 &&
	    as_image_get_width (im) != screenshot_width) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> width did not match specified [%s]",
				     url);
	}

	/* check height matches */
	if (as_image_get_height (im) != 0 &&
	    as_image_get_height (im) != screenshot_height) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> height did not match specified [%s]",
				     url);
	}

	/* check size is reasonable */
	if (screenshot_width < ss_size_width_min) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> width too small [%s] minimum is %upx",
				     url, ss_size_width_min);
	}
	if (screenshot_height < ss_size_height_min) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> height too small [%s] minimum is %upx",
				     url, ss_size_height_min);
	}
	if (screenshot_width > ss_size_width_max) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> width too large [%s] maximum is %upx",
				     url, ss_size_width_max);
	}
	if (screenshot_height > ss_size_height_max) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_ATTRIBUTE_INVALID,
				     "<screenshot> height too large [%s] maximum is %upx",
				     url, ss_size_height_max);
	}

	/* check padding */
	as_image_set_pixbuf (im, pixbuf);
	alpha_flags = as_image_get_alpha_flags (im);
	if ((alpha_flags & AS_IMAGE_ALPHA_FLAG_TOP) > 0||
	    (alpha_flags & AS_IMAGE_ALPHA_FLAG_BOTTOM) > 0) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_STYLE_INCORRECT,
				     "<image> has vertical padding [%s]",
				     url);
	}
	if ((alpha_flags & AS_IMAGE_ALPHA_FLAG_LEFT) > 0||
	    (alpha_flags & AS_IMAGE_ALPHA_FLAG_RIGHT) > 0) {
		ai_app_validate_add (helper,
				     AS_PROBLEM_KIND_STYLE_INCORRECT,
				     "<image> has horizontal padding [%s]",
				     url);
	}

	/* check aspect ratio */
	if (require_correct_aspect_ratio) {
		screenshot_aspect = (gdouble) screenshot_width / (gdouble) screenshot_height;
		if (ABS (screenshot_aspect - 1.777777777) > 0.1) {
			g_debug ("got aspect %.2f, wanted %.2f",
				 screenshot_aspect, desired_aspect);
			ai_app_validate_add (helper,
					     AS_PROBLEM_KIND_ASPECT_RATIO_INCORRECT,
					     "<screenshot> aspect ratio not 16:9 [%s]",
					     url);
		}
	}
	return TRUE;
}
コード例 #8
0
ファイル: ntlm-test.c プロジェクト: BabaNina/libsoup
static void
do_message (SoupSession *session, SoupURI *base_uri, const char *path,
	    gboolean get_ntlm_prompt, gboolean do_ntlm,
	    gboolean get_basic_prompt, gboolean do_basic,
	    guint status_code)
{
	SoupURI *uri;
	SoupMessage *msg;
	NTLMState state = { FALSE, FALSE, FALSE, FALSE };

	uri = soup_uri_new_with_base (base_uri, path);
	msg = soup_message_new_from_uri ("GET", uri);
	soup_uri_free (uri);

	g_signal_connect (msg, "got_headers",
			  G_CALLBACK (prompt_check), &state);
	g_signal_connect (msg, "got_headers",
			  G_CALLBACK (challenge_check), &state);
	g_signal_connect (msg, "wrote-headers",
			  G_CALLBACK (request_check), &state);
	g_signal_connect (msg, "wrote-headers",
			  G_CALLBACK (response_check), &state);

	soup_session_send_message (session, msg);
	debug_printf (1, "  %-10s -> ", path);

	if (state.got_ntlm_prompt) {
		debug_printf (1, " NTLM_PROMPT");
		if (!get_ntlm_prompt) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (get_ntlm_prompt) {
		debug_printf (1, " no-ntlm-prompt???");
		errors++;
	}

	if (state.got_basic_prompt) {
		debug_printf (1, " BASIC_PROMPT");
		if (!get_basic_prompt) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (get_basic_prompt) {
		debug_printf (1, " no-basic-prompt???");
		errors++;
	}

	if (state.sent_ntlm_request) {
		debug_printf (1, " REQUEST");
		if (!do_ntlm) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (do_ntlm) {
		debug_printf (1, " no-request???");
		errors++;
	}

	if (state.got_ntlm_challenge) {
		debug_printf (1, " CHALLENGE");
		if (!do_ntlm) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (do_ntlm) {
		debug_printf (1, " no-challenge???");
		errors++;
	}

	if (state.sent_ntlm_response) {
		debug_printf (1, " NTLM_RESPONSE");
		if (!do_ntlm) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (do_ntlm) {
		debug_printf (1, " no-ntlm-response???");
		errors++;
	}

	if (state.sent_basic_response) {
		debug_printf (1, " BASIC_RESPONSE");
		if (!do_basic) {
			debug_printf (1, "???");
			errors++;
		}
	} else if (do_basic) {
		debug_printf (1, " no-basic-response???");
		errors++;
	}

	debug_printf (1, " -> %s", msg->reason_phrase);
	if (msg->status_code != status_code) {
		debug_printf (1, "???");
		errors++;
	}
	debug_printf (1, "\n");

	g_object_unref (msg);
}
コード例 #9
0
ファイル: continue-test.c プロジェクト: NEVERMOR/libsoup
static void
do_message (const char *path, gboolean long_body,
	    gboolean expect_continue, gboolean auth,
	    ...)
{
	SoupSession *session;
	SoupMessage *msg;
	const char *body;
	char *uri;
	va_list ap;
	const char *expected_event;
	char *actual_event;
	int expected_status, actual_status;
	static int count = 1;

	debug_printf (1, "%d. /%s, %s body, %sExpect, %s password\n",
		      count++, path,
		      long_body ? "long" : "short",
		      expect_continue ? "" : "no ",
		      auth ? "with" : "without");

	uri = g_strdup_printf ("http://%s127.0.0.1:%d/%s",
			       auth ? "user:pass@" : "",
			       port, path);
	msg = soup_message_new ("POST", uri);
	g_free (uri);

	body = long_body ? LONG_BODY : SHORT_BODY;
	soup_message_set_request (msg, "text/plain", SOUP_MEMORY_STATIC,
				  body, strlen (body));
	soup_message_headers_append (msg->request_headers, "Connection", "close");
	if (expect_continue) {
		soup_message_headers_set_expectations (msg->request_headers,
						       SOUP_EXPECTATION_CONTINUE);
	}

	g_signal_connect (msg, "got_informational",
			  G_CALLBACK (got_informational), "client");
	g_signal_connect (msg, "got_headers",
			  G_CALLBACK (got_headers), "client");
	g_signal_connect (msg, "got_body",
			  G_CALLBACK (got_body), "client");
	g_signal_connect (msg, "wrote_informational",
			  G_CALLBACK (wrote_informational), "client");
	g_signal_connect (msg, "wrote_headers",
			  G_CALLBACK (wrote_headers), "client");
	g_signal_connect (msg, "wrote_body",
			  G_CALLBACK (wrote_body), "client");
	g_signal_connect (msg, "finished",
			  G_CALLBACK (finished), "client");

	events = NULL;
	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	soup_session_send_message (session, msg);
	soup_test_session_abort_unref (session);

	va_start (ap, auth);
	while ((expected_event = va_arg (ap, const char *))) {

		if (!events) {
			actual_event = g_strdup ("");
			debug_printf (1, "  Expected '%s', got end of list\n",
				      expected_event);
			errors++;
		} else {
			actual_event = events->data;
			if (strcmp (expected_event, actual_event) != 0) {
				debug_printf (1, "  Expected '%s', got '%s'\n",
					      expected_event, actual_event);
				errors++;
			}
			events = g_slist_delete_link (events, events);
		}

		if (!strcmp (expected_event, "server-wrote_headers") ||
		    !strcmp (expected_event, "server-wrote_informational"))
			expected_status = va_arg (ap, int);
		else
			expected_status = -1;
		if (!strcmp (actual_event, "server-wrote_headers") ||
		    !strcmp (actual_event, "server-wrote_informational")) {
			actual_status = GPOINTER_TO_INT (events->data);
			events = g_slist_delete_link (events, events);
		} else
			expected_status = -1;

		if (expected_status != -1 && actual_status != -1 &&
		    expected_status != actual_status) {
			debug_printf (1, "  Expected status '%s', got '%s'\n",
				      soup_status_get_phrase (expected_status),
				      soup_status_get_phrase (actual_status));
			errors++;
		}

		g_free (actual_event);
	}
コード例 #10
0
SoupBuffer *
open_app_get_data_by_request (SoupSession *session, const gchar *request)
{
	SoupMessage *msg;
	SoupBuffer *buf;
	const gchar *name;
	const gchar *header;
	const gchar *method;

	g_return_val_if_fail (request != NULL, NULL);

//	g_debug ("open_app_get_data_by_request: %s\n", request);

	buf = NULL;
	method = SOUP_METHOD_GET;
	msg = soup_message_new (method, request);
	soup_message_set_flags (msg, SOUP_MESSAGE_NO_REDIRECT);
	soup_session_send_message (session, msg);

	name = soup_message_get_uri (msg)->path;

	
	if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
		g_debug ("%s: %d %s\n", name, msg->status_code, msg->reason_phrase);
	} else {
#ifdef SERVER_DEBUG
		SoupMessageHeadersIter iter;
		const gchar *hname, *value;
		gchar *path = soup_uri_to_string (soup_message_get_uri (msg), TRUE);

		g_debug ("%s %s HTTP/1.%d\n", method, path,
			soup_message_get_http_version (msg));
		g_free (path);
		soup_message_headers_iter_init (&iter, msg->request_headers);
		while (soup_message_headers_iter_next (&iter, &hname, &value))
			g_debug ("%s: %s\r\n", hname, value);
		g_debug ("\n");

		g_debug ("HTTP/1.%d %d %s\n",
			soup_message_get_http_version (msg),
			msg->status_code, msg->reason_phrase);
		soup_message_headers_iter_init (&iter, msg->response_headers);
		while (soup_message_headers_iter_next (&iter, &hname, &value))
			g_debug ("%s: %s\r\n", hname, value);
		g_debug ("\n");
#endif
	}

	if (SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
		header = soup_message_headers_get_one (msg->response_headers,
						       "Location");
		if (header) {
			SoupURI *request;
			gchar *request_string;

			g_debug ("   -> %s\n", header);

			request = soup_uri_new_with_base (soup_message_get_uri (msg), header);
			request_string = soup_uri_to_string (request, FALSE);
			buf = open_app_get_data_by_request (session, request_string);
			g_free (request_string);
			soup_uri_free (request);
		}
	} else if (SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		buf = soup_message_body_flatten (msg->response_body);
	}

	g_object_unref (msg);

	return buf;
}
コード例 #11
0
ファイル: geniuspaste.c プロジェクト: BYC/geany-plugins
static void paste(GeanyDocument * doc, const gchar * website)
{
    SoupSession *session;
    SoupMessage *msg = NULL;

    gchar *f_content;
    gchar const *f_type;
    gchar *f_title;
    gchar *p_url;
    gchar *formdata = NULL;
    gchar *user_agent = NULL;
    gchar **tokens_array;

    const gchar *langs_supported_codepad[] =
    {
        "C", "C++", "D", "Haskell",
        "Lua", "OCaml", "PHP", "Perl", "Plain Text",
        "Python", "Ruby", "Scheme", "Tcl"
    };

    const gchar *langs_supported_dpaste[] =
    {
        "Bash", "C", "CSS", "Diff",
        "Django/Jinja", "HTML", "IRC logs", "JavaScript", "PHP",
        "Python console session", "Python Traceback", "Python",
        "Python3", "Restructured Text", "SQL", "Text only"
    };

    gint occ_position;
    gint i;
    guint status;
    gsize f_length;

    g_return_if_fail(doc && doc->is_valid);

    f_type = doc->file_type->name;

    if (doc->file_name == NULL)
        f_title = document_get_basename_for_display(doc, -1);
    else
        f_title = g_path_get_basename(doc->file_name);

    load_settings();
    
    f_content = get_paste_text(doc, &f_length);
    if (f_content == NULL || f_content[0] == '\0')
    {
        dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Refusing to create blank paste"));
        return;
    }

    switch (website_selected)
    {

    case CODEPAD_ORG:

        for (i = 0; i < G_N_ELEMENTS(langs_supported_codepad); i++)
        {
            if (g_strcmp0(f_type, langs_supported_codepad[i]) == 0)
                break;
            else
                f_type = DEFAULT_TYPE_CODEPAD;
        }

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("lang", f_type,
                                    "code", f_content,
                                    "submit", "Submit",
                                    NULL);

        break;

    case TINYPASTE_COM:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("paste", f_content, 
                                    "title", f_title,
                                    "is_code", g_strcmp0(f_type, "None") == 0 ? "0" : "1",
                                    NULL);

        break;


    case DPASTE_DE:

        for (i = 0; i < G_N_ELEMENTS(langs_supported_dpaste); i++)
        {
            if (g_strcmp0(f_type, langs_supported_dpaste[i]) == 0)
                break;
            else
                f_type = DEFAULT_TYPE_DPASTE;
        }

        msg = soup_message_new("POST", website);
        /* apparently dpaste.de detects automatically the syntax of the
         * pasted code so 'lexer' should be unneeded
         */
        formdata = soup_form_encode("content", f_content,
                                    "title", f_title,
                                    "lexer", f_type,
                                    NULL);

        break;

    case SPRUNGE_US:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("sprunge", f_content, NULL);

        break;

    case PASTEBIN_GEANY_ORG:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("content", f_content,
                                    "author", author_name,
                                    "title", f_title,
                                    "lexer", f_type,
                                    NULL);

        break;

    }

    g_free(f_content);

    user_agent = g_strconcat(PLUGIN_NAME, " ", PLUGIN_VERSION, " / Geany ", GEANY_VERSION, NULL);
    session = soup_session_async_new_with_options(SOUP_SESSION_USER_AGENT, user_agent, NULL);
    g_free(user_agent);

    soup_message_set_request(msg, "application/x-www-form-urlencoded",
                             SOUP_MEMORY_TAKE, formdata, strlen(formdata));

    status = soup_session_send_message(session, msg);
    p_url = g_strdup(msg->response_body->data);

    g_object_unref(session);
    g_object_unref(msg);

    if(status == SOUP_STATUS_OK)
    {

        /*
         * codepad.org doesn't return only the url of the new snippet pasted
         * but an html page. This minimal parser will get the bare url.
         */

        if (website_selected == CODEPAD_ORG)
        {
            tokens_array = g_strsplit(p_url, "<a href=\"", 0);

            /* cuts the string when it finds the first occurrence of '/'
             * It shoud work even if codepad would change its url.
             */

            SETPTR(p_url, g_strdup(tokens_array[5]));
            occ_position = indexof(tokens_array[5], '\"');

            g_strfreev(tokens_array);

            if(occ_position != -1)
            {
                p_url[occ_position] = '\0';
            }
            else
            {
                dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Unable to paste the code on codepad.org\n"
                                    "Retry or select another pastebin."));
                g_free(p_url);
                return;
            }

        }
        else if(website_selected == TINYPASTE_COM)
        {
            /* tinypaste.com returns a XML response which looks
             * like this:
             * 
             * <?xml version="1.0" encoding="utf-8"?>
             * <result>
             *      <response>xxxxx</response>
             * </result>
             */
            tokens_array = g_strsplit_set(p_url, "<>", 0);
            
            SETPTR(p_url, g_strdup_printf("http://%s/%s", websites[TINYPASTE_COM], tokens_array[6]));
            
            g_strfreev(tokens_array);
        }
            
        else if(website_selected == DPASTE_DE)
        {
            SETPTR(p_url, g_strndup(p_url + 1, strlen(p_url) - 2));

        }
        else if(website_selected == SPRUNGE_US)
        {

            /* in order to enable the syntax highlightning on sprunge.us
             * it is necessary to append at the returned url a question
             * mark '?' followed by the file type.
             *
             * e.g. sprunge.us/xxxx?c
             */
            gchar *ft_tmp = g_ascii_strdown(f_type, -1);
            g_strstrip(p_url);
            SETPTR(p_url, g_strdup_printf("%s?%s", p_url, ft_tmp));
            g_free(ft_tmp);
        }

        if (check_button_is_checked)
        {
            utils_open_browser(p_url);
        }
        else
        {
            GtkWidget *dlg = gtk_message_dialog_new(GTK_WINDOW(geany->main_widgets->window),
                GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
                _("Paste Successful"));
            gtk_message_dialog_format_secondary_markup(GTK_MESSAGE_DIALOG(dlg),
                _("Your paste can be found here:\n<a href=\"%s\" "
                "title=\"Click to open the paste in your browser\">%s</a>"), p_url, p_url);
            gtk_dialog_run(GTK_DIALOG(dlg));
            gtk_widget_destroy(dlg);
        }
    }
    else
    {
        dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Unable to paste the code. Check your connection and retry.\n"
                            "Error code: %d\n"), status);
    }

    g_free(p_url);
}
コード例 #12
0
ファイル: network-soup.c プロジェクト: UIKit0/evolution-rss
gboolean
net_queue_dispatcher(void)
{
	STNET *_stnet;
	guint qlen = g_queue_get_length(rf->stqueue);

	d("que len:%d workers:%d\n",
		g_queue_get_length(rf->stqueue),
		net_queue_run_count);

#if EVOLUTION_VERSION < 30304
	if (qlen && net_queue_run_count < gconf_client_get_int (
						rss_gconf,
						GCONF_KEY_DOWNLOAD_QUEUE_SIZE,
						NULL)) {
#else
	if (qlen && net_queue_run_count < g_settings_get_int (
						settings,
						CONF_DOWNLOAD_QUEUE_SIZE)) {
#endif
		net_queue_run_count++;
		_stnet = g_queue_pop_head(rf->stqueue);
		soup_session_queue_message (
			_stnet->ss,
			_stnet->sm,
			_stnet->cb2,
			_stnet->cbdata2);
		g_free(_stnet);
		return TRUE;
	}
	net_qid = 0;
	return FALSE;
}

GString*
net_post_blocking(gchar *url,
	GSList *headers,
	GString *post,
	NetStatusCallback cb,
	gpointer data,
	GError **err) {
#if LIBSOUP_VERSION < 2003000
	SoupUri *suri = NULL;
#else
	SoupURI *suri = NULL;
#endif
	SoupMessage *req = NULL;
	GString *response = NULL;
	CallbackInfo info = { cb, data, 0, 0 };
	SoupSession *soup_sess = NULL;
	gchar *agstr;

	if (!rf->b_session)
		rf->b_session = soup_sess =
			soup_session_sync_new_with_options(
				SOUP_SESSION_TIMEOUT,
				SS_TIMEOUT,
				NULL);
	else
		soup_sess = rf->b_session;


	g_signal_connect (soup_sess,
		"authenticate",
		G_CALLBACK (authenticate),
		(gpointer)url);
#if LIBSOUP_VERSION < 2003000
	g_signal_connect (soup_sess,
		"reauthenticate",
		G_CALLBACK (reauthenticate),
		(gpointer)url);
#endif

	req = soup_message_new(SOUP_METHOD_GET, url);
	if (!req) {
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC, "%s",
				soup_status_get_phrase(2));			//invalid url
		goto out;
	}
	d("request ok :%d\n", req->status_code);
	g_signal_connect(G_OBJECT(req), "got-chunk",
			G_CALLBACK(got_chunk_blocking_cb), &info);
	for (; headers; headers = headers->next) {
		char *header = headers->data;
		/* soup wants the key and value separate, so we have to munge this
		 * a bit. */
		char *colonpos = strchr(header, ':');
		*colonpos = 0;
#if LIBSOUP_VERSION < 2003000
		soup_message_add_header(
			req->request_headers,
			header,
			colonpos+1);
#else
		soup_message_headers_append(
			req->request_headers, header, colonpos+1);
#endif
		*colonpos = ':';
	}
	agstr = g_strdup_printf("Evolution/%s; Evolution-RSS/%s",
			EVOLUTION_VERSION_STRING, VERSION);
#if LIBSOUP_VERSION < 2003000
	soup_message_add_header (
		req->request_headers,
		"User-Agent",
		agstr);
#else
	soup_message_headers_append (
		req->request_headers,
		"User-Agent",
		agstr);
#endif
	g_free(agstr);

#if (DATASERVER_VERSION >= 2023001)
	proxify_session(proxy, soup_sess, url);
#endif
	rf->b_session = soup_sess;
	rf->b_msg_session = req;
	soup_session_send_message(soup_sess, req);

	if (req->status_code != SOUP_STATUS_OK) {
		//might not be a good ideea
		soup_session_abort(soup_sess);
		g_object_unref(soup_sess);
		rf->b_session = NULL;
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC, "%s",
				soup_status_get_phrase(req->status_code));
		goto out;
	}

#if LIBSOUP_VERSION < 2003000
	response = g_string_new_len(
			req->response.body,
			req->response.length);
#else
	response = g_string_new_len(
			req->response_body->data,
			req->response_body->length);
#endif

out:
	if (suri) soup_uri_free(suri);
	if (req) g_object_unref(G_OBJECT(req));

	return response;
}
コード例 #13
0
ファイル: network-soup.c プロジェクト: UIKit0/evolution-rss
guint
net_get_status(const char *url, GError **err)
{
#if LIBSOUP_VERSION < 2003000
	SoupUri *suri = NULL;
#else
	SoupURI *suri = NULL;
#endif
	SoupMessage *req = NULL;
	guint response = 0;
	SoupSession *soup_sess = NULL;
	GSList *headers = NULL;
	gchar *agstr;

	if (!rf->b_session)
		rf->b_session = soup_sess =
			soup_session_sync_new_with_options(
				SOUP_SESSION_TIMEOUT, SS_TIMEOUT, NULL);
	else
		soup_sess = rf->b_session;

	req = soup_message_new(SOUP_METHOD_GET, url);
	if (!req) {
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC, "%s",
				soup_status_get_phrase(2));			//invalid url
		goto out;
	}
	for (; headers; headers = headers->next) {
		char *header = headers->data;
		/* soup wants the key and value separate, so we have to munge this
		 * a bit. */
		char *colonpos = strchr(header, ':');
		*colonpos = 0;
#if LIBSOUP_VERSION < 2003000
		soup_message_add_header(
			req->request_headers, header, colonpos+1);
#else
		soup_message_headers_append(
			req->request_headers, header, colonpos+1);
#endif
		*colonpos = ':';
	}
	agstr = g_strdup_printf("Evolution/%s; Evolution-RSS/%s",
			EVOLUTION_VERSION_STRING, VERSION);
#if LIBSOUP_VERSION < 2003000
	soup_message_add_header (req->request_headers,
		"User-Agent",
		agstr);
#else
	soup_message_headers_append (req->request_headers,
		"User-Agent",
		agstr);
#endif
	g_free(agstr);

	rf->b_session = soup_sess;
	rf->b_msg_session = req;
	soup_session_send_message(soup_sess, req);

	if (req->status_code != SOUP_STATUS_OK) {
		//might not be a good ideea
		soup_session_abort(soup_sess);
		g_object_unref(soup_sess);
		rf->b_session = NULL;
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC, "%s",
				soup_status_get_phrase(req->status_code));
		goto out;
	}

out:
	if (suri) soup_uri_free(suri);
	response = req->status_code;
	if (req) g_object_unref(G_OBJECT(req));

	return response;
}
コード例 #14
0
ファイル: MediaDownloader.c プロジェクト: remeh/corebird
static void
cb_media_downloader_load_threaded (CbMediaDownloader *downloader,
                                   CbMedia           *media)
{
  const char *url;
  SoupMessage *msg;
  GInputStream *input_stream;

  g_return_if_fail (CB_IS_MEDIA_DOWNLOADER (downloader));
  g_return_if_fail (CB_IS_MEDIA (media));
  g_return_if_fail (media->url != NULL);

  g_object_ref (media);

  url = canonicalize_url (media->url);

  /* For these, we first need to download some html and get the real
     URL of the image we want to display */
  if (g_str_has_prefix (url, "instagr.am") ||
      g_str_has_prefix (url, "instagram.com/p/"))
    {
      cb_media_downloader_get_instagram_url (downloader, media);
    }
  else if (g_str_has_prefix (url, "ow.ly/i/") ||
           g_str_has_prefix (url, "flickr.com/photos/") ||
           g_str_has_prefix (url, "flic.kr/p/") ||
           g_str_has_prefix (url, "flic.kr/s/") ||
           g_str_has_prefix (url, "vine.co/v/"))
    {
      cb_media_downloader_load_real_url (downloader, media,
                                         "<meta property=\"og:image\" content=\"(.*?)\"", 1);
    }
  else if (g_str_has_prefix (url, "twitpic.com/"))
    {
      cb_media_downloader_load_real_url (downloader, media,
                                         "<meta name=\"twitter:image\" value=\"(.*?)\"", 1);
    }
  else if (g_str_has_suffix (url, "/photo/1"))
    {
      cb_media_downloader_load_twitter_video (downloader, media);
    }
  else if (g_str_has_prefix (url, "d.pr/i/"))
    {
      cb_media_downloader_load_real_url (downloader, media,
                                         "<meta property=\"og:image\"\\s+content=\"(.*?)\"", 1);
    }

  if (media->url == NULL)
    {
      g_warning ("Media is invalid.");
      mark_invalid (media);
      return;
    }


  msg = soup_message_new ("GET", media->thumb_url ? media->thumb_url : media->url);
  if (msg == NULL)
    {
      mark_invalid (media);
      g_warning ("soup_message_new failed for URI '%s'",
                 media->thumb_url ? media->thumb_url : media->url);
      return;
    }
  g_signal_connect (msg, "got-chunk", G_CALLBACK (update_media_progress), media);
  soup_session_send_message (downloader->soup_session, msg);

  if (msg->status_code != SOUP_STATUS_OK)
    {
      g_debug ("Request on '%s' returned status '%s'",
               media->thumb_url ? media->thumb_url : media->url,
               soup_status_get_phrase (msg->status_code));

      mark_invalid (media);
      g_object_unref (msg);
      return;
    }

  input_stream = g_memory_input_stream_new_from_data (msg->response_body->data,
                                                      msg->response_body->length,
                                                      NULL);

  load_animation (input_stream, media);
  g_input_stream_close (input_stream, NULL, NULL);
  g_object_unref (input_stream);
  g_object_unref (msg);
}
コード例 #15
0
ファイル: fu-util.c プロジェクト: phomes/fwupd
/**
 * fu_util_download_file:
 **/
static gboolean
fu_util_download_file (FuUtilPrivate *priv,
		       const gchar *uri,
		       const gchar *fn,
		       const gchar *checksum_expected,
		       GError **error)
{
	guint status_code;
	_cleanup_error_free_ GError *error_local = NULL;
	_cleanup_free_ gchar *checksum_actual = NULL;
	_cleanup_object_unref_ SoupMessage *msg = NULL;
	_cleanup_object_unref_ SoupSession *session = NULL;

	session = soup_session_new_with_options (SOUP_SESSION_USER_AGENT,
						 "fwupdmgr",
						 NULL);
	if (session == NULL) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INTERNAL,
				     "%s: failed to setup networking");
		return FALSE;
	}

	/* this disables the double-compression of the firmware.xml.gz file */
	soup_session_remove_feature_by_type (session, SOUP_TYPE_CONTENT_DECODER);

	/* download data */
	g_debug ("downloading %s to %s:", uri, fn);
	msg = soup_message_new (SOUP_METHOD_GET, uri);
	status_code = soup_session_send_message (session, msg);
	if (status_code != SOUP_STATUS_OK) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INVALID_FILE,
			     "Failed to download %s: %s",
			     uri, soup_status_get_phrase (status_code));
		return FALSE;
	}

	/* verify checksum */
	if (checksum_expected != NULL) {
		checksum_actual = g_compute_checksum_for_data (G_CHECKSUM_SHA1,
							       (guchar *) msg->response_body->data,
							       msg->response_body->length);
		if (g_strcmp0 (checksum_expected, checksum_actual) != 0) {
			g_set_error (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INVALID_FILE,
				     "Checksum invalid, expected %s got %s",
				     checksum_expected, checksum_actual);
			return FALSE;
		}
	}

	/* save file */
	if (!g_file_set_contents (fn,
				  msg->response_body->data,
				  msg->response_body->length,
				  &error_local)) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_WRITE,
			     "Failed to save file: %s",
			     error_local->message);
		return FALSE;
	}
	return TRUE;
}
コード例 #16
0
static void
refine_app (GsPlugin *plugin, GsApp *app, JsonObject *package, gboolean from_search, GCancellable *cancellable)
{
	g_autofree gchar *macaroon = NULL;
	g_auto(GStrv) discharges = NULL;
	const gchar *status, *icon_url, *launch_name = NULL;
	g_autoptr(GdkPixbuf) icon_pixbuf = NULL;
	gint64 size = -1;

	get_macaroon (plugin, &macaroon, &discharges);

	status = json_object_get_string_member (package, "status");
	if (g_strcmp0 (status, "installed") == 0 || g_strcmp0 (status, "active") == 0) {
		const gchar *update_available;

		update_available = json_object_has_member (package, "update_available") ?
			json_object_get_string_member (package, "update_available") : NULL;
		if (update_available)
			gs_app_set_state (app, AS_APP_STATE_UPDATABLE);
		else {
			if (gs_app_get_state (app) == AS_APP_STATE_AVAILABLE)
				gs_app_set_state (app, AS_APP_STATE_UNKNOWN);
			gs_app_set_state (app, AS_APP_STATE_INSTALLED);
		}
	} else if (g_strcmp0 (status, "not installed") == 0 || g_strcmp0 (status, "available") == 0) {
		gs_app_set_state (app, AS_APP_STATE_AVAILABLE);
	}
	gs_app_set_name (app, GS_APP_QUALITY_HIGHEST,
			 json_object_get_string_member (package, "summary"));
	gs_app_set_summary (app, GS_APP_QUALITY_HIGHEST,
			    json_object_get_string_member (package, "summary"));
	gs_app_set_description (app, GS_APP_QUALITY_HIGHEST,
				json_object_get_string_member (package, "description"));
	gs_app_set_version (app, json_object_get_string_member (package, "version"));
	if (json_object_has_member (package, "installed-size")) {
		size = json_object_get_int_member (package, "installed-size");
		if (size > 0)
			gs_app_set_size_installed (app, (guint64) size);
	}
	if (json_object_has_member (package, "download-size")) {
		size = json_object_get_int_member (package, "download-size");
		if (size > 0)
			gs_app_set_size_download (app, (guint64) size);
	}
	gs_app_add_quirk (app, AS_APP_QUIRK_PROVENANCE);
	icon_url = json_object_get_string_member (package, "icon");
	if (g_str_has_prefix (icon_url, "/")) {
		g_autofree gchar *icon_data = NULL;
		gsize icon_data_length;
		g_autoptr(GError) error = NULL;

		icon_data = gs_snapd_get_resource (macaroon, discharges, icon_url, &icon_data_length, cancellable, &error);
		if (icon_data != NULL) {
			g_autoptr(GdkPixbufLoader) loader = NULL;

			loader = gdk_pixbuf_loader_new ();
			gdk_pixbuf_loader_write (loader,
						 (guchar *) icon_data,
						 icon_data_length,
						 NULL);
			gdk_pixbuf_loader_close (loader, NULL);
			icon_pixbuf = g_object_ref (gdk_pixbuf_loader_get_pixbuf (loader));
		}
		else
			g_printerr ("Failed to get icon: %s\n", error->message);
	}
	else {
		g_autoptr(SoupMessage) message = NULL;
		g_autoptr(GdkPixbufLoader) loader = NULL;

		message = soup_message_new (SOUP_METHOD_GET, icon_url);
		if (message != NULL) {
			soup_session_send_message (gs_plugin_get_soup_session (plugin), message);
			loader = gdk_pixbuf_loader_new ();
			gdk_pixbuf_loader_write (loader,
						 (guint8 *) message->response_body->data,
						 (gsize) message->response_body->length,
						 NULL);
			gdk_pixbuf_loader_close (loader, NULL);
			icon_pixbuf = g_object_ref (gdk_pixbuf_loader_get_pixbuf (loader));
		}
	}

	if (icon_pixbuf) {
		gs_app_set_pixbuf (app, icon_pixbuf);
	} else {
		g_autoptr(AsIcon) icon = as_icon_new ();
		as_icon_set_kind (icon, AS_ICON_KIND_STOCK);
		as_icon_set_name (icon, "package-x-generic");
		gs_app_add_icon (app, icon);
	}

	if (json_object_has_member (package, "screenshots") && gs_app_get_screenshots (app)->len <= 0) {
		JsonArray *screenshots;
		guint i;

		screenshots = json_object_get_array_member (package, "screenshots");
		for (i = 0; i < json_array_get_length (screenshots); i++) {
			JsonObject *screenshot = json_array_get_object_element (screenshots, i);
			g_autoptr(AsScreenshot) ss = NULL;
			g_autoptr(AsImage) image = NULL;

			ss = as_screenshot_new ();
			as_screenshot_set_kind (ss, AS_SCREENSHOT_KIND_NORMAL);
			image = as_image_new ();
			as_image_set_url (image, json_object_get_string_member (screenshot, "url"));
			as_image_set_kind (image, AS_IMAGE_KIND_SOURCE);
			as_screenshot_add_image (ss, image);
			gs_app_add_screenshot (app, ss);
		}
	}

	if (!from_search) {
		JsonArray *apps;

		apps = json_object_get_array_member (package, "apps");
		if (apps && json_array_get_length (apps) > 0)
			launch_name = json_object_get_string_member (json_array_get_object_element (apps, 0), "name");

		if (launch_name)
			gs_app_set_metadata (app, "snap::launch-name", launch_name);
		else
			gs_app_add_quirk (app, AS_APP_QUIRK_NOT_LAUNCHABLE);
	}
}
コード例 #17
0
ファイル: auth-test.c プロジェクト: simonmiddleton/libsoup
static void
do_batch_tests (gconstpointer data)
{
	const SoupAuthTest *current_tests = data;
	SoupSession *session;
	SoupMessage *msg;
	char *expected, *uristr;
	SoupURI *base;
	guint signal;
	int i;

	SOUP_TEST_SKIP_IF_NO_APACHE;

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	base = soup_uri_new (base_uri);

	for (i = 0; current_tests[i].url; i++) {
		SoupURI *soup_uri = soup_uri_new_with_base (base, current_tests[i].url);

		debug_printf (1, "Test %d: %s\n", i + 1, current_tests[i].explanation);

		if (current_tests[i].url_auth) {
			gchar *username = g_strdup_printf ("user%c", current_tests[i].provided[0]);
			gchar *password = g_strdup_printf ("realm%c", current_tests[i].provided[0]);
			soup_uri_set_user (soup_uri, username);
			soup_uri_set_password (soup_uri, password);
			g_free (username);
			g_free (password);
		}

		msg = soup_message_new_from_uri (SOUP_METHOD_GET, soup_uri);
		soup_uri_free (soup_uri);
		if (!msg) {
			g_printerr ("auth-test: Could not parse URI\n");
			exit (1);
		}

		uristr = soup_uri_to_string (soup_message_get_uri (msg), FALSE);
		debug_printf (1, "  GET %s\n", uristr);
		g_free (uristr);

		expected = g_strdup (current_tests[i].expected);
		soup_message_add_status_code_handler (
			msg, "got_headers", SOUP_STATUS_UNAUTHORIZED,
			G_CALLBACK (handler), expected);
		soup_message_add_status_code_handler (
			msg, "got_headers", SOUP_STATUS_OK,
			G_CALLBACK (handler), expected);

		signal = g_signal_connect (session, "authenticate",
					   G_CALLBACK (authenticate),
					   (gpointer)&current_tests[i]);
		soup_session_send_message (session, msg);
		g_signal_handler_disconnect (session, signal);

		soup_test_assert_message_status (msg, current_tests[i].final_status);
		soup_test_assert (!*expected,
				  "expected %d more round(s)\n",
				  (int)strlen (expected));

		g_free (expected);
		debug_printf (1, "\n");

		g_object_unref (msg);
	}
	soup_uri_free (base);

	soup_test_session_abort_unref (session);
}
コード例 #18
0
ファイル: cookies-test.c プロジェクト: DrGore/libsoup
/* FIXME: moar tests! */
static void
do_cookies_parsing_test (void)
{
	SoupSession *session;
	SoupMessage *msg;
	SoupCookieJar *jar;
	GSList *cookies, *iter;
	SoupCookie *cookie;
	gboolean got1, got2, got3;

	debug_printf (1, "\nSoupCookie parsing test\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	soup_session_add_feature_by_type (session, SOUP_TYPE_COOKIE_JAR);
	jar = SOUP_COOKIE_JAR (soup_session_get_feature (session, SOUP_TYPE_COOKIE_JAR));

	/* "httponly" is case-insensitive, and its value (if any) is ignored */
	msg = soup_message_new_from_uri ("GET", first_party_uri);
	soup_message_headers_append (msg->request_headers, "Echo-Set-Cookie",
				     "one=1; httponly; max-age=100");
	soup_session_send_message (session, msg);
	g_object_unref (msg);

	msg = soup_message_new_from_uri ("GET", first_party_uri);
	soup_message_headers_append (msg->request_headers, "Echo-Set-Cookie",
				     "two=2; HttpOnly; max-age=100");
	soup_session_send_message (session, msg);
	g_object_unref (msg);

	msg = soup_message_new_from_uri ("GET", first_party_uri);
	soup_message_headers_append (msg->request_headers, "Echo-Set-Cookie",
				     "three=3; httpONLY=Wednesday; max-age=100");
	soup_session_send_message (session, msg);
	g_object_unref (msg);

	cookies = soup_cookie_jar_get_cookie_list (jar, first_party_uri, TRUE);
	got1 = got2 = got3 = FALSE;

	for (iter = cookies; iter; iter = iter->next) {
		cookie = iter->data;

		if (!strcmp (soup_cookie_get_name (cookie), "one")) {
			got1 = TRUE;
			if (!soup_cookie_get_http_only (cookie)) {
				debug_printf (1, "  cookie 1 is not HttpOnly!\n");
				errors++;
			}
			if (!soup_cookie_get_expires (cookie)) {
				debug_printf (1, "  cookie 1 did not fully parse!\n");
				errors++;
			}
		} else if (!strcmp (soup_cookie_get_name (cookie), "two")) {
			got2 = TRUE;
			if (!soup_cookie_get_http_only (cookie)) {
				debug_printf (1, "  cookie 2 is not HttpOnly!\n");
				errors++;
			}
			if (!soup_cookie_get_expires (cookie)) {
				debug_printf (1, "  cookie 3 did not fully parse!\n");
				errors++;
			}
		} else if (!strcmp (soup_cookie_get_name (cookie), "three")) {
			got3 = TRUE;
			if (!soup_cookie_get_http_only (cookie)) {
				debug_printf (1, "  cookie 3 is not HttpOnly!\n");
				errors++;
			}
			if (!soup_cookie_get_expires (cookie)) {
				debug_printf (1, "  cookie 3 did not fully parse!\n");
				errors++;
			}
		} else {
			debug_printf (1, "  got unexpected cookie '%s'\n",
				      soup_cookie_get_name (cookie));
			errors++;
		}

		soup_cookie_free (cookie);
	}
	g_slist_free (cookies);

	if (!got1) {
		debug_printf (1, "  didn't get cookie 1\n");
		errors++;
	}
	if (!got2) {
		debug_printf (1, "  didn't get cookie 2\n");
		errors++;
	}
	if (!got3) {
		debug_printf (1, "  didn't get cookie 3\n");
		errors++;
	}

	soup_test_session_abort_unref (session);
}	
コード例 #19
0
ファイル: login.c プロジェクト: tripcodeuser/piiptyyt
bool oauth_login(
	GtkBuilder *builder,
	char **username_p,
	char **auth_token_p,
	char **auth_secret_p,
	uint64_t *userid_p,
	GError **err_p)
{
#if !USE_LOCAL_CGI
	const char *token_uri = "https://api.twitter.com/oauth/request_token";
	const char *access_uri = "https://api.twitter.com/oauth/access_token";
#else
	const char *token_uri = "https://localhost/cgi-bin/oauth.cgi/request_token";
	const char *access_uri = "https://localhost/cgi-bin/oauth.cgi/access_token";
#endif

	SoupSession *ss = soup_session_async_new();
#if 0
	SoupLogger *logger = soup_logger_new(1, -1);
	soup_session_add_feature(ss, SOUP_SESSION_FEATURE(logger));
	g_object_unref(logger);
#endif

	SoupMessage *msg = make_token_request_msg(token_uri, CONSUMER_KEY,
		CONSUMER_SECRET);
	if(msg == NULL) {
		/* FIXME */
		abort();
	}
	soup_session_send_message(ss, msg);

	bool ok;
	if(msg->status_code != SOUP_STATUS_OK) {
		fprintf(stderr, "%s: server returned status %d (%s)\n", __func__,
			msg->status_code, soup_status_get_phrase(msg->status_code));
		ok = false;
		goto end;
	}

	/* interpret the response. */
	char **rt_output = oa_parse_response(msg->response_body->data,
		"oauth_token", "oauth_token_secret", NULL);
	if(rt_output == NULL) {
		g_set_error(err_p, 0, EINVAL, "can't parse response data");
		ok = false;
		goto end;
	}

	/* do out-of-band OAuth */
	const char *req_token = rt_output[0], *req_secret = rt_output[1];
#if !USE_LOCAL_CGI
	GError *err = NULL;
	if(!launch_authorization_browser(req_token, &err)) {
		fprintf(stderr, "warning: browser launching failed: %s\n",
			err->message);
		g_error_free(err);
	}
#endif

	char *pin = query_pin(builder);
	printf("PIN is: `%s'\n", pin);

	/* get an access token */
	g_object_unref(msg);
	msg = make_access_token_request_msg(access_uri, req_token, req_secret,
		pin, CONSUMER_KEY, CONSUMER_SECRET);
	g_free(pin);
	if(msg == NULL) {
		fprintf(stderr, "can't sign access request message!\n");
		abort();
	}
	soup_session_send_message(ss, msg);

	if(msg->status_code != SOUP_STATUS_OK) {
		fprintf(stderr, "%s: server returned status %d (%s)\n", __func__,
			msg->status_code, soup_status_get_phrase(msg->status_code));
		/* FIXME: handle */
		abort();
	}
	char **at_output = oa_parse_response(msg->response_body->data,
		"oauth_token", "oauth_token_secret", "user_id", "screen_name", NULL);
	if(at_output == NULL) {
		/* FIXME: response data parsing fail */
		abort();
	}
	/* the payoff */
	*auth_token_p = g_strdup(at_output[0]);
	*auth_secret_p = g_strdup(at_output[1]);
	*userid_p = strtoull(at_output[2], NULL, 10);
	*username_p = g_strdup(at_output[3]);

	printf("login successful! username `%s', userid %llu\n", *username_p,
		(unsigned long long)*userid_p);

	g_strfreev(at_output);
	g_strfreev(rt_output);

	ok = true;

end:
	g_object_unref(msg);
	g_object_unref(ss);

	return ok;
}
コード例 #20
0
/**
 * gs_plugin_fedora_tagger_download:
 */
static gboolean
gs_plugin_fedora_tagger_download (GsPlugin *plugin, GError **error)
{
	FedoraTaggerItem *item;
	gdouble count_sum = 0;
	guint i;
	guint status_code;
	_cleanup_free_ gchar *uri = NULL;
	_cleanup_object_unref_ SoupMessage *msg = NULL;
	_cleanup_ptrarray_unref_ GPtrArray *items = NULL;
	_cleanup_strv_free_ gchar **split = NULL;

	/* create the GET data */
	uri = g_strdup_printf ("%s/api/v1/rating/dump/",
			       GS_PLUGIN_FEDORA_TAGGER_SERVER);
	msg = soup_message_new (SOUP_METHOD_GET, uri);

	/* ensure networking is set up */
	if (!gs_plugin_setup_networking (plugin, error))
		return FALSE;

	/* set sync request */
	status_code = soup_session_send_message (plugin->priv->session, msg);
	if (status_code != SOUP_STATUS_OK) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_FAILED,
			     "Failed to download fedora-tagger dump: %s",
			     soup_status_get_phrase (status_code));
		return FALSE;
	}

	/* process the tab-delimited data */
	items = g_ptr_array_new_with_free_func ((GDestroyNotify) fedora_tagger_item_free);
	split = g_strsplit (msg->response_body->data, "\n", -1);
	for (i = 0; split[i] != NULL; i++) {
		_cleanup_strv_free_ gchar **fields = NULL;
		if (split[i][0] == '\0' ||
		    split[i][0] == '#')
			continue;
		fields = g_strsplit (split[i], "\t", -1);
		if (g_strv_length (fields) == 4) {
			item = g_slice_new0 (FedoraTaggerItem);
			item->pkgname = g_strdup (fields[0]);
			item->rating = g_strtod (fields[1], NULL);
			item->vote_count = g_strtod (fields[2], NULL);
			item->user_count = g_strtod (fields[3], NULL);
			g_ptr_array_add (items, item);
		} else {
			g_warning ("unexpected data from fedora-tagger, expected: "
				   "'pkgname\trating\tvote_count\tuser_count' and got '%s'",
				   split[i]);
		}
	}

	/* no suitable data? */
	if (items->len == 0) {
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     "Failed to get data from fedora-tagger");
		return FALSE;
	}

	/* calculate confidence */
	for (i = 0; i < items->len; i++) {
		item = g_ptr_array_index (items, i);
		count_sum += item->vote_count;
	}
	if (count_sum == 0) {
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     "Failed to get vote count in fedora-tagger");
		return FALSE;
	}
	count_sum /= (gdouble) items->len;
	g_debug ("fedora-tagger vote_count average is %.2f", count_sum);
	for (i = 0; i < items->len; i++) {
		item = g_ptr_array_index (items, i);
		item->confidence = MAX (100.0f * item->vote_count / count_sum, 100);
	}

	/* add each completed item */
	for (i = 0; i < items->len; i++) {
		item = g_ptr_array_index (items, i);
		g_debug ("adding %s: %.1f%% [%.1f] {%.1f%%}",
			 item->pkgname, item->rating,
			 item->vote_count, item->confidence);
		if (!gs_plugin_fedora_tagger_add (plugin, item, error))
			return FALSE;
	}

	/* reset the timestamp */
	return gs_plugin_fedora_tagger_set_timestamp (plugin, "mtime", error);
}
コード例 #21
0
ファイル: coding-test.c プロジェクト: NEVERMOR/libsoup
static void
do_coding_test (void)
{
	SoupSession *session;
	SoupMessage *msg, *msgz, *msgj, *msge, *msgzl, *msgzlj, *msgzle, *msgzlr, *msgzlre;
	SoupURI *uri;

	debug_printf (1, "SoupMessage tests\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	uri = soup_uri_new_with_base (base_uri, "/mbox");

	/* Plain text data, no claim */
	debug_printf (1, "  GET /mbox, plain\n");
	msg = soup_message_new_from_uri ("GET", uri);
	soup_session_send_message (session, msg);
	check_response (msg, NULL, "text/plain", EXPECT_NOT_DECODED);

	/* Plain text data, claim gzip */
	debug_printf (1, "  GET /mbox, Accept-Encoding: gzip\n");
	soup_session_add_feature_by_type (session, SOUP_TYPE_CONTENT_DECODER);
	msgz = soup_message_new_from_uri ("GET", uri);
	soup_session_send_message (session, msgz);
	check_response (msgz, "gzip", "text/plain", EXPECT_DECODED);
	check_msg_bodies (msg, msgz, "plain", "compressed");

	/* Plain text data, claim gzip w/ junk */
	debug_printf (1, "  GET /mbox, Accept-Encoding: gzip, plus trailing junk\n");
	msgj = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgj->request_headers,
				     "X-Test-Options", "trailing-junk");
	soup_session_send_message (session, msgj);
	check_response (msgj, "gzip", "text/plain", EXPECT_DECODED);
	check_msg_bodies (msg, msgj, "plain", "compressed w/ junk");

	/* Plain text data, claim gzip with server error */
	debug_printf (1, "  GET /mbox, Accept-Encoding: gzip, with server error\n");
	msge = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msge->request_headers,
				     "X-Test-Options", "force-encode");
	soup_session_send_message (session, msge);
	check_response (msge, "gzip", "text/plain", EXPECT_NOT_DECODED);

	/* Failed content-decoding should have left the body untouched
	 * from what the server sent... which happens to be the
	 * uncompressed data.
	 */
	check_msg_bodies (msg, msge, "plain", "mis-encoded");

	/* Plain text data, claim deflate */
	debug_printf (1, "  GET /mbox, Accept-Encoding: deflate\n");
	msgzl = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgzl->request_headers,
				     "X-Test-Options", "prefer-deflate-zlib");
	soup_session_send_message (session, msgzl);
	check_response (msgzl, "deflate", "text/plain", EXPECT_DECODED);
	check_msg_bodies (msg, msgzl, "plain", "compressed");

	/* Plain text data, claim deflate w/ junk */
	debug_printf (1, "  GET /mbox, Accept-Encoding: deflate, plus trailing junk\n");
	msgzlj = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgzlj->request_headers,
				     "X-Test-Options", "prefer-deflate-zlib, trailing-junk");
	soup_session_send_message (session, msgzlj);
	check_response (msgzlj, "deflate", "text/plain", EXPECT_DECODED);
	check_msg_bodies (msg, msgzlj, "plain", "compressed w/ junk");

	/* Plain text data, claim deflate with server error */
	debug_printf (1, "  GET /mbox, Accept-Encoding: deflate, with server error\n");
	msgzle = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgzle->request_headers,
				     "X-Test-Options", "force-encode, prefer-deflate-zlib");
	soup_session_send_message (session, msgzle);
	check_response (msgzle, "deflate", "text/plain", EXPECT_NOT_DECODED);
	check_msg_bodies (msg, msgzle, "plain", "mis-encoded");

	/* Plain text data, claim deflate (no zlib headers)*/
	debug_printf (1, "  GET /mbox, Accept-Encoding: deflate (raw data)\n");
	msgzlr = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgzlr->request_headers,
				     "X-Test-Options", "prefer-deflate-raw");
	soup_session_send_message (session, msgzlr);
	check_response (msgzlr, "deflate", "text/plain", EXPECT_DECODED);
	check_msg_bodies (msg, msgzlr, "plain", "compressed");

	/* Plain text data, claim deflate with server error */
	debug_printf (1, "  GET /mbox, Accept-Encoding: deflate (raw data), with server error\n");
	msgzlre = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgzlre->request_headers,
				     "X-Test-Options", "force-encode, prefer-deflate-raw");
	soup_session_send_message (session, msgzlre);
	check_response (msgzlre, "deflate", "text/plain", EXPECT_NOT_DECODED);
	check_msg_bodies (msg, msgzlre, "plain", "mis-encoded");

	g_object_unref (msg);
	g_object_unref (msgzlre);
	g_object_unref (msgzlr);
	g_object_unref (msgzlj);
	g_object_unref (msgzle);
	g_object_unref (msgzl);
	g_object_unref (msgz);
	g_object_unref (msgj);
	g_object_unref (msge);
	soup_uri_free (uri);

	soup_test_session_abort_unref (session);
}
コード例 #22
0
ファイル: cmd_result.c プロジェクト: gsr-shanks/restraint
int main(int argc, char *argv[]) {

    AppData *app_data = g_slice_new0 (AppData);
    app_data->filename = g_strdup("resultoutputfile.log");
    app_data->outputfile = g_strdup(getenv("OUTPUTFILE"));
    app_data->disable_plugin = g_ptr_array_new_with_free_func (g_free);

    GError *error = NULL;

    gchar *server = NULL;
    SoupURI *result_uri = NULL;

    guint ret = 0;

    SoupMessage *server_msg;
    SoupRequest *request;

    gchar *result_msg = NULL;
    gchar *prefix = NULL;
    gchar *server_recipe_key = NULL;
    gchar *server_recipe = NULL;
    gchar *task_id = NULL;
    gchar *task_id_key = NULL;
    gboolean no_plugins = FALSE;

    gchar *form_data;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    GOptionEntry entries[] = {
        {"server", 's', 0, G_OPTION_ARG_STRING, &server,
            "Server to connect to", "URL" },
        { "message", 't', 0, G_OPTION_ARG_STRING, &result_msg,
            "Short 100 characters or less message", "TEXT" },
        { "outputfile", 'o', 0, G_OPTION_ARG_CALLBACK, callback_outputfile,
            "Log to upload with result, $OUTPUTFILE is used by default", "FILE" },
        { "disable-plugin", 'p', 0, G_OPTION_ARG_CALLBACK, callback_disable_plugin,
            "don't run plugin on server side", "PLUGIN" },
        { "no-plugins", 0, 0, G_OPTION_ARG_NONE, &no_plugins,
            "don't run any plugins on server side", NULL },
        { NULL }
    };
    GOptionGroup *option_group = g_option_group_new ("main",
                                                    "Application Options",
                                                    "Various application related options",
                                                    app_data, NULL);

    GOptionContext *context = g_option_context_new("TASK_PATH RESULT SCORE");
    g_option_context_set_summary(context,
            "Report results to lab controller. if you don't specify the\n"
            "the server url you must have RECIPEID and TASKID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPEID and TASKID");
    g_option_group_add_entries(option_group, entries);
    g_option_context_set_main_group (context, option_group);

    gboolean parse_succeeded = g_option_context_parse(context, &argc, &argv, &error);

    if (!parse_succeeded) {
        goto cleanup;
    }

    prefix = getenv("HARNESS_PREFIX") ? getenv("HARNESS_PREFIX") : "";
    server_recipe_key = g_strdup_printf ("%sRECIPE_URL", prefix);
    server_recipe = getenv(server_recipe_key);
    task_id_key = g_strdup_printf ("%sTASKID", prefix);
    task_id = getenv(task_id_key);
    g_free(task_id_key);
    g_free(server_recipe_key);

    if (!server && server_recipe && task_id) {
        server = g_strdup_printf ("%s/tasks/%s/results/", server_recipe, task_id);
    }

    if (argc < 3 || !server) {
        cmd_usage(context);
        goto cleanup;
    }

    result_uri = soup_uri_new (server);
    if (result_uri == NULL) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Malformed server url: %s", server);
        goto cleanup;
    }
    session = soup_session_new_with_options("timeout", 3600, NULL);

    g_hash_table_insert (data_table, "path", argv[1]);
    g_hash_table_insert (data_table, "result", argv[2]);

    // if AVC_ERROR=+no_avc_check then disable the selinux check plugin
    // This is for legacy rhts tests.. please use --disable-plugin
    gchar *avc_error = getenv("AVC_ERROR");
    if (g_strcmp0 (avc_error, "+no_avc_check") == 0) {
        g_ptr_array_add (app_data->disable_plugin, g_strdup ("10_avc_check"));
    }

    if (app_data->disable_plugin->pdata) {
        g_hash_table_insert (data_table, "disable_plugin",
                             g_strjoinv (" ", (gchar **)app_data->disable_plugin->pdata));
    }
    if (no_plugins)
      g_hash_table_insert (data_table, "no_plugins", &no_plugins);
    if (argc > 3)
      g_hash_table_insert (data_table, "score", argv[3]);
    if (result_msg)
      g_hash_table_insert (data_table, "message", result_msg);

    request = (SoupRequest *)soup_session_request_http_uri (session, "POST", result_uri, &error);
    server_msg = soup_request_http_get_message (SOUP_REQUEST_HTTP (request));
    g_object_unref(request);
    form_data = soup_form_encode_hash (data_table);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));
    g_print ("** %s %s Score:%s\n", argv[1], argv[2], argv[3]);
    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
        gchar *location = g_strdup_printf ("%s/logs/",
                                           soup_message_headers_get_one (server_msg->response_headers, "Location"));
        soup_uri_free (result_uri);
        result_uri = soup_uri_new (location);
        g_free (location);
        if (app_data->outputfile != NULL &&
            g_file_test (app_data->outputfile, G_FILE_TEST_EXISTS))
        {
            g_print ("Uploading %s ", app_data->filename);
            if (upload_file (session, app_data->outputfile, app_data->filename, result_uri, &error)) {
                g_print ("done\n");
            } else {
                g_print ("failed\n");
            }
        }
    } else {
       g_warning ("Failed to submit result, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }
    g_object_unref(server_msg);
    soup_session_abort(session);
    g_object_unref(session);

cleanup:
    if (server != NULL) {
        g_free(server);
    }
    if (result_msg != NULL) {
        g_free(result_msg);
    }
    g_option_context_free(context);
    g_hash_table_destroy(data_table);
    if (result_uri != NULL) {
        soup_uri_free (result_uri);
    }
    restraint_free_appdata(app_data);
    if (error) {
        int retcode = error->code;
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        g_clear_error(&error);
        return retcode;
    } else {
        return EXIT_SUCCESS;
    }
}
コード例 #23
0
ファイル: auth-test.c プロジェクト: Conservatory/quark
static void
select_auth_test_one (SoupURI *uri,
		      gboolean disable_digest, const char *password,
		      const char *first_headers, const char *first_response,
		      const char *second_headers, const char *second_response,
		      guint final_status)
{
	SelectAuthData sad;
	SoupMessage *msg;
	SoupSession *session;

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	if (disable_digest)
		soup_session_remove_feature_by_type (session, SOUP_TYPE_AUTH_DIGEST);

	g_signal_connect (session, "authenticate",
			  G_CALLBACK (select_auth_authenticate), &sad);
	memset (&sad, 0, sizeof (sad));
	sad.password = password;

	msg = soup_message_new_from_uri ("GET", uri);
	soup_session_send_message (session, msg);

	if (strcmp (sad.round[0].headers, first_headers) != 0) {
		debug_printf (1, "    Header order wrong: expected %s, got %s\n",
			      first_headers, sad.round[0].headers);
		errors++;
	}
	if (strcmp (sad.round[0].response, first_response) != 0) {
		debug_printf (1, "    Selected auth type wrong: expected %s, got %s\n",
			      first_response, sad.round[0].response);
		errors++;
	}

	if (second_headers && !sad.round[1].headers) {
		debug_printf (1, "    Expected a second round!\n");
		errors++;
	} else if (!second_headers && sad.round[1].headers) {
		debug_printf (1, "    Didn't expect a second round!\n");
		errors++;
	} else if (second_headers) {
		if (strcmp (sad.round[1].headers, second_headers) != 0) {
			debug_printf (1, "    Second round header order wrong: expected %s, got %s\n",
				      second_headers, sad.round[1].headers);
			errors++;
		}
		if (strcmp (sad.round[1].response, second_response) != 0) {
			debug_printf (1, "    Second round selected auth type wrong: expected %s, got %s\n",
				      second_response, sad.round[1].response);
			errors++;
		}
	}

	if (msg->status_code != final_status) {
		debug_printf (1, "    Final status wrong: expected %u, got %u\n",
			      final_status, msg->status_code);
		errors++;
	}

	g_object_unref (msg);
	soup_test_session_abort_unref (session);
}
コード例 #24
0
int main(int argc, char *argv[])
{
    char packet[] = {0x00, 0x00, 0x00};

    float temp, hum;

    int error_count = 0;

    int count = 1;

    GError *error = NULL;
    GOptionContext *context;

    context = g_option_context_new ("- collect temperature and humidity readings");
    g_option_context_add_main_entries (context, entries, NULL);
    if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_print ("option parsing failed: %s\n", error->message);
      exit (1);
    }
    g_option_context_free(context);
    set_debug(debug);
    hid_device *handle;
    gboolean found = search_for_device();

    if(!found) {
        g_printerr("Sensor not found, aborting.\n");
        exit(-1);
    }
    
    // Open the device using the VID and PID
    handle = open_lascar();
    if(handle == NULL) {
      g_printerr("Error opening sensor.\n");
      exit(-1);
    }
    
    SoupSession *session = NULL;
    int channel;
    gchar *channel_name;
    gchar *room;
    GString *uri, *body;
    
    /* parse config file */
    GKeyFile *gkf = g_key_file_new();
    g_key_file_load_from_data_dirs(gkf,"templogger.conf",NULL,G_KEY_FILE_NONE,&error);
    if(error!=NULL) {
        g_printerr("Can't load configuration file, not uploading to server.\n");
        g_key_file_free(gkf);
    }
    else {
      gchar *url = g_key_file_get_string(gkf,"influx","url",NULL);
      channel = g_key_file_get_integer(gkf,"channel","channel_num",NULL);
      channel_name = g_key_file_get_string(gkf,"channel","channel_name",NULL);
      room = g_key_file_get_string(gkf,"channel","room",NULL);
      int port = g_key_file_get_integer(gkf,"influx","port",NULL);
      gchar *db = g_key_file_get_string(gkf,"influx","database",NULL);
      gchar *username = g_key_file_get_string(gkf,"influx","username",NULL);
      gchar *password = g_key_file_get_string(gkf,"influx","password",NULL);
      g_key_file_free(gkf);
    
      /* open session */
    
      session = soup_session_new();
      uri = g_string_new("http://");
      g_string_append_printf(uri,"%s:%d/write?db=%s&u=%s&p=%s",url,port,db,username,password);

      g_message(uri->str);
      body = g_string_new("");
	  g_print("Uploading as channel %d, name %s, room %s",channel, channel_name, room);
    }
    
    FILE *logfile = NULL;
    if(log_local) {
        logfile = fopen("log.txt","a");
    }
    
    const int upload_freq = floor(UPLOAD_TIME/SLEEP_TIME);
    
    while(1) {
        int ret = get_reading(handle, packet, &temp, &hum, TRUE);
        if(ret >= 0) {
            gint64 t = 1000*g_get_real_time();
            
            if(log_local) {
              fprintf(logfile,"%" G_GINT64_FORMAT "\t%.1f\t%.1f\n",t, temp, hum);
              fflush(logfile);
            }
            
            if(debug)
              g_print("%" G_GINT64_FORMAT "\t%.1f\t%.1f\n",t, temp, hum);
            
            if(session && (count % upload_freq == 0)) {
            SoupRequestHTTP *request = soup_session_request_http(session,"POST",uri->str,NULL);
            SoupMessage *message = soup_request_http_get_message(request);
            g_string_append_printf(body,"temp,channel=%d,channel_name=%s,room=%s",channel,channel_name,room);
            g_string_append_printf(body," value=%.1f %" G_GINT64_FORMAT,temp,t);
            g_string_append_printf(body,"\n");
            g_string_append_printf(body,"hum,channel=%d,channel_name=%s,room=%s",channel,channel_name,room);
            g_string_append_printf(body," value=%.1f %" G_GINT64_FORMAT,hum,t);
            g_string_append_printf(body,"\n");
            
            if(debug)
              g_message(body->str);
            
            if(!testing) {
                soup_message_set_request(message,"application/binary",SOUP_MEMORY_COPY,body->str,body->len);
                guint session_status = soup_session_send_message(session,message);
                if(session_status == 204) { /* message was received */
                    //g_print("received status %d\n",session_status);
                    g_string_erase(body,0,-1); /* clear the string */
                }
                else {
                  g_print("no connection to server");
                }
                /* otherwise, keep it and attempt to resend next time */
            }
            g_object_unref(message);
            }
            count ++;

            /* reset the error count on successful read */
            error_count = 0;
        } else if(error_count > MAX_ERRORS) {
            g_printerr("Too many errors to continue\n");
            exit(-1);
        } else {
            error_count++;
        }
        if(testing && count>60)
          break;
        g_usleep(SLEEP_TIME*1000000);
    }
    if(session) {
      g_string_free(uri,TRUE);
      g_string_free(body,TRUE);
      g_object_unref(session);
    }
    hid_close(handle);
    hid_exit();
    
    return 0;
}
コード例 #25
0
ファイル: grits-http.c プロジェクト: adamboggs/grits
/* TODO: use .part extentions and continue even when using GRITS_ONCE */
gchar *grits_http_fetch(GritsHttp *http, const gchar *uri, const char *local,
		GritsCacheType mode, GritsChunkCallback callback, gpointer user_data)
{
	g_debug("GritsHttp: fetch - %s mode=%d", local, mode);
	gchar *path = _get_cache_path(http, local);

	/* Unlink the file if we're refreshing it */
	if (mode == GRITS_REFRESH)
		g_remove(path);

	/* Do the cache if necessasairy */
	if (!(mode == GRITS_ONCE && g_file_test(path, G_FILE_TEST_EXISTS)) &&
			mode != GRITS_LOCAL) {
		g_debug("GritsHttp: fetch - Caching file %s", local);

		/* Open the file for writting */
		gchar *part = path;
		if (!g_file_test(path, G_FILE_TEST_EXISTS))
			part = g_strdup_printf("%s.part", path);
		FILE *fp = fopen_p(part, "ab");
		if (!fp) {
			g_warning("GritsHttp: fetch - error opening %s", path);
			return NULL;
		}
		fseek(fp, 0, SEEK_END); // "a" is broken on Windows, twice

		/* Make temp data */
		struct _CacheInfo info = {
			.fp        = fp,
			.path      = path,
			.callback  = callback,
			.user_data = user_data,
		};

		/* Download the file */
		SoupMessage *message = soup_message_new("GET", uri);
		if (message == NULL)
			g_error("message is null, cannot parse uri");
		g_signal_connect(message, "got-chunk", G_CALLBACK(_chunk_cb), &info);
		//if (ftell(fp) > 0)
			soup_message_headers_set_range(message->request_headers, ftell(fp), -1);
		if (mode == GRITS_REFRESH)
			soup_message_headers_replace(message->request_headers,
					"Cache-Control", "max-age=0");
		soup_session_send_message(http->soup, message);

		/* Close file */
		fclose(fp);
		if (path != part) {
			if (SOUP_STATUS_IS_SUCCESSFUL(message->status_code))
				g_rename(part, path);
			g_free(part);
		}

		/* Finished */
		guint status = message->status_code;
		g_object_unref(message);
		if (status == SOUP_STATUS_CANCELLED) {
			return NULL;
		} else if (status == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE) {
			/* Range unsatisfiable, file already complete */
		} else if (!SOUP_STATUS_IS_SUCCESSFUL(status)) {
			g_warning("GritsHttp: done_cb - error copying file, status=%d\n"
					"\tsrc=%s\n"
					"\tdst=%s",
					status, uri, path);
			return NULL;
		}
	}
コード例 #26
0
ファイル: get.c プロジェクト: Distrotech/libsoup
static void
get_url (const char *url)
{
	const char *name;
	SoupMessage *msg;
	const char *header;
	FILE *output_file = NULL;

	msg = soup_message_new (head ? "HEAD" : "GET", url);
	soup_message_set_flags (msg, SOUP_MESSAGE_NO_REDIRECT);

	if (loop) {
		g_object_ref (msg);
		soup_session_queue_message (session, msg, finished, loop);
		g_main_loop_run (loop);
	} else
		soup_session_send_message (session, msg);

	name = soup_message_get_uri (msg)->path;

	if (!debug) {
		if (msg->status_code == SOUP_STATUS_SSL_FAILED) {
			GTlsCertificateFlags flags;

			if (soup_message_get_https_status (msg, NULL, &flags))
				g_print ("%s: %d %s (0x%x)\n", name, msg->status_code, msg->reason_phrase, flags);
			else
				g_print ("%s: %d %s (no handshake status)\n", name, msg->status_code, msg->reason_phrase);
		} else if (!quiet || SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code))
			g_print ("%s: %d %s\n", name, msg->status_code, msg->reason_phrase);
	}

	if (SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
		header = soup_message_headers_get_one (msg->response_headers,
						       "Location");
		if (header) {
			SoupURI *uri;
			char *uri_string;

			if (!debug && !quiet)
				g_print ("  -> %s\n", header);

			uri = soup_uri_new_with_base (soup_message_get_uri (msg), header);
			uri_string = soup_uri_to_string (uri, FALSE);
			get_url (uri_string);
			g_free (uri_string);
			soup_uri_free (uri);
		}
	} else if (!head && SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		if (output_file_path) {
			output_file = fopen (output_file_path, "w");
			if (!output_file)
				g_printerr ("Error trying to create file %s.\n", output_file_path);
		} else if (!quiet)
			output_file = stdout;

		if (output_file) {
			fwrite (msg->response_body->data,
				1,
				msg->response_body->length,
				output_file);

			if (output_file_path)
				fclose (output_file);
		}
	}
}
コード例 #27
0
static void
do_request_test (SoupSession *session, SoupURI *base_uri, RequestTestFlags flags)
{
	SoupURI *uri = base_uri;
	PutTestData ptd;
	SoupMessage *msg;
	const char *client_md5, *server_md5;
	GChecksum *check;
	int i, length;

	debug_printf (1, "PUT");
	if (flags & HACKY_STREAMING)
		debug_printf (1, " w/ hacky streaming");
	else if (flags & PROPER_STREAMING)
		debug_printf (1, " w/ proper streaming");
	if (flags & RESTART) {
		debug_printf (1, " and restart");
		uri = soup_uri_copy (base_uri);
		soup_uri_set_path (uri, "/redirect");
	}
	debug_printf (1, "\n");

	ptd.session = session;
	setup_request_body (&ptd);
	ptd.streaming = flags & (HACKY_STREAMING | PROPER_STREAMING);

	check = g_checksum_new (G_CHECKSUM_MD5);
	length = 0;
	for (i = 0; i < 3; i++) {
		g_checksum_update (check, (guchar *)ptd.chunks[i]->data,
				   ptd.chunks[i]->length);
		length += ptd.chunks[i]->length;
	}
	client_md5 = g_checksum_get_string (check);

	msg = soup_message_new_from_uri ("PUT", uri);
	soup_message_headers_set_encoding (msg->request_headers, SOUP_ENCODING_CHUNKED);
	soup_message_body_set_accumulate (msg->request_body, FALSE);
	soup_message_set_chunk_allocator (msg, error_chunk_allocator, NULL, NULL);
	if (flags & HACKY_STREAMING) {
		g_signal_connect (msg, "wrote_chunk",
				  G_CALLBACK (write_next_chunk_streaming_hack), &ptd);
		if (flags & RESTART) {
			g_signal_connect (msg, "restarted",
					  G_CALLBACK (restarted_streaming_hack), &ptd);
		}
	} else {
		g_signal_connect (msg, "wrote_chunk",
				  G_CALLBACK (write_next_chunk), &ptd);
	}

	if (flags & PROPER_STREAMING) {
		soup_message_set_flags (msg, SOUP_MESSAGE_CAN_REBUILD);
		if (flags & RESTART) {
			g_signal_connect (msg, "restarted",
					  G_CALLBACK (restarted_streaming), &ptd);
		}
	}

	g_signal_connect (msg, "wrote_headers",
			  G_CALLBACK (write_next_chunk), &ptd);
	g_signal_connect (msg, "wrote_body_data",
			  G_CALLBACK (wrote_body_data), &ptd);
	soup_session_send_message (session, msg);

	if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		debug_printf (1, "  message failed: %d %s\n",
			      msg->status_code, msg->reason_phrase);
		errors++;
	}

	if (msg->request_body->data) {
		debug_printf (1, "  msg->request_body set!\n");
		errors++;
	}
	if (msg->request_body->length != length || length != ptd.nwrote) {
		debug_printf (1, "  sent length mismatch: %d vs %d vs %d\n",
			      (int)msg->request_body->length, length, ptd.nwrote);
		errors++;
	}

	server_md5 = soup_message_headers_get_one (msg->response_headers,
						   "Content-MD5");
	if (!server_md5 || strcmp (client_md5, server_md5) != 0) {
		debug_printf (1, "  client/server data mismatch: %s vs %s\n",
			      client_md5, server_md5 ? server_md5 : "(null)");
		errors++;
	}

	g_object_unref (msg);
	g_checksum_free (check);

	if (uri != base_uri)
		soup_uri_free (uri);
}
コード例 #28
0
/**
 * gupnp_service_info_get_introspection:
 * @info: A #GUPnPServiceInfo
 * @error: return location for a #GError, or %NULL
 *
 * Note that introspection object is created from the information in service
 * description document (SCPD) provided by the service so it can not be created
 * if the service does not provide an SCPD.
 *
 * Warning: You  should use gupnp_service_info_get_introspection_async()
 * instead, this function re-enter the GMainloop before returning or might
 * even block.
 *
 * Return value: (transfer full):  A new #GUPnPServiceIntrospection for this
 * service or %NULL. Unref after use.
 *
 * Deprecated: 0.20.15. Use gupnp_service_info_get_introspection_async() or
 * gupnp_service_info_get_introspection_async_full() instead.
 **/
G_DEPRECATED GUPnPServiceIntrospection *
gupnp_service_info_get_introspection (GUPnPServiceInfo *info,
                                      GError          **error)
{
        GUPnPServiceIntrospection *introspection;
        SoupSession *session;
        SoupMessage *msg;
        int status;
        char *scpd_url;
        xmlDoc *scpd;

        g_return_val_if_fail (GUPNP_IS_SERVICE_INFO (info), NULL);

        introspection = NULL;

        scpd_url = gupnp_service_info_get_scpd_url (info);

        msg = NULL;
        if (scpd_url != NULL) {
                msg = soup_message_new (SOUP_METHOD_GET, scpd_url);

                g_free (scpd_url);
        }

        if (msg == NULL) {
                g_set_error (error,
                             GUPNP_SERVER_ERROR,
                             GUPNP_SERVER_ERROR_INVALID_URL,
                             "No valid SCPD URL defined");

                return NULL;
        }

        /* Send off the message */
        session = gupnp_context_get_session (info->priv->context);

        status = soup_session_send_message (session, msg);
        if (!SOUP_STATUS_IS_SUCCESSFUL (status)) {
                _gupnp_error_set_server_error (error, msg);

                g_object_unref (msg);

                return NULL;
        }

        scpd = xmlRecoverMemory (msg->response_body->data,
                                 msg->response_body->length);

        g_object_unref (msg);

        if (scpd) {
                introspection = gupnp_service_introspection_new (scpd);

                xmlFreeDoc (scpd);
        }

        if (!introspection) {
                g_set_error (error,
                             GUPNP_SERVER_ERROR,
                             GUPNP_SERVER_ERROR_INVALID_RESPONSE,
                             "Could not parse SCPD");
        }

        return introspection;
}
コード例 #29
0
gboolean
gs_plugin_add_unvoted_reviews (GsPlugin *plugin,
			       GsAppList *list,
			       GCancellable *cancellable,
			       GError **error)
{
	GsPluginData *priv = gs_plugin_get_data (plugin);
	guint status_code;
	guint i;
	g_autofree gchar *uri = NULL;
	g_autoptr(GHashTable) hash = NULL;
	g_autoptr(GPtrArray) reviews = NULL;
	g_autoptr(SoupMessage) msg = NULL;

	/* create the GET data *with* the machine hash so we can later
	 * review the application ourselves */
	uri = g_strdup_printf ("%s/moderate/%s/%s",
			       priv->review_server,
			       priv->user_hash,
			       gs_plugin_get_locale (plugin));
	msg = soup_message_new (SOUP_METHOD_GET, uri);
	status_code = soup_session_send_message (gs_plugin_get_soup_session (plugin), msg);
	if (status_code != SOUP_STATUS_OK) {
		if (!gs_plugin_odrs_parse_success (msg->response_body->data,
						   msg->response_body->length,
						   error))
			return FALSE;
		/* not sure what to do here */
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_DOWNLOAD_FAILED,
				     "status code invalid");
		gs_utils_error_add_unique_id (error, priv->cached_origin);
		return FALSE;
	}
	g_debug ("odrs returned: %s", msg->response_body->data);
	reviews = gs_plugin_odrs_parse_reviews (plugin,
						msg->response_body->data,
						msg->response_body->length,
						error);
	if (reviews == NULL)
		return FALSE;

	/* look at all the reviews; faking application objects */
	hash = g_hash_table_new_full (g_str_hash, g_str_equal,
				      g_free, (GDestroyNotify) g_object_unref);
	for (i = 0; i < reviews->len; i++) {
		GsApp *app;
		AsReview *review;
		const gchar *app_id;

		/* same app? */
		review = g_ptr_array_index (reviews, i);
		app_id = as_review_get_metadata_item (review, "app_id");
		app = g_hash_table_lookup (hash, app_id);
		if (app == NULL) {
			app = gs_plugin_create_app_dummy (app_id);
			gs_app_list_add (list, app);
			g_hash_table_insert (hash, g_strdup (app_id), app);
		}
		gs_app_add_review (app, review);
	}

	return TRUE;
}
コード例 #30
0
ファイル: coding-test.c プロジェクト: ChingezKhan/libsoup
static void
do_coding_test (void)
{
	SoupSession *session;
	SoupMessage *msg, *msgz, *msgj;
	SoupURI *uri;
	const char *coding;

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	uri = soup_uri_new_with_base (base_uri, "/mbox");

	debug_printf (1, "GET /mbox, plain\n");
	msg = soup_message_new_from_uri ("GET", uri);
	soup_session_send_message (session, msg);
	if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		debug_printf (1, "  Unexpected status %d %s\n",
			      msg->status_code, msg->reason_phrase);
		errors++;
	}
	coding = soup_message_headers_get_one (msg->response_headers, "Content-Encoding");
	if (coding) {
		debug_printf (1, "  Unexpected Content-Encoding: %s\n",
			      coding);
		errors++;
	}
	if (soup_message_get_flags (msg) & SOUP_MESSAGE_CONTENT_DECODED) {
		debug_printf (1, "  SOUP_MESSAGE_CONTENT_DECODED set!\n");
		errors++;
	}

	debug_printf (1, "GET /mbox, Accept-Encoding: gzip\n");
	soup_session_add_feature_by_type (session, SOUP_TYPE_CONTENT_DECODER);
	msgz = soup_message_new_from_uri ("GET", uri);
	soup_session_send_message (session, msgz);
	if (!SOUP_STATUS_IS_SUCCESSFUL (msgz->status_code)) {
		debug_printf (1, "  Unexpected status %d %s\n",
			      msgz->status_code, msgz->reason_phrase);
		errors++;
	}
	coding = soup_message_headers_get_one (msgz->response_headers, "Content-Encoding");
	if (!coding || g_ascii_strcasecmp (coding, "gzip") != 0) {
		debug_printf (1, "  Unexpected Content-Encoding: %s\n",
			      coding ? coding : "(none)");
		errors++;
	}
	if (!(soup_message_get_flags (msgz) & SOUP_MESSAGE_CONTENT_DECODED)) {
		debug_printf (1, "  SOUP_MESSAGE_CONTENT_DECODED not set!\n");
		errors++;
	}

	if (msg->response_body->length != msgz->response_body->length) {
		debug_printf (1, "  Message length mismatch: %lu (plain) vs %lu (compressed)\n",
			      (gulong)msg->response_body->length,
			      (gulong)msgz->response_body->length);
		errors++;
	} else if (memcmp (msg->response_body->data,
			   msgz->response_body->data,
			   msg->response_body->length) != 0) {
		debug_printf (1, "  Message data mismatch (plain/compressed)\n");
		errors++;
	}

	debug_printf (1, "GET /mbox, Accept-Encoding: gzip, plus trailing junk\n");
	msgj = soup_message_new_from_uri ("GET", uri);
	soup_message_headers_append (msgj->request_headers,
				     "X-Trailing-Junk", "junk!");
	soup_session_send_message (session, msgj);
	if (!SOUP_STATUS_IS_SUCCESSFUL (msgj->status_code)) {
		debug_printf (1, "  Unexpected status %d %s\n",
			      msgj->status_code, msgj->reason_phrase);
		errors++;
	}
	coding = soup_message_headers_get_one (msgj->response_headers, "Content-Encoding");
	if (!coding || g_ascii_strcasecmp (coding, "gzip") != 0) {
		debug_printf (1, "  Unexpected Content-Encoding: %s\n",
			      coding ? coding : "(none)");
		errors++;
	}
	if (!(soup_message_get_flags (msgj) & SOUP_MESSAGE_CONTENT_DECODED)) {
		debug_printf (1, "  SOUP_MESSAGE_CONTENT_DECODED not set!\n");
		errors++;
	}

	if (msg->response_body->length != msgj->response_body->length) {
		debug_printf (1, "  Message length mismatch: %lu (plain) vs %lu (compressed w/ junk)\n",
			      (gulong)msg->response_body->length,
			      (gulong)msgj->response_body->length);
		errors++;
	} else if (memcmp (msg->response_body->data,
			   msgj->response_body->data,
			   msg->response_body->length) != 0) {
		debug_printf (1, "  Message data mismatch (plain/compressed w/ junk)\n");
		errors++;
	}

	g_object_unref (msg);
	g_object_unref (msgz);
	g_object_unref (msgj);
	soup_uri_free (uri);

	soup_test_session_abort_unref (session);
}