Beispiel #1
0
static gboolean
gs_plugin_odrs_json_post (SoupSession *session,
			  const gchar *uri,
			  const gchar *data,
			  GError **error)
{
	guint status_code;
	g_autoptr(SoupMessage) msg = NULL;

	/* create the GET data */
	g_debug ("odrs sending: %s", data);
	msg = soup_message_new (SOUP_METHOD_POST, uri);
	soup_message_set_request (msg, "application/json; charset=utf-8",
				  SOUP_MEMORY_COPY, data, strlen (data));

	/* set sync request */
	status_code = soup_session_send_message (session, msg);
	if (status_code != SOUP_STATUS_OK) {
		g_warning ("Failed to set rating on odrs: %s",
			   soup_status_get_phrase (status_code));
	}

	/* process returned JSON */
	g_debug ("odrs returned: %s", msg->response_body->data);
	return gs_plugin_odrs_parse_success (msg->response_body->data,
					     msg->response_body->length,
					     error);
}
Beispiel #2
0
static void
do_message_to_session (SoupSession *session, const char *uri,
		       const char *comment, guint expected_status)
{
	SoupMessage *msg;

	debug_printf (1, "    %s\n", comment);
	msg = soup_message_new ("GET", uri);
	soup_session_send_message (session, msg);

	if (msg->status_code != expected_status) {
		debug_printf (1, "      FAILED: %d %s (expected %d %s)\n",
			      msg->status_code, msg->reason_phrase,
			      expected_status,
			      soup_status_get_phrase (expected_status));
		errors++;
	}

	if (SOUP_STATUS_IS_SUCCESSFUL (msg->status_code) &&
	    !soup_message_is_keepalive (msg)) {
		debug_printf (1, "      ERROR: message is not keepalive!");
		errors++;
	}

	g_object_unref (msg);
}
Beispiel #3
0
static void
parse_error (guint status,
             const gchar *reason,
             const gchar *response,
             GSimpleAsyncResult *result)
{
  if (!response || *response == '\0')
    response = reason;

  switch (status) {
  case SOUP_STATUS_CANT_RESOLVE:
  case SOUP_STATUS_CANT_CONNECT:
  case SOUP_STATUS_SSL_FAILED:
  case SOUP_STATUS_IO_ERROR:
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_NETWORK_ERROR,
                                     _("Cannot connect to the server"));
    return;
  case SOUP_STATUS_CANT_RESOLVE_PROXY:
  case SOUP_STATUS_CANT_CONNECT_PROXY:
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_PROXY_ERROR,
                                     _("Cannot connect to the proxy server"));
    return;
  case SOUP_STATUS_INTERNAL_SERVER_ERROR: /* 500 */
  case SOUP_STATUS_MALFORMED:
  case SOUP_STATUS_BAD_REQUEST: /* 400 */
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_PROTOCOL_ERROR,
                                     _("Invalid request URI or header: %s"),
                                     response);
    return;
  case SOUP_STATUS_UNAUTHORIZED: /* 401 */
  case SOUP_STATUS_FORBIDDEN: /* 403 */
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_AUTHENTICATION_REQUIRED,
                                     _("Authentication required: %s"), response);
    return;
  case SOUP_STATUS_NOT_FOUND: /* 404 */
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_NOT_FOUND,
                                     _("The requested resource was not found: %s"),
                                     response);
    return;
  case SOUP_STATUS_CONFLICT: /* 409 */
  case SOUP_STATUS_PRECONDITION_FAILED: /* 412 */
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_CONFLICT,
                                     _("The entry has been modified since it was downloaded: %s"),
                                     response);
    return;
  case SOUP_STATUS_CANCELLED:
    g_simple_async_result_set_error (result, GRL_NET_WC_ERROR,
                                     GRL_NET_WC_ERROR_CANCELLED,
                                     _("Operation was cancelled"));
    return;
  default:
    g_message (_("Unhandled status: %s"), soup_status_get_phrase (status));
  }
}
Beispiel #4
0
static void
do_tests_for_session (SoupSession *session,
		      char *fast_uri, char *slow_uri)
{
	SoupMessage *msg;

	debug_printf (1, "    fast\n");
	msg = soup_message_new ("GET", fast_uri);
	soup_session_send_message (session, msg);
	if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		debug_printf (1, "      FAILED: %d %s (expected 200 OK)\n",
			      msg->status_code, msg->reason_phrase);
		errors++;
	}
	g_object_unref (msg);

	debug_printf (1, "    slow\n");
	msg = soup_message_new ("GET", slow_uri);
	soup_session_send_message (session, msg);
	if (msg->status_code != SOUP_STATUS_IO_ERROR) {
		debug_printf (1, "      FAILED: %d %s (expected %d %s)\n",
			      msg->status_code, msg->reason_phrase,
			      SOUP_STATUS_IO_ERROR,
			      soup_status_get_phrase (SOUP_STATUS_IO_ERROR));
		errors++;
	}
	g_object_unref (msg);
}
Beispiel #5
0
static void
_oauth_service_get_access_token_ready_cb (SoupSession *session,
					  SoupMessage *msg,
					  gpointer     user_data)
{
	OAuthService       *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;

	result = _web_service_get_result (WEB_SERVICE (self));

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	self->priv->consumer->access_token_response (self, msg, body, result);
	g_simple_async_result_complete_in_idle (result);

	soup_buffer_free (body);
}
Beispiel #6
0
static void
gdav_propfind_request_cb (GObject *source_object,
                          GAsyncResult *result,
                          gpointer user_data)
{
	SoupRequestHTTP *request;
	GTask *task = G_TASK (user_data);
	SoupURI *base_uri;
	gpointer parsable;
	guint status_code;
	AsyncContext *async_context;
	GError *local_error = NULL;

	request = SOUP_REQUEST_HTTP (source_object);
	async_context = g_task_get_task_data (task);
	status_code = async_context->message->status_code;

	gdav_request_send_finish (request, result, &local_error);

	if (local_error != NULL)
		goto exit;

	if (status_code != SOUP_STATUS_MULTI_STATUS) {
		g_task_return_new_error (
			task, GDAV_PARSABLE_ERROR,
			GDAV_PARSABLE_ERROR_INTERNAL,
			_("Expected status %u (%s), but got (%u) (%s)"),
			SOUP_STATUS_MULTI_STATUS,
			soup_status_get_phrase (SOUP_STATUS_MULTI_STATUS),
			async_context->message->status_code,
			async_context->message->reason_phrase);
		goto exit;
	}

	base_uri = soup_message_get_uri (async_context->message);

	parsable = gdav_parsable_new_from_data (
		GDAV_TYPE_MULTI_STATUS, base_uri,
		async_context->message->response_body->data,
		async_context->message->response_body->length,
		&local_error);

	/* Sanity check */
	g_warn_if_fail (
		((parsable != NULL) && (local_error == NULL)) ||
		((parsable == NULL) && (local_error != NULL)));

	if (parsable != NULL) {
		g_warn_if_fail (GDAV_IS_MULTI_STATUS (parsable));
		g_task_return_pointer (task, parsable, g_object_unref);
	}

exit:
	if (local_error != NULL)
		g_task_return_error (task, local_error);

	g_object_unref (task);
}
Beispiel #7
0
static void
get_user_info_ready_cb (SoupSession *session,
			SoupMessage *msg,
			gpointer     user_data)
{
	FacebookService      *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc = NULL;
	GError             *error = NULL;

	result = facebook_connection_get_result (self->priv->conn);

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	if (facebook_utils_parse_response (body, &doc, &error)) {
		DomElement   *node;
		FacebookUser *user = NULL;

		for (node = DOM_ELEMENT (doc)->first_child; node; node = node->next_sibling) {
			if (g_strcmp0 (node->tag_name, "users_getInfo_response") == 0) {
				DomElement *child;

				for (child = node->first_child; child; child = child->next_sibling) {
					if (g_strcmp0 (child->tag_name, "user") == 0) {
						user = facebook_user_new ();
						dom_domizable_load_from_element (DOM_DOMIZABLE (user), child);
						g_simple_async_result_set_op_res_gpointer (result, user, (GDestroyNotify) g_object_unref);
					}
				}
			}
		}

		if (user == NULL) {
			error = g_error_new_literal (FACEBOOK_CONNECTION_ERROR, 0, _("Unknown error"));
			g_simple_async_result_set_from_error (result, error);
		}

		g_object_unref (doc);
	}
	else
		g_simple_async_result_set_from_error (result, error);

	g_simple_async_result_complete_in_idle (result);

	soup_buffer_free (body);
}
Beispiel #8
0
static void
get_albums_ready_cb (SoupSession *session,
		     SoupMessage *msg,
		     gpointer     user_data)
{
	FacebookService    *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc = NULL;
	GError             *error = NULL;

	result = facebook_connection_get_result (self->priv->conn);

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	if (facebook_utils_parse_response (body, &doc, &error)) {
		DomElement *node;
		GList      *albums = NULL;

		for (node = DOM_ELEMENT (doc)->first_child; node; node = node->next_sibling) {
			if (g_strcmp0 (node->tag_name, "photos_getAlbums_response") == 0) {
				DomElement *child;

				for (child = node->first_child; child; child = child->next_sibling) {
					if (g_strcmp0 (child->tag_name, "album") == 0) {
						FacebookAlbum *album;

						album = facebook_album_new ();
						dom_domizable_load_from_element (DOM_DOMIZABLE (album), child);
						albums = g_list_prepend (albums, album);
					}
				}
			}
		}

		albums = g_list_reverse (albums);
		g_simple_async_result_set_op_res_gpointer (result, albums, (GDestroyNotify) _g_object_list_unref);

		g_object_unref (doc);
	}
	else
		g_simple_async_result_set_from_error (result, error);

	g_simple_async_result_complete_in_idle (result);

	soup_buffer_free (body);
}
Beispiel #9
0
static void
upload_photo_ready_cb (SoupSession *session,
		       SoupMessage *msg,
		       gpointer     user_data)
{
	FacebookService *self = user_data;
	SoupBuffer    *body;
	DomDocument   *doc = NULL;
	GError        *error = NULL;
	GthFileData   *file_data;

	if (msg->status_code != 200) {
		GError *error;

		error = g_error_new_literal (SOUP_HTTP_ERROR, msg->status_code, soup_status_get_phrase (msg->status_code));
		upload_photos_done (self, error);
		g_error_free (error);

		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	if (facebook_utils_parse_response (body, &doc, &error)) {
		DomElement *node;

		/* save the photo id */

		for (node = DOM_ELEMENT (doc)->first_child; node; node = node->next_sibling) {
			if (g_strcmp0 (node->tag_name, "pid") == 0) {
				const char *id;

				id = dom_element_get_inner_text (node);
				self->priv->post_photos->ids = g_list_prepend (self->priv->post_photos->ids, g_strdup (id));
			}
		}

		g_object_unref (doc);
	}
	else {
		soup_buffer_free (body);
		upload_photos_done (self, error);
		return;
	}

	soup_buffer_free (body);

	file_data = self->priv->post_photos->current->data;
	self->priv->post_photos->uploaded_size += g_file_info_get_size (file_data->info);
	self->priv->post_photos->current = self->priv->post_photos->current->next;
	facebook_service_upload_current_file (self);
}
Beispiel #10
0
static void taskThread(GTask * task, gpointer source,
                       gpointer taskData, GCancellable * cancellable)
{
    TaskData *td = taskData;
    gchar *q = g_uri_escape_string(td->src, NULL, TRUE);
    gchar *target = g_strdup_printf(TARGET_URL,
                                    wl_dict_lang_get_phrase(td->from),
                                    wl_dict_lang_get_phrase(td->to), q);
    g_free(q);
    SoupMessage *msg = soup_message_new("GET", target);

    if (msg == NULL) {
        GError *error = g_error_new(G_IO_ERROR, 2,
                                    "failed to parse URL %s", target);
        g_free(target);
        g_task_return_error(task, error);
        return;
    }
    g_free(target);

    static SoupSession *session = NULL;
    if (session == NULL) {
        session = soup_session_new();
    }

    if (g_task_return_error_if_cancelled(task)) {
        g_object_unref(msg);
        return;
    }

    guint status = soup_session_send_message(session, msg);
    if (!SOUP_STATUS_IS_SUCCESSFUL(status)) {
        g_object_unref(msg);
        g_task_return_new_error(task, G_IO_ERROR, status,
                                "%s", soup_status_get_phrase(status));
        return;
    }

    if (g_task_return_error_if_cancelled(task)) {
        g_object_unref(msg);
        return;
    }

    SoupMessageBody *body = NULL;
    g_object_get(msg, "response-body", &body, NULL);
    gchar *responseBody = g_strdup(body->data);
    g_object_unref(msg);
    g_task_return_pointer(task, responseBody, g_free);
}
Beispiel #11
0
static gboolean
picasa_web_utils_parse_json_response (SoupMessage  *msg,
				      JsonNode    **node,
				      GError      **error)
{
	JsonParser *parser;
	SoupBuffer *body;

	g_return_val_if_fail (msg != NULL, FALSE);
	g_return_val_if_fail (node != NULL, FALSE);

	*node = NULL;

	if ((msg->status_code != 200) && (msg->status_code != 400)) {
		*error = g_error_new (SOUP_HTTP_ERROR,
				      msg->status_code,
				      "%s",
				      soup_status_get_phrase (msg->status_code));
		return FALSE;
	}

	body = soup_message_body_flatten (msg->response_body);
	parser = json_parser_new ();
	if (json_parser_load_from_data (parser, body->data, body->length, error)) {
		JsonObject *obj;

		*node = json_node_copy (json_parser_get_root (parser));

		obj = json_node_get_object (*node);
		if (json_object_has_member (obj, "error")) {
			JsonObject *error_obj;

			error_obj = json_object_get_object_member (obj, "error");
			*error = g_error_new (WEB_SERVICE_ERROR,
					      json_object_get_int_member (error_obj, "code"),
					      "%s",
					      json_object_get_string_member (error_obj, "message"));

			json_node_free (*node);
			*node = NULL;
		}
	}

	g_object_unref (parser);
	soup_buffer_free (body);

	return *node != NULL;
}
Beispiel #12
0
static void
get_logged_in_user_ready_cb (SoupSession *session,
			     SoupMessage *msg,
			     gpointer     user_data)
{
	FacebookService    *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc = NULL;
	GError             *error = NULL;

	result = facebook_connection_get_result (self->priv->conn);

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	if (facebook_utils_parse_response (body, &doc, &error)) {
		DomElement *root;
		char       *uid = NULL;

		root = DOM_ELEMENT (doc)->first_child;
		if (g_strcmp0 (root->tag_name, "users_getLoggedInUser_response") == 0)
			uid = g_strdup (dom_element_get_inner_text (root));

		if (uid == NULL) {
			error = g_error_new_literal (FACEBOOK_CONNECTION_ERROR, 0, _("Unknown error"));
			g_simple_async_result_set_from_error (result, error);
		}
		else
			g_simple_async_result_set_op_res_gpointer (result, uid, g_free);

		g_object_unref (doc);
	}
	else
		g_simple_async_result_set_from_error (result, error);

	g_simple_async_result_complete_in_idle (result);

	soup_buffer_free (body);
}
Beispiel #13
0
static void
resolve_callback (SoupAddress *addr, guint status, gpointer data)
{
    if (status == SOUP_STATUS_OK) {
        printf ("Name:    %s\n", soup_address_get_name (addr));
        printf ("Address: %s\n", soup_address_get_physical (addr));
    } else {
        printf ("Name:    %s\n", soup_address_get_name (addr));
        printf ("Error:   %s\n", soup_status_get_phrase (status));
    }
    printf ("\n");

    nlookups--;
    if (nlookups == 0)
        g_main_loop_quit (loop);
}
Beispiel #14
0
static void
_oauth_service_get_request_token_ready_cb (SoupSession *session,
					   SoupMessage *msg,
					   gpointer     user_data)
{
	OAuthService       *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	GHashTable         *values;
	char               *token;
	char               *token_secret;

	result = _web_service_get_result (WEB_SERVICE (self));

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	values = soup_form_decode (body->data);
	token = g_hash_table_lookup (values, "oauth_token");
	token_secret = g_hash_table_lookup (values, "oauth_token_secret");
	if ((token != NULL) && (token_secret != NULL)) {
		oauth_service_set_token (self, token);
		oauth_service_set_token_secret (self, token_secret);
		g_simple_async_result_set_op_res_gboolean (result, TRUE);
	}
	else {
		GError *error;

		error = g_error_new_literal (WEB_SERVICE_ERROR, WEB_SERVICE_ERROR_GENERIC, _("Unknown error"));
		g_simple_async_result_set_from_error (result, error);
	}

	g_simple_async_result_complete_in_idle (result);

	g_hash_table_destroy (values);
	soup_buffer_free (body);
}
Beispiel #15
0
static void
create_album_ready_cb (SoupSession *session,
		       SoupMessage *msg,
		       gpointer     user_data)
{
	PicasaWebService   *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc;
	GError             *error = NULL;

	result = _web_service_get_result (WEB_SERVICE (self));

	if (msg->status_code != 201) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	doc = dom_document_new ();
	if (dom_document_load (doc, body->data, body->length, &error)) {
		PicasaWebAlbum *album;

		album = picasa_web_album_new ();
		dom_domizable_load_from_element (DOM_DOMIZABLE (album), DOM_ELEMENT (doc)->first_child);
		g_simple_async_result_set_op_res_gpointer (result, album, (GDestroyNotify) g_object_unref);
	}
	else {
		g_simple_async_result_set_from_error (result, error);
		g_error_free (error);
	}
	g_simple_async_result_complete_in_idle (result);

	g_object_unref (doc);
	soup_buffer_free (body);
}
Beispiel #16
0
static void
post_photo_ready_cb (SoupSession *session,
		     SoupMessage *msg,
		     gpointer     user_data)
{
	PicasaWebService *self = user_data;

	if (msg->status_code != 201) {
		GError *error;

		error = g_error_new_literal (SOUP_HTTP_ERROR,
					     msg->status_code,
					     soup_status_get_phrase (msg->status_code));
		post_photos_done (self, error);
		g_error_free (error);

		return;
	}

	self->priv->post_photos->current = self->priv->post_photos->current->next;
	picasa_wev_service_post_current_file (self);
}
Beispiel #17
0
static void
do_message_to_session (SoupSession *session, const char *uri,
		       const char *comment, guint expected_status)
{
	SoupMessage *msg;
	gboolean finished = FALSE;

	debug_printf (1, "    msg %s\n", comment);
	msg = soup_message_new ("GET", uri);

	g_signal_connect (msg, "finished",
			  G_CALLBACK (message_finished), &finished);
	soup_session_send_message (session, msg);

	if (msg->status_code != expected_status) {
		debug_printf (1, "      FAILED: %d %s (expected %d %s)\n",
			      msg->status_code, msg->reason_phrase,
			      expected_status,
			      soup_status_get_phrase (expected_status));
		errors++;
	}

	if (SOUP_STATUS_IS_SUCCESSFUL (msg->status_code) &&
	    !soup_message_is_keepalive (msg)) {
		debug_printf (1, "      ERROR: message is not keepalive!\n");
		errors++;
	}

	if (!finished) {
		debug_printf (1, "      ERROR: 'finished' was not emitted\n");
		errors++;
	}

	g_signal_handlers_disconnect_by_func (msg,
					      G_CALLBACK (message_finished),
					      &finished);
	g_object_unref (msg);
}
/**
 * gs_plugin_app_set_rating_pkg:
 */
static gboolean
gs_plugin_app_set_rating_pkg (GsPlugin *plugin,
			      const gchar *pkgname,
			      gint rating,
			      GError **error)
{
	guint status_code;
	_cleanup_free_ gchar *data = NULL;
	_cleanup_free_ gchar *error_msg = NULL;
	_cleanup_free_ gchar *uri = NULL;
	_cleanup_object_unref_ SoupMessage *msg = NULL;

	/* create the PUT data */
	uri = g_strdup_printf ("%s/api/v1/rating/%s/",
			       GS_PLUGIN_FEDORA_TAGGER_SERVER,
			       pkgname);
	data = g_strdup_printf ("pkgname=%s&rating=%i", pkgname, rating);
	msg = soup_message_new (SOUP_METHOD_PUT, uri);
	soup_message_set_request (msg, SOUP_FORM_MIME_TYPE_URLENCODED,
				  SOUP_MEMORY_COPY, data, strlen (data));

	/* set sync request */
	status_code = soup_session_send_message (plugin->priv->session, msg);
	if (status_code != SOUP_STATUS_OK) {
		g_debug ("Failed to set rating on fedora-tagger: %s",
			 soup_status_get_phrase (status_code));
		if (msg->response_body->data != NULL) {
			error_msg = gs_plugin_parse_json (msg->response_body->data,
							  msg->response_body->length,
							  "error");
			g_debug ("the error given was: %s", error_msg);
		}
	} else {
		g_debug ("Got response: %s", msg->response_body->data);
	}
	return TRUE;
}
static gboolean
gs_plugin_app_set_usage_pkg (GsPlugin *plugin,
			     const gchar *pkgname,
			     gboolean is_install,
			     GError **error)
{
	guint status_code;
	g_autofree gchar *data = NULL;
	g_autofree gchar *uri = NULL;
	g_autoptr(SoupMessage) msg = NULL;

	/* create the PUT data */
	uri = g_strdup_printf ("%s/api/v1/usage/%s/",
			       GS_PLUGIN_FEDORA_TAGGER_SERVER,
			       pkgname);
	data = g_strdup_printf ("pkgname=%s&usage=%s",
				pkgname,
				is_install ? "true" : "false");
	msg = soup_message_new (SOUP_METHOD_PUT, uri);
	soup_message_set_request (msg, SOUP_FORM_MIME_TYPE_URLENCODED,
				  SOUP_MEMORY_COPY, data, strlen (data));

	/* set sync request */
	status_code = soup_session_send_message (gs_plugin_get_soup_session (plugin), msg);
	if (status_code != SOUP_STATUS_OK) {
		g_debug ("Failed to set usage on fedora-tagger: %s",
			 soup_status_get_phrase (status_code));
		if (msg->response_body->data != NULL) {
			g_debug ("the error given was: %s",
				 msg->response_body->data);
		}
	} else {
		g_debug ("Got response: %s", msg->response_body->data);
	}
	return TRUE;
}
static GError *
download_contacts (EBookBackendWebdav *webdav,
                   EFlag *running,
                   EDataBookView *book_view,
                   GCancellable *cancellable)
{
	EBookBackendWebdavPrivate *priv = webdav->priv;
	EBookBackend		  *book_backend;
	SoupMessage               *message;
	guint                      status;
	xmlTextReaderPtr           reader;
	response_element_t        *elements;
	response_element_t        *element;
	response_element_t        *next;
	gint                        count;
	gint                        i;
	gchar                     *new_ctag = NULL;

	g_mutex_lock (&priv->update_lock);

	if (!check_addressbook_changed (webdav, &new_ctag, cancellable)) {
		g_free (new_ctag);
		g_mutex_unlock (&priv->update_lock);
		return EDB_ERROR (SUCCESS);
	}

	book_backend = E_BOOK_BACKEND (webdav);

	if (book_view != NULL) {
		e_data_book_view_notify_progress (book_view, -1,
				_("Loading Addressbook summary..."));
	}

	message = send_propfind (webdav, cancellable);
	status  = message->status_code;

	if (status == 401 || status == 407) {
		g_object_unref (message);
		g_free (new_ctag);
		if (book_view)
			e_data_book_view_notify_progress (book_view, -1, NULL);
		g_mutex_unlock (&priv->update_lock);
		return webdav_handle_auth_request (webdav);
	}
	if (status != 207) {
		GError *error;

		error = e_data_book_create_error_fmt (
			E_DATA_BOOK_STATUS_OTHER_ERROR,
			_("PROPFIND on webdav failed with HTTP status %d (%s)"),
			status,
			message->reason_phrase && *message->reason_phrase ? message->reason_phrase :
			(soup_status_get_phrase (message->status_code) ? soup_status_get_phrase (message->status_code) : _("Unknown error")));

		g_object_unref (message);
		g_free (new_ctag);

		if (book_view)
			e_data_book_view_notify_progress (book_view, -1, NULL);

		g_mutex_unlock (&priv->update_lock);

		return error;
	}
	if (message->response_body == NULL) {
		g_warning ("No response body in webdav PROPFIND result");
		g_object_unref (message);
		g_free (new_ctag);

		if (book_view)
			e_data_book_view_notify_progress (book_view, -1, NULL);

		g_mutex_unlock (&priv->update_lock);

		return e_data_book_create_error_fmt (E_DATA_BOOK_STATUS_OTHER_ERROR, _("No response body in webdav PROPFIND result"));
	}

	/* parse response */
	reader = xmlReaderForMemory (
		message->response_body->data,
		message->response_body->length, NULL, NULL,
		XML_PARSE_NOWARNING);

	elements = parse_propfind_response (reader);

	/* count contacts */
	count = 0;
	for (element = elements; element != NULL; element = element->next) {
		++count;
	}

	/* download contacts */
	i = 0;
	for (element = elements; element != NULL; element = element->next, ++i) {
		const gchar  *uri;
		const gchar *etag;
		EContact    *contact;
		gchar *complete_uri;

		/* stop downloading if search was aborted */
		if (running != NULL && !e_flag_is_set (running))
			break;

		if (book_view != NULL) {
			gfloat percent = 100.0 / count * i;
			gchar buf[100];
			snprintf (buf, sizeof (buf), _("Loading Contacts (%d%%)"), (gint) percent);
			e_data_book_view_notify_progress (book_view, -1, buf);
		}

		/* skip collections */
		uri = (const gchar *) element->href;
		if (uri[strlen (uri) - 1] == '/')
			continue;

		/* uri might be relative, construct complete one */
		if (uri[0] == '/') {
			SoupURI *soup_uri = soup_uri_new (priv->uri);
			soup_uri->path    = g_strdup (uri);

			complete_uri = soup_uri_to_string (soup_uri, 0);
			soup_uri_free (soup_uri);
		} else {
			complete_uri = g_strdup (uri);
		}

		etag = (const gchar *) element->etag;

		g_mutex_lock (&priv->cache_lock);
		contact = e_book_backend_cache_get_contact (priv->cache, complete_uri);
		g_mutex_unlock (&priv->cache_lock);

		/* download contact if it is not cached or its ETag changed */
		if (contact == NULL || etag == NULL ||
		    strcmp (e_contact_get_const (contact, E_CONTACT_REV), etag) != 0) {
			contact = download_contact (webdav, complete_uri, cancellable);
			if (contact != NULL) {
				g_mutex_lock (&priv->cache_lock);
				if (e_book_backend_cache_remove_contact (priv->cache, complete_uri))
					e_book_backend_notify_remove (book_backend, complete_uri);
				e_book_backend_cache_add_contact (priv->cache, contact);
				g_mutex_unlock (&priv->cache_lock);
				e_book_backend_notify_update (book_backend, contact);
			}
		}

		g_free (complete_uri);
	}

	/* free element list */
	for (element = elements; element != NULL; element = next) {
		next = element->next;

		xmlFree (element->href);
		xmlFree (element->etag);
		g_free (element);
	}

	xmlFreeTextReader (reader);
	g_object_unref (message);

	if (new_ctag) {
		g_mutex_lock (&priv->cache_lock);
		if (!e_file_cache_replace_object (E_FILE_CACHE (priv->cache), WEBDAV_CTAG_KEY, new_ctag))
			e_file_cache_add_object (E_FILE_CACHE (priv->cache), WEBDAV_CTAG_KEY, new_ctag);
		g_mutex_unlock (&priv->cache_lock);
	}
	g_free (new_ctag);

	if (book_view)
		e_data_book_view_notify_progress (book_view, -1, NULL);

	g_mutex_unlock (&priv->update_lock);

	return EDB_ERROR (SUCCESS);
}
static guint
upload_contact (EBookBackendWebdav *webdav,
                EContact *contact,
                gchar **reason,
                GCancellable *cancellable)
{
	ESource     *source;
	ESourceWebdav *webdav_extension;
	SoupMessage *message;
	gchar       *uri;
	gchar       *etag;
	const gchar  *new_etag, *redir_uri;
	gchar        *request;
	guint        status;
	gboolean     avoid_ifmatch;
	const gchar *extension_name;

	source = e_backend_get_source (E_BACKEND (webdav));

	extension_name = E_SOURCE_EXTENSION_WEBDAV_BACKEND;
	webdav_extension = e_source_get_extension (source, extension_name);

	source = e_backend_get_source (E_BACKEND (webdav));

	uri = e_contact_get (contact, E_CONTACT_UID);
	if (uri == NULL) {
		g_warning ("can't upload contact without UID");
		return 400;
	}

	message = soup_message_new (SOUP_METHOD_PUT, uri);
	soup_message_headers_append (message->request_headers, "User-Agent", USERAGENT);
	soup_message_headers_append (message->request_headers, "Connection", "close");

	avoid_ifmatch = e_source_webdav_get_avoid_ifmatch (webdav_extension);

	/* some servers (like apache < 2.2.8) don't handle If-Match, correctly so
	 * we can leave it out */
	if (!avoid_ifmatch) {
		/* only override if etag is still the same on the server */
		etag = e_contact_get (contact, E_CONTACT_REV);
		if (etag == NULL) {
			soup_message_headers_append (
				message->request_headers,
				"If-None-Match", "*");
		} else if (etag[0] == 'W' && etag[1] == '/') {
			g_warning ("we only have a weak ETag, don't use If-Match synchronisation");
		} else {
			soup_message_headers_append (
				message->request_headers,
				"If-Match", etag);
			g_free (etag);
		}
	}

	request = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
	soup_message_set_request (
		message, "text/vcard", SOUP_MEMORY_TEMPORARY,
		request, strlen (request));

	status   = send_and_handle_ssl (webdav, message, cancellable);
	new_etag = soup_message_headers_get_list (message->response_headers, "ETag");

	redir_uri = soup_message_headers_get_list (message->response_headers, "Location");

	/* set UID and REV fields */
	e_contact_set (contact, E_CONTACT_REV, (gconstpointer) new_etag);
	if (redir_uri && *redir_uri) {
		if (!strstr (redir_uri, "://")) {
			/* it's a relative URI */
			SoupURI *suri = soup_uri_new (uri);
			gchar *full_uri;

			soup_uri_set_path (suri, redir_uri);
			full_uri = soup_uri_to_string (suri, TRUE);

			e_contact_set (contact, E_CONTACT_UID, full_uri);

			g_free (full_uri);
			soup_uri_free (suri);
		} else {
			e_contact_set (contact, E_CONTACT_UID, redir_uri);
		}
	} else {
		e_contact_set (contact, E_CONTACT_UID, uri);
	}

	if (reason) {
		*reason = g_strdup (message->reason_phrase && *message->reason_phrase ? message->reason_phrase :
				    (soup_status_get_phrase (message->status_code) ? soup_status_get_phrase (message->status_code) : _("Unknown error")));
	}

	g_object_unref (message);
	g_free (request);
	g_free (uri);

	return status;
}
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;
}
Beispiel #23
0
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;
}
Beispiel #24
0
/**
 * 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;
}
Beispiel #25
0
int
main (int argc, char **argv)
{
	int opt, debug = 0, listener, sin_len, port, i;
	struct sockaddr_in sin;
	GThread *server;
	char writebuf[BUFSIZE], readbuf[BUFSIZE];
	SoupAddress *addr;
	SoupSSLCredentials *creds;
	SoupSocket *sock;
	gsize n, total;
	SoupSocketIOStatus status;
	int connect_status;
	GError *error = NULL;

	g_thread_init (NULL);
	g_type_init ();

	/* On Windows, this will call WSAStartup() */
	soup_socket_get_type ();

	while ((opt = getopt (argc, argv, "c:d:k:")) != -1) {
		switch (opt) {
		case 'c':
			ssl_cert_file = optarg;
			break;
		case 'd':
			debug = atoi (optarg);
			break;
		case 'k':
			ssl_key_file = optarg;
			break;

		case '?':
			fprintf (stderr, "Usage: %s [-d debuglevel] [-c ssl-cert-file] [-k ssl-key-file]\n",
				 argv[0]);
			break;
		}
	}

	if (debug) {
		gnutls_global_set_log_function (debug_log);
		gnutls_global_set_log_level (debug);
	}

	/* Create server socket */
	listener = socket (AF_INET, SOCK_STREAM, 0);
	if (listener == -1) {
		SOCKET_PRINT_ERROR ("creating listening socket");
		exit (1);
	}

	memset (&sin, 0, sizeof (sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = ntohl (INADDR_LOOPBACK);

	if (bind (listener, (struct sockaddr *) &sin, sizeof (sin))  == -1) {
		SOCKET_PRINT_ERROR ("binding listening socket");
		exit (1);
	}

	if (listen (listener, 1) == -1) {
		SOCKET_PRINT_ERROR ("listening on socket");
		exit (1);
	}

	sin_len = sizeof (sin);
	getsockname (listener, (struct sockaddr *)&sin, (void *)&sin_len);
	port = ntohs (sin.sin_port);

	/* Create the client */
	addr = soup_address_new ("127.0.0.1", port);
	creds = soup_ssl_get_client_credentials (NULL);
	sock = soup_socket_new (SOUP_SOCKET_REMOTE_ADDRESS, addr,
				SOUP_SOCKET_FLAG_NONBLOCKING, FALSE,
				SOUP_SOCKET_SSL_CREDENTIALS, creds,
				NULL);
	g_object_unref (addr);
	connect_status = soup_socket_connect_sync (sock, NULL);
	if (connect_status != SOUP_STATUS_OK) {
		g_error ("Could not create client socket: %s",
			 soup_status_get_phrase (connect_status));
	}

	soup_socket_start_ssl (sock, NULL);

	/* Now spawn server thread */
	server = g_thread_create (server_thread, GINT_TO_POINTER (listener),
				  TRUE, NULL);

	/* Synchronous client test */
	for (i = 0; i < BUFSIZE; i++)
		writebuf[i] = i & 0xFF;

	total = 0;
	while (total < BUFSIZE) {
		status = soup_socket_write (sock, writebuf + total,
					    BUFSIZE - total, &n,
					    NULL, &error);
		if (status != SOUP_SOCKET_OK)
			g_error ("Sync write got status %d: %s", status,
				 error ? error->message : "(unknown)");
		total += n;
	}

	total = 0;
	while (total < BUFSIZE) {
		status = soup_socket_read (sock, readbuf + total,
					   BUFSIZE - total, &n,
					   NULL, &error);
		if (status != SOUP_SOCKET_OK)
			g_error ("Sync read got status %d: %s", status,
				 error ? error->message : "(unknown)");
		total += n;
	}

	if (memcmp (writebuf, readbuf, BUFSIZE) != 0)
		g_error ("Sync read didn't match write");

	printf ("SYNCHRONOUS SSL TEST PASSED\n");

	/* Switch socket to async and do it again */

	g_object_set (sock,
		      SOUP_SOCKET_FLAG_NONBLOCKING, TRUE,
		      NULL);

	g_idle_add (start_writing, sock);
	loop = g_main_loop_new (NULL, TRUE);
	g_main_loop_run (loop);
	g_main_loop_unref (loop);
	g_main_context_unref (g_main_context_default ());

	printf ("ASYNCHRONOUS SSL TEST PASSED\n");

	g_object_unref (sock);
	soup_ssl_free_client_credentials (creds);
	g_thread_join (server);

	/* Success */
	return 0;
}
Beispiel #26
0
static void
list_albums_ready_cb (SoupSession *session,
		      SoupMessage *msg,
		      gpointer     user_data)
{
	PicasaWebService   *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc;
	GError             *error = NULL;

	result = _web_service_get_result (WEB_SERVICE (self));

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	doc = dom_document_new ();
	if (dom_document_load (doc, body->data, body->length, &error)) {
		DomElement *feed_node;
		GList      *albums = NULL;

		feed_node = DOM_ELEMENT (doc)->first_child;
		while ((feed_node != NULL) && g_strcmp0 (feed_node->tag_name, "feed") != 0)
			feed_node = feed_node->next_sibling;

		if (feed_node != NULL) {
			DomElement     *node;
			PicasaWebAlbum *album;

			album = NULL;
			for (node = feed_node->first_child;
			     node != NULL;
			     node = node->next_sibling)
			{
				if (g_strcmp0 (node->tag_name, "entry") == 0) { /* read the album data */
					if (album != NULL)
						albums = g_list_prepend (albums, album);
					album = picasa_web_album_new ();
					dom_domizable_load_from_element (DOM_DOMIZABLE (album), node);
				}
				else if (g_strcmp0 (node->tag_name, "gphoto:quotalimit") == 0) {
					self->priv->quota_limit = g_ascii_strtoull (dom_element_get_inner_text (node), NULL, 10);
				}
				else if (g_strcmp0 (node->tag_name, "gphoto:quotacurrent") == 0) {
					self->priv->quota_used = g_ascii_strtoull (dom_element_get_inner_text (node), NULL, 10);
				}
			}
			if (album != NULL)
				albums = g_list_prepend (albums, album);
		}
		albums = g_list_reverse (albums);
		g_simple_async_result_set_op_res_gpointer (result, albums, (GDestroyNotify) _g_object_list_unref);
	}
	else {
		g_simple_async_result_set_from_error (result, error);
		g_error_free (error);
	}
	g_simple_async_result_complete_in_idle (result);

	g_object_unref (doc);
	soup_buffer_free (body);
}
/**
 * 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);
}
Beispiel #28
0
static void rygel_mediathek_rss_container_on_feed_got (RygelMediathekRssContainer* self, SoupSession* session, SoupMessage* msg) {
#line 129 "rygel-mediathek-rss-container.c"
	guint _tmp0_;
#line 31 "rygel-mediathek-rss-container.vala"
	g_return_if_fail (self != NULL);
#line 31 "rygel-mediathek-rss-container.vala"
	g_return_if_fail (session != NULL);
#line 31 "rygel-mediathek-rss-container.vala"
	g_return_if_fail (msg != NULL);
#line 32 "rygel-mediathek-rss-container.vala"
	switch ((g_object_get (msg, "status-code", &_tmp0_, NULL), _tmp0_)) {
#line 139 "rygel-mediathek-rss-container.c"
		case 304:
		{
#line 34 "rygel-mediathek-rss-container.vala"
			g_message ("rygel-mediathek-rss-container.vala:34: %s", _ ("Feed has not changed, nothing to do"));
#line 35 "rygel-mediathek-rss-container.vala"
			break;
#line 146 "rygel-mediathek-rss-container.c"
		}
		case 200:
		{
#line 37 "rygel-mediathek-rss-container.vala"
			if (rygel_mediathek_rss_container_parse_response (self, (const char*) msg->response_body->data, (gsize) msg->response_body->length)) {
#line 152 "rygel-mediathek-rss-container.c"
				SoupDate* _tmp1_;
#line 39 "rygel-mediathek-rss-container.vala"
				self->priv->last_modified = (_tmp1_ = soup_date_new_from_string (soup_message_headers_get (msg->response_headers, "Date")), _soup_date_free0 (self->priv->last_modified), _tmp1_);
#line 156 "rygel-mediathek-rss-container.c"
			}
#line 42 "rygel-mediathek-rss-container.vala"
			break;
#line 160 "rygel-mediathek-rss-container.c"
		}
		default:
		{
			guint _tmp2_;
			guint _tmp3_;
#line 45 "rygel-mediathek-rss-container.vala"
			g_warning (_ ("Got unexpected response %u (%s)"), (g_object_get (msg, "status-code", &_tmp2_, NULL), _tmp2_), soup_status_get_phrase ((g_object_get (msg, "status-code", &_tmp3_, NULL), _tmp3_)));
#line 48 "rygel-mediathek-rss-container.vala"
			break;
#line 170 "rygel-mediathek-rss-container.c"
		}
	}
}
Beispiel #29
0
static void
list_photos_ready_cb (SoupSession *session,
		      SoupMessage *msg,
		      gpointer     user_data)
{
	PicasaWebService   *self = user_data;
	GSimpleAsyncResult *result;
	SoupBuffer         *body;
	DomDocument        *doc;
	GError             *error = NULL;

	result = _web_service_get_result (WEB_SERVICE (self));

	if (msg->status_code != 200) {
		g_simple_async_result_set_error (result,
						 SOUP_HTTP_ERROR,
						 msg->status_code,
						 "%s",
						 soup_status_get_phrase (msg->status_code));
		g_simple_async_result_complete_in_idle (result);
		return;
	}

	body = soup_message_body_flatten (msg->response_body);
	doc = dom_document_new ();
	if (dom_document_load (doc, body->data, body->length, &error)) {
		DomElement *feed_node;
		GList      *photos = NULL;

		feed_node = DOM_ELEMENT (doc)->first_child;
		while ((feed_node != NULL) && g_strcmp0 (feed_node->tag_name, "feed") != 0)
			feed_node = feed_node->next_sibling;

		if (feed_node != NULL) {
			DomElement     *node;
			PicasaWebPhoto *photo;

			photo = NULL;
			for (node = feed_node->first_child;
			     node != NULL;
			     node = node->next_sibling)
			{
				if (g_strcmp0 (node->tag_name, "entry") == 0) { /* read the photo data */
					if (photo != NULL)
						photos = g_list_prepend (photos, photo);
					photo = picasa_web_photo_new ();
					dom_domizable_load_from_element (DOM_DOMIZABLE (photo), node);
				}
			}
			if (photo != NULL)
				photos = g_list_prepend (photos, photo);
		}
		photos = g_list_reverse (photos);
		g_simple_async_result_set_op_res_gpointer (result, photos, (GDestroyNotify) _g_object_list_unref);
	}
	else {
		g_simple_async_result_set_from_error (result, error);
		g_error_free (error);
	}
	g_simple_async_result_complete_in_idle (result);

	g_object_unref (doc);
	soup_buffer_free (body);
}
static gboolean
do_one_attempt (gpointer user_data)
{
  GError *local_error = NULL;
  MinCloudAgentApp *self = user_data;
  gs_free char *uri_str = NULL;
  gs_unref_object SoupRequest *request = NULL;
  gs_unref_object GInputStream *instream = NULL;
  gs_unref_object GFileOutputStream *outstream = NULL;
  gs_unref_object GFile *authorized_keys_path = NULL;
  gs_unref_object SoupMessage *msg = NULL;
  SoupURI *uri = NULL;
  const int max_request_failures = 5;
  const char *state_description = NULL;

  /* Skip over already completed states */
 again:
  switch (self->state)
    {
    case MCA_STATE_USER_DATA:
      if (g_file_query_exists (self->userdata_done_stamp, NULL))
        {
          self->state++;
          goto again;
        }
      break;
    case MCA_STATE_OPENSSH_KEY:
      if (g_file_query_exists (self->authorized_keys_path, NULL))
        {
          self->state++;
          goto again;
        }
      break;
    case MCA_STATE_DONE:
      goto out;
    }

  uri = soup_uri_new (NULL);
  soup_uri_set_scheme (uri, "http");
  {
    gs_free char *addr_str = g_inet_address_to_string (self->addr);
    soup_uri_set_host (uri, addr_str);
  }
  soup_uri_set_port (uri, g_inet_socket_address_get_port (self->addr_port));
  switch (self->state)
    {
    case MCA_STATE_USER_DATA:
      soup_uri_set_path (uri, "/2009-04-04/user-data");
      state_description = "user-data";
      break;
    case MCA_STATE_OPENSSH_KEY:
      soup_uri_set_path (uri, "/2009-04-04/meta-data/public-keys/0/openssh-key");
      state_description = "openssh-key";
      break;
    case MCA_STATE_DONE:
      g_assert_not_reached ();
    }

  uri_str = soup_uri_to_string (uri, FALSE);
  g_print ("Requesting '%s'...\n", uri_str);

  request = soup_session_request_uri (self->session, uri, &local_error);
  soup_uri_free (uri);
  if (!request)
    goto out;

  instream = soup_request_send (request, NULL, &local_error);
  if (!instream)
    goto out;

  msg = soup_request_http_get_message ((SoupRequestHTTP*) request);
  if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
    {
      switch (msg->status_code)
        {
        case 404:
        case 410:
          {
            gs_log_structured_print_id_v (MCA_NOT_FOUND_ID, "No %s found", state_description);
            g_clear_error (&local_error);
            /* Note fallthrough to out, where we'll advance to the
               next state */
            goto out;
          }
        default:
          /* Don't actually set the error, we will just continue to
           * the next phase.
           */
          gs_log_structured_print_id_v (MCA_TIMEOUT_ID,
                                        "Error fetching %s: %u %s",
                                        uri_str,
                                        msg->status_code,
                                        soup_status_get_phrase (msg->status_code));
          goto out;
        }
    }

  switch (self->state)
    {
    case MCA_STATE_USER_DATA:
      if (!handle_userdata_script (self, instream, self->cancellable,
                                   &local_error))
        goto out;
      break;
    case MCA_STATE_OPENSSH_KEY:
      if (!handle_install_authorized_keys (self, instream, self->cancellable,
                                           &local_error))
        goto out;
      break;
    default:
      g_assert_not_reached ();
    }

  g_assert (self->state != MCA_STATE_DONE);
  self->state++;
  self->request_failure_count = 0;

 out:
  if (local_error)
    {
      self->request_failure_count++;
      if (self->request_failure_count >= max_request_failures)
        {
          g_error_free (local_error);
          gs_log_structured_print_id_v (MCA_TIMEOUT_ID,
                                        "Reached maximum failed attempts (%u) to fetch metadata",
                                        self->request_failure_count);
          self->do_one_attempt_id = 0;
          self->running = FALSE;
        }
      else
        {
          gs_log_structured_print_id_v (MCA_REQUEST_FAILED_ID,
                                        "Request failed (count: %u): %s", self->request_failure_count,
                                        local_error->message);
          g_error_free (local_error);
          self->do_one_attempt_id = g_timeout_add_seconds (self->request_failure_count,
                                                           do_one_attempt, self);
        }
    }
  else
    {
      /* If we advanced in state, schedule the next callback in an
       * idle so we're consistently scheduled out of an idle.
       */
      if (self->state != MCA_STATE_DONE)
        self->do_one_attempt_id = g_idle_add (do_one_attempt, self);
      else
        {
          self->do_one_attempt_id = 0;
          self->running = FALSE;
        }
    }

  return FALSE;
}