librest/0000755000175000017500000000000012014274315010607 5ustar bobboblibrest/README0000664000175000017500000000452112014274314011472 0ustar bobboblibrest ======= This library has been designed to make it easier to access web services that claim to be "RESTful". A reasonable definition of what this means can be found on Wikipedia [1]. However a reasonable description is that a RESTful service should have urls that represent remote objects which methods can then be called on. However it should be noted that the majority of services don't actually adhere to this strict definition. Instead their RESTful end-point usually has an API that is just simpler to use compared to other types of APIs they may support (XML-RPC, for instance.). It is this kind of API that this library is attempting to support. It comprises of two parts: the first aims to make it easier to make requests by providing a wrapper around libsoup [2], the second aids with XML parsing by wrapping libxml2 [3]. Making requests ~~~~~~~~~~~~~~~ When a proxy is created for a url you are able to present a format string. This format string is intended to represent the type of path for a remote object, it is then possible to bind this format string with specific names of objects to make this proxy concrete rather than abstract. We abstract the parameters required for a particular call into it's own object which we can then invoke both asynchronously and pseudo-asynchronously (by spinning the main loop whilst waiting for an answer.) This has the advantage of allowing us to support complex behaviour that depends on the parameters, for instance signing a request: a requirement for many web services. Handling the result ~~~~~~~~~~~~~~~~~~~ Standard XML parsers require a significant amount of work to parse a piece of XML. In terms of a SAX parser this involves setting up the functions before hand, in terms of a DOM parser this means dealing with complexity of a DOM tree. The XML parsing components of librest are designed to try and behave a bit like the BeautifulSoup parser [4]. It does this by parsing the XML into an easily walkable tree were nodes have children for their descendents and siblings for the nodes of the same type that share the same parent. This makes it easy for instance to get a list of all the "photo" nodes in a document from the root. [1] - http://en.wikipedia.org/wiki/Representational_State_Transfer [2] - http://live.gnome.org/LibSoup [3] - http://xmlsoft.org/ [4] - http://www.crummy.com/software/BeautifulSoup/ librest/librest.doap0000664000175000017500000000215712014274314013126 0ustar bobbob librest Helper library for RESTful services librest is a helper library for RESTful services. It uses libsoup to provide HTTP communication. Rob Bradford rbradford Ross Burton rburton librest/rest.pc.in0000664000175000017500000000046112014274314012517 0ustar bobbobprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ apiversion=@API_VERSION@ Name: rest Description: RESTful web api query library Version: @VERSION@ Libs: -L${libdir} -lrest-${apiversion} Cflags: -I${includedir}/rest-${apiversion} Requires: glib-2.0 libsoup-2.4 libxml-2.0 librest/autogen.sh0000775000175000017500000000071712014274314012616 0ustar bobbob#!/bin/sh set -e test -n "$srcdir" || srcdir=`dirname "$0"` test -n "$srcdir" || srcdir=. olddir=`pwd` cd "$srcdir" GTKDOCIZE=`which gtkdocize` if test -z $GTKDOCIZE; then echo "*** No gtk-doc support ***" echo "EXTRA_DIST =" > gtk-doc.make echo "CLEANFILES =" >> gtk-doc.make else gtkdocize --flavour no-tmpl || exit 1 fi ACLOCAL="${ACLOCAL-aclocal} $ACLOCAL_FLAGS" autoreconf -v -i cd "$olddir" test -n "$NOCONFIGURE" || "$srcdir/configure" "$@" librest/.gitignore0000664000175000017500000000220212014274314012574 0ustar bobbob*.gir *.typelib *.la *.lo *.o Makefile Makefile.in .deps .libs *.bak *~ *.pc aclocal.m4 autom4te.cache compile configure config.* depcomp gtk-doc.make gtk-doc.m4 install-sh libtool.m4 ltoptions.m4 ltsugar.m4 ltversion.m4 lt~obsolete.m4 libtool ltmain.sh missing stamp-h1 docs/reference/rest*/*-decl*.txt docs/reference/rest*/*-overrides.txt docs/reference/rest*/*-undeclared.txt docs/reference/rest*/*-undocumented.txt docs/reference/rest*/*-unused.txt docs/reference/rest*/*.args docs/reference/rest*/*.hierarchy docs/reference/rest*/*.interfaces docs/reference/rest*/*.prerequisites docs/reference/rest*/*.signals docs/reference/rest*/*.stamp docs/reference/rest*/html/ docs/reference/rest*/xml/ examples/continuous-twitter examples/dump-xml examples/get-fireeagle-location examples/get-flickr-favorites examples/lastfm-shout examples/post-twitter examples/test-raw examples/test-xml rest-extras/test-runner rest/rest-enum-types.c rest/rest-enum-types.h rest/stamp-rest-enum-types.h rest/test-runner tests/custom-serialize tests/flickr tests/lastfm tests/oauth tests/oauth-async tests/oauth2 tests/proxy tests/proxy-continuous tests/threaded tests/xml librest/rest-extras/0000775000175000017500000000000012014274314013071 5ustar bobboblibrest/rest-extras/lastfm-proxy-call.h0000664000175000017500000000373712014274314016632 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _LASTFM_PROXY_CALL #define _LASTFM_PROXY_CALL #include G_BEGIN_DECLS #define LASTFM_TYPE_PROXY_CALL lastfm_proxy_call_get_type() #define LASTFM_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), LASTFM_TYPE_PROXY_CALL, LastfmProxyCall)) #define LASTFM_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), LASTFM_TYPE_PROXY_CALL, LastfmProxyCallClass)) #define LASTFM_IS_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), LASTFM_TYPE_PROXY_CALL)) #define LASTFM_IS_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), LASTFM_TYPE_PROXY_CALL)) #define LASTFM_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), LASTFM_TYPE_PROXY_CALL, LastfmProxyCallClass)) /** * LastfmProxyCall: * * #LastfmProxyCall has no publicly available members. */ typedef struct { RestProxyCall parent; } LastfmProxyCall; typedef struct { RestProxyCallClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } LastfmProxyCallClass; GType lastfm_proxy_call_get_type (void); G_END_DECLS #endif /* _LASTFM_PROXY_CALL */ librest/rest-extras/flickr-proxy-private.h0000664000175000017500000000213412014274314017343 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "flickr-proxy.h" #define FLICKR_PROXY_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), FLICKR_TYPE_PROXY, FlickrProxyPrivate)) struct _FlickrProxyPrivate { char *api_key; char *shared_secret; char *token; }; librest/rest-extras/youtube-proxy-private.h0000664000175000017500000000204712014274314017570 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2011 Collabora Ltd. * * Authors: Eitan Isaacson * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "youtube-proxy.h" #define YOUTUBE_PROXY_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), YOUTUBE_TYPE_PROXY, YoutubeProxyPrivate)) struct _YoutubeProxyPrivate { char *developer_key; char *user_auth; }; librest/rest-extras/flickr-proxy.c0000664000175000017500000003255512014274314015700 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* * TODO: * * Convenience API for authentication so that the user doesn't have to parse the * XML themselves. */ #include #include #include #include #include #include "flickr-proxy.h" #include "flickr-proxy-private.h" #include "flickr-proxy-call.h" G_DEFINE_TYPE (FlickrProxy, flickr_proxy, REST_TYPE_PROXY) enum { PROP_0, PROP_API_KEY, PROP_SHARED_SECRET, PROP_TOKEN, }; GQuark flickr_proxy_error_quark (void) { return g_quark_from_static_string ("rest-flickr-proxy"); } static RestProxyCall * _new_call (RestProxy *proxy) { RestProxyCall *call; call = g_object_new (FLICKR_TYPE_PROXY_CALL, "proxy", proxy, NULL); return call; } static void flickr_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_API_KEY: g_value_set_string (value, priv->api_key); break; case PROP_SHARED_SECRET: g_value_set_string (value, priv->shared_secret); break; case PROP_TOKEN: g_value_set_string (value, priv->token); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void flickr_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_API_KEY: if (priv->api_key) g_free (priv->api_key); priv->api_key = g_value_dup_string (value); break; case PROP_SHARED_SECRET: if (priv->shared_secret) g_free (priv->shared_secret); priv->shared_secret = g_value_dup_string (value); break; case PROP_TOKEN: if (priv->token) g_free (priv->token); priv->token = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void flickr_proxy_finalize (GObject *object) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (object); g_free (priv->api_key); g_free (priv->shared_secret); g_free (priv->token); G_OBJECT_CLASS (flickr_proxy_parent_class)->finalize (object); } #ifndef G_PARAM_STATIC_STRINGS #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB) #endif static void flickr_proxy_class_init (FlickrProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); RestProxyClass *proxy_class = REST_PROXY_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (FlickrProxyPrivate)); object_class->get_property = flickr_proxy_get_property; object_class->set_property = flickr_proxy_set_property; object_class->finalize = flickr_proxy_finalize; proxy_class->new_call = _new_call; pspec = g_param_spec_string ("api-key", "api-key", "The API key", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_API_KEY, pspec); pspec = g_param_spec_string ("shared-secret", "shared-secret", "The shared secret", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_SHARED_SECRET, pspec); pspec = g_param_spec_string ("token", "token", "The request or access token", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_TOKEN, pspec); } static void flickr_proxy_init (FlickrProxy *self) { self->priv = FLICKR_PROXY_GET_PRIVATE (self); } RestProxy * flickr_proxy_new (const char *api_key, const char *shared_secret) { return flickr_proxy_new_with_token (api_key, shared_secret, NULL); } RestProxy * flickr_proxy_new_with_token (const char *api_key, const char *shared_secret, const char *token) { return g_object_new (FLICKR_TYPE_PROXY, "api-key", api_key, "shared-secret", shared_secret, "token", token, "url-format", "http://api.flickr.com/services/rest/", "binding-required", FALSE, NULL); } /** * flickr_proxy_get_api_key: * @proxy: an #FlickrProxy * * Get the API key. * * Returns: the API key. This string is owned by #FlickrProxy and should not be * freed. */ const char * flickr_proxy_get_api_key (FlickrProxy *proxy) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (proxy); return priv->api_key; } /** * flickr_proxy_get_shared_secret: * @proxy: an #FlickrProxy * * Get the shared secret for authentication. * * Returns: the shared secret. This string is owned by #FlickrProxy and should not be * freed. */ const char * flickr_proxy_get_shared_secret (FlickrProxy *proxy) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (proxy); return priv->shared_secret; } /** * flickr_proxy_get_token: * @proxy: an #FlickrProxy * * Get the current token. * * Returns: the token, or %NULL if there is no token yet. This string is owned * by #FlickrProxy and should not be freed. */ const char * flickr_proxy_get_token (FlickrProxy *proxy) { FlickrProxyPrivate *priv = FLICKR_PROXY_GET_PRIVATE (proxy); return priv->token; } /** * flickr_proxy_set_token: * @proxy: an #FlickrProxy * @token: the access token * * Set the token. */ void flickr_proxy_set_token (FlickrProxy *proxy, const char *token) { FlickrProxyPrivate *priv; g_return_if_fail (FLICKR_IS_PROXY (proxy)); priv = FLICKR_PROXY_GET_PRIVATE (proxy); if (priv->token) g_free (priv->token); priv->token = g_strdup (token); } char * flickr_proxy_sign (FlickrProxy *proxy, GHashTable *params) { FlickrProxyPrivate *priv; GList *keys; char *md5; GChecksum *checksum; g_return_val_if_fail (FLICKR_IS_PROXY (proxy), NULL); g_return_val_if_fail (params, NULL); priv = FLICKR_PROXY_GET_PRIVATE (proxy); checksum = g_checksum_new (G_CHECKSUM_MD5); g_checksum_update (checksum, (guchar *)priv->shared_secret, -1); keys = g_hash_table_get_keys (params); keys = g_list_sort (keys, (GCompareFunc)strcmp); while (keys) { const char *key, *value; key = keys->data; value = g_hash_table_lookup (params, key); g_checksum_update (checksum, (guchar *)key, -1); g_checksum_update (checksum, (guchar *)value, -1); keys = g_list_delete_link (keys, keys); } md5 = g_strdup (g_checksum_get_string (checksum)); g_checksum_free (checksum); return md5; } char * flickr_proxy_build_login_url (FlickrProxy *proxy, const char *frob, const char *perms) { SoupURI *uri; GHashTable *params; char *sig, *s; g_return_val_if_fail (FLICKR_IS_PROXY (proxy), NULL); uri = soup_uri_new ("http://flickr.com/services/auth/"); params = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (params, "api_key", proxy->priv->api_key); g_hash_table_insert (params, "perms", (gpointer)perms); if (frob) g_hash_table_insert (params, "frob", (gpointer)frob); sig = flickr_proxy_sign (proxy, params); g_hash_table_insert (params, "api_sig", sig); soup_uri_set_query_from_form (uri, params); s = soup_uri_to_string (uri, FALSE); g_free (sig); g_hash_table_destroy (params); soup_uri_free (uri); return s; } /** * flickr_proxy_is_successful: * @root: The root node of a parsed Flickr response * @error: #GError to set if the response was an error * * Examines the Flickr response and if it not a successful reply, set @error and * return FALSE. * * Returns: %TRUE if this response is successful, %FALSE otherwise. */ gboolean flickr_proxy_is_successful (RestXmlNode *root, GError **error) { RestXmlNode *node; g_return_val_if_fail (root, FALSE); if (strcmp (root->name, "rsp") != 0) { g_set_error (error, FLICKR_PROXY_ERROR, 0, "Unexpected response from Flickr (root node %s)", root->name); return FALSE; } if (strcmp (rest_xml_node_get_attr (root, "stat"), "ok") != 0) { node = rest_xml_node_find (root, "err"); g_set_error_literal (error,FLICKR_PROXY_ERROR, atoi (rest_xml_node_get_attr (node, "code")), rest_xml_node_get_attr (node, "msg")); return FALSE; } return TRUE; } /** * flickr_proxy_new_upload: * @proxy: a valid #FlickrProxy * * Create a new #RestProxyCall that can be used for uploading. * * See http://www.flickr.com/services/api/upload.api.html for details on * uploading to Flickr. * * Returns: (type FlickrProxyCall) (transfer full): a new #FlickrProxyCall */ RestProxyCall * flickr_proxy_new_upload (FlickrProxy *proxy) { g_return_val_if_fail (FLICKR_IS_PROXY (proxy), NULL); return g_object_new (FLICKR_TYPE_PROXY_CALL, "proxy", proxy, "upload", TRUE, NULL); } /** * flickr_proxy_new_upload_for_file: * @proxy: a valid #FlickrProxy * @filename: the file to upload * @error: #GError to set on error * Create a new #RestProxyCall that can be used for uploading. @filename will * be set as the "photo" parameter for you, avoiding you from having to open the * file and determine the MIME type. * * Note that this function can in theory block. * * See http://www.flickr.com/services/api/upload.api.html for details on * uploading to Flickr. * * Returns: (type FlickrProxyCall) (transfer full): a new #FlickrProxyCall */ RestProxyCall * flickr_proxy_new_upload_for_file (FlickrProxy *proxy, const char *filename, GError **error) { GMappedFile *map; GError *err = NULL; char *basename = NULL, *content_type = NULL; RestParam *param; RestProxyCall *call = NULL; g_return_val_if_fail (FLICKR_IS_PROXY (proxy), NULL); g_return_val_if_fail (filename, NULL); /* Open the file */ map = g_mapped_file_new (filename, FALSE, &err); if (err) { g_propagate_error (error, err); return NULL; } /* Get the file information */ basename = g_path_get_basename (filename); content_type = g_content_type_guess (filename, (const guchar*) g_mapped_file_get_contents (map), g_mapped_file_get_length (map), NULL); /* Make the call */ call = flickr_proxy_new_upload (proxy); param = rest_param_new_with_owner ("photo", g_mapped_file_get_contents (map), g_mapped_file_get_length (map), content_type, basename, map, (GDestroyNotify)g_mapped_file_unref); rest_proxy_call_add_param_full (call, param); g_free (basename); g_free (content_type); return call; } #if BUILD_TESTS void test_flickr_error (void) { RestXmlParser *parser; RestXmlNode *root; GError *error; const char test_1[] = "" ""; const char test_2[] = "" ""; const char test_3[] = "" ""; parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, test_1, sizeof (test_1) - 1); error = NULL; flickr_proxy_is_successful (root, &error); g_assert_no_error (error); rest_xml_node_unref (root); error = NULL; root = rest_xml_parser_parse_from_data (parser, test_2, sizeof (test_2) - 1); flickr_proxy_is_successful (root, &error); g_assert_error (error, FLICKR_PROXY_ERROR, 0); g_error_free (error); rest_xml_node_unref (root); error = NULL; root = rest_xml_parser_parse_from_data (parser, test_3, sizeof (test_3) - 1); flickr_proxy_is_successful (root, &error); g_assert_error (error, FLICKR_PROXY_ERROR, 108); g_error_free (error); rest_xml_node_unref (root); } #endif librest/rest-extras/Makefile.am0000664000175000017500000000561312014274314015132 0ustar bobbobCLEANFILES = lib_sources = \ flickr-proxy.c \ flickr-proxy-call.c \ flickr-proxy-private.h \ lastfm-proxy.c \ lastfm-proxy-call.c \ lastfm-proxy-private.h \ youtube-proxy.c \ youtube-proxy-private.h lib_headers = \ flickr-proxy.h \ flickr-proxy-call.h \ lastfm-proxy.h \ lastfm-proxy-call.h \ youtube-proxy.h lib_LTLIBRARIES = librest-extras-@API_VERSION@.la librest_extras_@API_VERSION@_la_CFLAGS = $(GLIB_CFLAGS) $(GTHREAD_CFLAGS) \ $(SOUP_CFLAGS) $(SOUP_GNOME_CFLAGS) \ $(XML_CFLAGS) $(GCOV_CFLAGS) \ -I$(top_srcdir) -Wall -DG_LOG_DOMAIN=\"Rest\" librest_extras_@API_VERSION@_la_LIBADD = $(GLIB_LIBS) $(GTHREAD_LIBS) \ $(SOUP_LIBS) $(SOUP_GNOME_LIBS) $(XML_LIBS) \ $(GCOV_LDFLAGS) \ $(top_builddir)/rest/librest-@API_VERSION@.la librest_extras_@API_VERSION@_la_LDFLAGS = -no-undefined librest_extras_@API_VERSION@_la_SOURCES = $(lib_sources) $(lib_headers) librest_extras_@API_VERSION@_la_HEADERS = $(lib_headers) librest_extras_@API_VERSION@_ladir = $(includedir)/rest-@API_VERSION@/rest-extras # Test suite TESTS = test-runner check_PROGRAMS = test-runner test_runner_SOURCES = test-runner.c $(lib_sources) $(lib_headers) test_runner_CFLAGS = -DBUILD_TESTS $(librest_extras_@API_VERSION@_la_CFLAGS) $(GCOV_CFLAGS) test_runner_LDFLAGS = $(librest_extras_@API_VERSION@_la_LIBADD) $(GCOV_LIBS) # TODO: use gtester # intospection -include $(INTROSPECTION_MAKEFILE) if HAVE_INTROSPECTION INTROSPECTION_GIRS = RestExtras-@API_VERSION@.gir # need to include ../rest when scanning/compiling INTROSPECTION_SCANNER_ARGS = --add-include-path=$(top_builddir)/rest --identifier-prefix= INTROSPECTION_COMPILER_ARGS = --includedir=$(top_builddir)/rest REST_EXTRAS_CINCLUDES=$(patsubst %,--c-include='rest/%',$(shell echo $(lib_headers))) INTROSPECTION_SCANNER_ARGS += $(REST_EXTRAS_CINCLUDES) RestExtras-@API_VERSION@.gir: librest-extras-@API_VERSION@.la Makefile RestExtras_@API_VERSION_AM@_gir_NAMESPACE = RestExtras RestExtras_@API_VERSION_AM@_gir_VERSION = @API_VERSION@ RestExtras_@API_VERSION_AM@_gir_LIBS = librest-extras-@API_VERSION@.la RestExtras_@API_VERSION_AM@_gir_FILES = \ $(lib_headers) \ $(filter-out %private.h, $(lib_sources)) RestExtras_@API_VERSION_AM@_gir_CFLAGS = -I$(top_srcdir) RestExtras_@API_VERSION_AM@_gir_INCLUDES = GObject-2.0 libxml2-2.0 RestExtras_@API_VERSION_AM@_gir_PACKAGES = gobject-2.0 libsoup-2.4 libxml-2.0 RestExtras_@API_VERSION_AM@_gir_SCANNERFLAGS = --include-uninstalled=$(top_builddir)/rest/Rest-@API_VERSION@.gir --accept-unprefixed RestExtras_@API_VERSION_AM@_gir_EXPORT_PACKAGES = rest-extras-@API_VERSION@ girdir = $(datadir)/gir-1.0 dist_gir_DATA = $(INTROSPECTION_GIRS) typelibsdir = $(libdir)/girepository-1.0/ typelibs_DATA = $(INTROSPECTION_GIRS:.gir=.typelib) CLEANFILES += $(dist_gir_DATA) $(typelibs_DATA) endif # HAVE_INTROSPECTION librest/rest-extras/flickr-proxy-call.h0000664000175000017500000000374712014274314016617 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _FLICKR_PROXY_CALL #define _FLICKR_PROXY_CALL #include G_BEGIN_DECLS #define FLICKR_TYPE_PROXY_CALL flickr_proxy_call_get_type() #define FLICKR_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLICKR_TYPE_PROXY_CALL, FlickrProxyCall)) #define FLICKR_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), FLICKR_TYPE_PROXY_CALL, FlickrProxyCallClass)) #define FLICKR_IS_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLICKR_TYPE_PROXY_CALL)) #define FLICKR_IS_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), FLICKR_TYPE_PROXY_CALL)) #define FLICKR_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), FLICKR_TYPE_PROXY_CALL, FlickrProxyCallClass)) /** * FlickrProxyCall: * * #FlickrProxyCall has no publicly available members. */ typedef struct { RestProxyCall parent; } FlickrProxyCall; typedef struct { RestProxyCallClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } FlickrProxyCallClass; GType flickr_proxy_call_get_type (void); G_END_DECLS #endif /* _FLICKR_PROXY_CALL */ librest/rest-extras/test-runner.c0000664000175000017500000000233012014274314015521 0ustar bobbob/* * librest - RESTful web services access * Copyright (C) 2009 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include #include #define test_add(unit_name, func) G_STMT_START { \ extern void func (void); \ g_test_add_func (unit_name, func); } G_STMT_END int main (int argc, char *argv[]) { g_type_init (); g_test_init (&argc, &argv, NULL); test_add ("/flickr/error", test_flickr_error); test_add ("/lastfm/error", test_flickr_error); return g_test_run (); } librest/rest-extras/youtube-proxy.c0000664000175000017500000003205112014274314016111 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include #include "rest/rest-private.h" #include "youtube-proxy.h" #include "youtube-proxy-private.h" G_DEFINE_TYPE (YoutubeProxy, youtube_proxy, REST_TYPE_PROXY) #define UPLOAD_URL \ "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads" enum { PROP_0, PROP_DEVELOPER_KEY, PROP_USER_AUTH, }; GQuark youtube_proxy_error_quark (void) { return g_quark_from_static_string ("rest-youtube-proxy"); } static void youtube_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { YoutubeProxyPrivate *priv = YOUTUBE_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_DEVELOPER_KEY: g_value_set_string (value, priv->developer_key); break; case PROP_USER_AUTH: g_value_set_string (value, priv->user_auth); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void youtube_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { YoutubeProxyPrivate *priv = YOUTUBE_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_DEVELOPER_KEY: g_free (priv->developer_key); priv->developer_key = g_value_dup_string (value); break; case PROP_USER_AUTH: g_free (priv->user_auth); priv->user_auth = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void youtube_proxy_finalize (GObject *object) { YoutubeProxyPrivate *priv = YOUTUBE_PROXY_GET_PRIVATE (object); g_free (priv->developer_key); g_free (priv->user_auth); G_OBJECT_CLASS (youtube_proxy_parent_class)->finalize (object); } static void youtube_proxy_class_init (YoutubeProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (YoutubeProxyPrivate)); object_class->get_property = youtube_proxy_get_property; object_class->set_property = youtube_proxy_set_property; object_class->finalize = youtube_proxy_finalize; pspec = g_param_spec_string ("developer-key", "developer-key", "The developer API key", NULL, G_PARAM_READWRITE| G_PARAM_CONSTRUCT_ONLY| G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_DEVELOPER_KEY, pspec); pspec = g_param_spec_string ("user-auth", "user-auth", "The ClientLogin token", NULL, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_USER_AUTH, pspec); } static void youtube_proxy_init (YoutubeProxy *self) { self->priv = YOUTUBE_PROXY_GET_PRIVATE (self); } RestProxy * youtube_proxy_new (const char *developer_key) { return youtube_proxy_new_with_auth (developer_key, NULL); } RestProxy * youtube_proxy_new_with_auth (const char *developer_key, const char *user_auth) { return g_object_new (YOUTUBE_TYPE_PROXY, "developer-key", developer_key, "user-auth", user_auth, NULL); } void youtube_proxy_set_user_auth (YoutubeProxy *proxy, const gchar *user_auth) { YoutubeProxyPrivate *priv = proxy->priv; priv->user_auth = g_strdup (user_auth); } static gchar * _construct_upload_atom_xml (GHashTable *fields, gboolean incomplete) { GHashTableIter iter; gpointer key, value; RestXmlNode *entry = rest_xml_node_add_child (NULL, "entry"); RestXmlNode *group = rest_xml_node_add_child (entry, "media:group"); gchar *bare_xml; gchar *full_xml; rest_xml_node_add_attr (entry, "xmlns", "http://www.w3.org/2005/Atom"); rest_xml_node_add_attr (entry, "xmlns:media", "http://search.yahoo.com/mrss/"); rest_xml_node_add_attr (entry, "xmlns:yt", "http://gdata.youtube.com/schemas/2007"); if (incomplete) rest_xml_node_add_child (group, "yt:incomplete"); g_hash_table_iter_init (&iter, fields); while (g_hash_table_iter_next (&iter, &key, &value)) { RestXmlNode *node; gchar *tag_name; const gchar* field_value = value; const gchar* field_key = key; tag_name = g_strdup_printf ("media:%s", field_key); node = rest_xml_node_add_child (group, tag_name); if (g_strcmp0 (field_key, "title") == 0 || g_strcmp0 (field_key, "description") == 0) rest_xml_node_add_attr (node, "type", "plain"); if (g_strcmp0 (field_key, "category") == 0) rest_xml_node_add_attr (node, "scheme", "http://gdata.youtube.com/" "schemas/2007/categories.cat"); rest_xml_node_set_content (node, field_value); } bare_xml = rest_xml_node_print (entry); full_xml = g_strdup_printf ("\n%s", bare_xml); rest_xml_node_unref (entry); g_free (bare_xml); return full_xml; } static void _set_upload_headers (YoutubeProxy *self, SoupMessageHeaders *headers, const gchar *filename) { YoutubeProxyPrivate *priv = self->priv; gchar *user_auth_header; gchar *devkey_header; gchar *basename; const gchar *user_agent; /* Set the user agent, if one was set in the proxy */ user_agent = rest_proxy_get_user_agent (REST_PROXY (self)); if (user_agent) soup_message_headers_append (headers, "User-Agent", user_agent); g_print ("%s\n", priv->user_auth); user_auth_header = g_strdup_printf ("GoogleLogin auth=%s", priv->user_auth); soup_message_headers_append (headers, "Authorization", user_auth_header); devkey_header = g_strdup_printf ("key=%s", priv->developer_key); soup_message_headers_append (headers, "X-GData-Key", devkey_header); basename = g_path_get_basename (filename); soup_message_headers_append (headers, "Slug", basename); g_free (user_auth_header); g_free (devkey_header); } typedef struct { YoutubeProxy *proxy; YoutubeProxyUploadCallback callback; SoupMessage *message; GObject *weak_object; gpointer user_data; gsize uploaded; } YoutubeProxyUploadClosure; static void _upload_async_weak_notify_cb (gpointer *data, GObject *dead_object) { YoutubeProxyUploadClosure *closure = (YoutubeProxyUploadClosure *) data; _rest_proxy_cancel_message (REST_PROXY (closure->proxy), closure->message); } static void _upload_async_closure_free (YoutubeProxyUploadClosure *closure) { if (closure->weak_object != NULL) g_object_weak_unref (closure->weak_object, (GWeakNotify) _upload_async_weak_notify_cb, closure); g_object_unref (closure->proxy); g_slice_free (YoutubeProxyUploadClosure, closure); } static YoutubeProxyUploadClosure * _upload_async_closure_new (YoutubeProxy *self, YoutubeProxyUploadCallback callback, SoupMessage *message, GObject *weak_object, gpointer user_data) { YoutubeProxyUploadClosure *closure = g_slice_new0 (YoutubeProxyUploadClosure); closure->proxy = g_object_ref (self); closure->callback = callback; closure->message = message; closure->weak_object = weak_object; closure->user_data = user_data; if (weak_object != NULL) g_object_weak_ref (weak_object, (GWeakNotify) _upload_async_weak_notify_cb, closure); return closure; } static void _upload_completed_cb (SoupSession *session, SoupMessage *message, gpointer user_data) { YoutubeProxyUploadClosure *closure = (YoutubeProxyUploadClosure *) user_data; GError *error = NULL; if (closure->callback == NULL) return; if (message->status_code < 200 || message->status_code >= 300) error = g_error_new_literal (REST_PROXY_ERROR, message->status_code, message->reason_phrase); closure->callback (closure->proxy, message->response_body->data, message->request_body->length, message->request_body->length, error, closure->weak_object, closure->user_data); _upload_async_closure_free (closure); } static void _message_wrote_data_cb (SoupMessage *msg, SoupBuffer *chunk, YoutubeProxyUploadClosure *closure) { closure->uploaded = closure->uploaded + chunk->length; if (closure->uploaded < msg->request_body->length) closure->callback (closure->proxy, NULL, msg->request_body->length, closure->uploaded, NULL, closure->weak_object, closure->user_data); } /** * youtube_proxy_upload_async: * @self: a #YoutubeProxy * @filename: filename * @fields: fields * @incomplete: incomplete * @callback: (scope async): callback to invoke upon completion * @weak_object: * @user_data: user data to pass to the callback * @error: a #GError pointer, or %NULL * * Upload a file. * * Returns: %TRUE, or %FALSE if the file could not be opened */ gboolean youtube_proxy_upload_async (YoutubeProxy *self, const gchar *filename, GHashTable *fields, gboolean incomplete, YoutubeProxyUploadCallback callback, GObject *weak_object, gpointer user_data, GError **error) { SoupMultipart *mp; SoupMessage *message; SoupMessageHeaders *part_headers; SoupBuffer *sb; gchar *content_type; gchar *atom_xml; GMappedFile *map; YoutubeProxyUploadClosure *closure; map = g_mapped_file_new (filename, FALSE, error); if (*error != NULL) { g_warning ("Error opening file %s: %s", filename, (*error)->message); return FALSE; } mp = soup_multipart_new ("multipart/related"); atom_xml = _construct_upload_atom_xml (fields, incomplete); sb = soup_buffer_new_with_owner (atom_xml, strlen(atom_xml), atom_xml, (GDestroyNotify) g_free); part_headers = soup_message_headers_new (SOUP_MESSAGE_HEADERS_MULTIPART); soup_message_headers_append (part_headers, "Content-Type", "application/atom+xml; charset=UTF-8"); soup_multipart_append_part (mp, part_headers, sb); soup_buffer_free (sb); content_type = g_content_type_guess ( filename, (const guchar*) g_mapped_file_get_contents (map), g_mapped_file_get_length (map), NULL); sb = soup_buffer_new_with_owner (g_mapped_file_get_contents (map), g_mapped_file_get_length (map), map, (GDestroyNotify) g_mapped_file_unref); soup_message_headers_replace (part_headers, "Content-Type", content_type); soup_multipart_append_part (mp, part_headers, sb); soup_buffer_free (sb); soup_message_headers_free (part_headers); message = soup_form_request_new_from_multipart (UPLOAD_URL, mp); soup_multipart_free (mp); _set_upload_headers (self, message->request_headers, filename); closure = _upload_async_closure_new (self, callback, message, weak_object, user_data); g_signal_connect (message, "wrote-body-data", (GCallback) _message_wrote_data_cb, closure); _rest_proxy_queue_message (REST_PROXY (self), message, _upload_completed_cb, closure); return TRUE; } librest/rest-extras/lastfm-proxy.c0000664000175000017500000002423312014274314015706 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include "lastfm-proxy.h" #include "lastfm-proxy-private.h" #include "lastfm-proxy-call.h" G_DEFINE_TYPE (LastfmProxy, lastfm_proxy, REST_TYPE_PROXY) enum { PROP_0, PROP_API_KEY, PROP_SECRET, PROP_SESSION_KEY, }; GQuark lastfm_proxy_error_quark (void) { return g_quark_from_static_string ("rest-lastfm-proxy"); } static RestProxyCall * _new_call (RestProxy *proxy) { RestProxyCall *call; call = g_object_new (LASTFM_TYPE_PROXY_CALL, "proxy", proxy, NULL); return call; } static void lastfm_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_API_KEY: g_value_set_string (value, priv->api_key); break; case PROP_SECRET: g_value_set_string (value, priv->secret); break; case PROP_SESSION_KEY: g_value_set_string (value, priv->session_key); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void lastfm_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_API_KEY: if (priv->api_key) g_free (priv->api_key); priv->api_key = g_value_dup_string (value); break; case PROP_SECRET: if (priv->secret) g_free (priv->secret); priv->secret = g_value_dup_string (value); break; case PROP_SESSION_KEY: if (priv->session_key) g_free (priv->session_key); priv->session_key = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void lastfm_proxy_finalize (GObject *object) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (object); g_free (priv->api_key); g_free (priv->secret); g_free (priv->session_key); G_OBJECT_CLASS (lastfm_proxy_parent_class)->finalize (object); } #ifndef G_PARAM_STATIC_STRINGS #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB) #endif static void lastfm_proxy_class_init (LastfmProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); RestProxyClass *proxy_class = REST_PROXY_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (LastfmProxyPrivate)); object_class->get_property = lastfm_proxy_get_property; object_class->set_property = lastfm_proxy_set_property; object_class->finalize = lastfm_proxy_finalize; proxy_class->new_call = _new_call; pspec = g_param_spec_string ("api-key", "api-key", "The API key", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_API_KEY, pspec); pspec = g_param_spec_string ("secret", "secret", "The API key secret", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_SECRET, pspec); pspec = g_param_spec_string ("session-key", "session-key", "The session key", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_SESSION_KEY, pspec); } static void lastfm_proxy_init (LastfmProxy *self) { self->priv = LASTFM_PROXY_GET_PRIVATE (self); } RestProxy * lastfm_proxy_new (const char *api_key, const char *secret) { return lastfm_proxy_new_with_session (api_key, secret, NULL); } RestProxy * lastfm_proxy_new_with_session (const char *api_key, const char *secret, const char *session_key) { return g_object_new (LASTFM_TYPE_PROXY, "api-key", api_key, "secret", secret, "session-key", session_key, "url-format", "http://ws.audioscrobbler.com/2.0/", "binding-required", FALSE, NULL); } /** * lastfm_proxy_get_api_key: * @proxy: an #LastfmProxy * * Get the API key. * * Returns: the API key. This string is owned by #LastfmProxy and should not be * freed. */ const char * lastfm_proxy_get_api_key (LastfmProxy *proxy) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (proxy); return priv->api_key; } /** * lastfm_proxy_get_secret: * @proxy: an #LastfmProxy * * Get the secret for authentication. * * Returns: the secret. This string is owned by #LastfmProxy and should not be * freed. */ const char * lastfm_proxy_get_secret (LastfmProxy *proxy) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (proxy); return priv->secret; } /** * lastfm_proxy_get_session_key: * @proxy: an #LastfmProxy * * Get the current session key. * * Returns: the session key, or %NULL if there is no session key yet. This string is owned * by #LastfmProxy and should not be freed. */ const char * lastfm_proxy_get_session_key (LastfmProxy *proxy) { LastfmProxyPrivate *priv = LASTFM_PROXY_GET_PRIVATE (proxy); return priv->session_key; } /** * lastfm_proxy_set_session_key: * @proxy: an #LastfmProxy * @session_key: the access session_key * * Set the session key. */ void lastfm_proxy_set_session_key (LastfmProxy *proxy, const char *session_key) { LastfmProxyPrivate *priv; g_return_if_fail (LASTFM_IS_PROXY (proxy)); priv = LASTFM_PROXY_GET_PRIVATE (proxy); if (priv->session_key) g_free (priv->session_key); priv->session_key = g_strdup (session_key); } char * lastfm_proxy_sign (LastfmProxy *proxy, GHashTable *params) { LastfmProxyPrivate *priv; GString *s; GList *keys; char *md5; g_return_val_if_fail (LASTFM_IS_PROXY (proxy), NULL); g_return_val_if_fail (params, NULL); priv = LASTFM_PROXY_GET_PRIVATE (proxy); s = g_string_new (NULL); keys = g_hash_table_get_keys (params); keys = g_list_sort (keys, (GCompareFunc)strcmp); while (keys) { const char *key; const char *value; key = keys->data; value = g_hash_table_lookup (params, key); g_string_append_printf (s, "%s%s", key, value); keys = g_list_delete_link (keys, keys); } g_string_append (s, priv->secret); md5 = g_compute_checksum_for_string (G_CHECKSUM_MD5, s->str, s->len); g_string_free (s, TRUE); return md5; } char * lastfm_proxy_build_login_url (LastfmProxy *proxy, const char *token) { g_return_val_if_fail (LASTFM_IS_PROXY (proxy), NULL); g_return_val_if_fail (token, NULL); return g_strdup_printf ("http://www.last.fm/api/auth/?api_key=%s&token=%s", proxy->priv->api_key, token); } /** * lastfm_proxy_is_successful: * @root: The root node of a parsed Lastfm response * @error: #GError to set if the response was an error * * Examines the Lastfm response and if it not a successful reply, set @error and * return FALSE. * * Returns: %TRUE if this response is successful, %FALSE otherwise. */ gboolean lastfm_proxy_is_successful (RestXmlNode *root, GError **error) { RestXmlNode *node; g_return_val_if_fail (root, FALSE); if (strcmp (root->name, "lfm") != 0) { g_set_error (error, LASTFM_PROXY_ERROR, 0, "Unexpected response from Lastfm (root node %s)", root->name); return FALSE; } if (strcmp (rest_xml_node_get_attr (root, "status"), "ok") != 0) { node = rest_xml_node_find (root, "error"); g_set_error_literal (error,LASTFM_PROXY_ERROR, atoi (rest_xml_node_get_attr (node, "code")), node->content); return FALSE; } return TRUE; } #if BUILD_TESTS void test_lastfm_error (void) { RestXmlParser *parser; RestXmlNode *root; GError *error; const char test_1[] = "" ""; const char test_2[] = "" "Invalid API Key"; const char test_3[] = "" "some data"; parser = rest_xml_parser_new (); error = NULL; root = rest_xml_parser_parse_from_data (parser, test_1, sizeof (test_1) - 1); lastfm_proxy_is_successful (root, &error); g_assert_error (error, LASTFM_PROXY_ERROR, 0); g_error_free (error); rest_xml_node_unref (root); root = rest_xml_parser_parse_from_data (parser, test_2, sizeof (test_2) - 1); error = NULL; lastfm_proxy_is_successful (root, &error); g_assert_error (error, LASTFM_PROXY_ERROR, 10); rest_xml_node_unref (root); error = NULL; root = rest_xml_parser_parse_from_data (parser, test_3, sizeof (test_3) - 1); lastfm_proxy_is_successful (root, &error); g_assert_no_error (error); g_error_free (error); rest_xml_node_unref (root); } #endif librest/rest-extras/lastfm-proxy-private.h0000664000175000017500000000212312014274314017355 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "lastfm-proxy.h" #define LASTFM_PROXY_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), LASTFM_TYPE_PROXY, LastfmProxyPrivate)) struct _LastfmProxyPrivate { char *api_key; char *secret; char *session_key; }; librest/rest-extras/lastfm-proxy.h0000664000175000017500000000544112014274314015713 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _LASTFM_PROXY #define _LASTFM_PROXY #include #include G_BEGIN_DECLS #define LASTFM_TYPE_PROXY lastfm_proxy_get_type() #define LASTFM_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), LASTFM_TYPE_PROXY, LastfmProxy)) #define LASTFM_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), LASTFM_TYPE_PROXY, LastfmProxyClass)) #define LASTFM_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), LASTFM_TYPE_PROXY)) #define LASTFM_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), LASTFM_TYPE_PROXY)) #define LASTFM_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), LASTFM_TYPE_PROXY, LastfmProxyClass)) typedef struct _LastfmProxyPrivate LastfmProxyPrivate; /** * LastfmProxy: * * #LastfmProxy has no publicly available members. */ typedef struct { RestProxy parent; LastfmProxyPrivate *priv; } LastfmProxy; typedef struct { RestProxyClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } LastfmProxyClass; #define LASTFM_PROXY_ERROR lastfm_proxy_error_quark() GType lastfm_proxy_get_type (void); RestProxy* lastfm_proxy_new (const char *api_key, const char *secret); RestProxy* lastfm_proxy_new_with_session (const char *api_key, const char *secret, const char *session_key); const char * lastfm_proxy_get_api_key (LastfmProxy *proxy); const char * lastfm_proxy_get_secret (LastfmProxy *proxy); const char * lastfm_proxy_get_session_key (LastfmProxy *proxy); void lastfm_proxy_set_session_key (LastfmProxy *proxy, const char *session_key); char * lastfm_proxy_sign (LastfmProxy *proxy, GHashTable *params); char * lastfm_proxy_build_login_url (LastfmProxy *proxy, const char *token); gboolean lastfm_proxy_is_successful (RestXmlNode *root, GError **error); G_END_DECLS #endif /* _LASTFM_PROXY */ librest/rest-extras/flickr-proxy-call.c0000664000175000017500000000737112014274314016607 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include "flickr-proxy-call.h" #include "flickr-proxy-private.h" #include "rest/rest-proxy-call-private.h" #include "rest/sha1.h" G_DEFINE_TYPE (FlickrProxyCall, flickr_proxy_call, REST_TYPE_PROXY_CALL) #define GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), FLICKR_TYPE_PROXY_CALL, FlickrProxyCallPrivate)) typedef struct { gboolean upload; } FlickrProxyCallPrivate; enum { PROP_0, PROP_UPLOAD }; static void flickr_proxy_call_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { case PROP_UPLOAD: GET_PRIVATE (object)->upload = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static gboolean _prepare (RestProxyCall *call, GError **error) { FlickrProxy *proxy = NULL; FlickrProxyPrivate *priv; RestProxyCallPrivate *call_priv; GHashTable *params; char *s; g_object_get (call, "proxy", &proxy, NULL); priv = FLICKR_PROXY_GET_PRIVATE (proxy); call_priv = call->priv; /* We need to reset the URL because Flickr puts the function in the parameters */ if (GET_PRIVATE (call)->upload) { call_priv->url = g_strdup ("http://api.flickr.com/services/upload/"); } else { call_priv->url = g_strdup ("http://api.flickr.com/services/rest/"); rest_proxy_call_add_param (call, "method", call_priv->function); } rest_proxy_call_add_param (call, "api_key", priv->api_key); if (priv->token) rest_proxy_call_add_param (call, "auth_token", priv->token); /* Get the string params as a hash for signing */ params = rest_params_as_string_hash_table (call_priv->params); s = flickr_proxy_sign (proxy, params); g_hash_table_unref (params); rest_proxy_call_add_param (call, "api_sig", s); g_free (s); g_object_unref (proxy); return TRUE; } static void flickr_proxy_call_class_init (FlickrProxyCallClass *klass) { RestProxyCallClass *call_class = REST_PROXY_CALL_CLASS (klass); GObjectClass *obj_class = G_OBJECT_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (FlickrProxyCallPrivate)); call_class->prepare = _prepare; obj_class->set_property = flickr_proxy_call_set_property; /** * FlickrProxyCall:upload: * * Set if the call should be sent to the photo upload endpoint and not the * general-purpose endpoint. */ pspec = g_param_spec_boolean ("upload", "upload", "upload", FALSE, G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_property (obj_class, PROP_UPLOAD, pspec); } static void flickr_proxy_call_init (FlickrProxyCall *self) { } #if BUILD_TESTS #warning TODO flickr signature test cases #endif librest/rest-extras/flickr-proxy.h0000664000175000017500000000605312014274314015677 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _FLICKR_PROXY #define _FLICKR_PROXY #include #include G_BEGIN_DECLS #define FLICKR_TYPE_PROXY flickr_proxy_get_type() #define FLICKR_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLICKR_TYPE_PROXY, FlickrProxy)) #define FLICKR_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), FLICKR_TYPE_PROXY, FlickrProxyClass)) #define FLICKR_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLICKR_TYPE_PROXY)) #define FLICKR_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), FLICKR_TYPE_PROXY)) #define FLICKR_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), FLICKR_TYPE_PROXY, FlickrProxyClass)) typedef struct _FlickrProxyPrivate FlickrProxyPrivate; /** * FlickrProxy: * * #FlickrProxy has no publicly available members. */ typedef struct { RestProxy parent; FlickrProxyPrivate *priv; } FlickrProxy; typedef struct { RestProxyClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } FlickrProxyClass; #define FLICKR_PROXY_ERROR flickr_proxy_error_quark() GType flickr_proxy_get_type (void); RestProxy* flickr_proxy_new (const char *api_key, const char *shared_secret); RestProxy* flickr_proxy_new_with_token (const char *api_key, const char *shared_secret, const char *token); const char * flickr_proxy_get_api_key (FlickrProxy *proxy); const char * flickr_proxy_get_shared_secret (FlickrProxy *proxy); const char * flickr_proxy_get_token (FlickrProxy *proxy); void flickr_proxy_set_token (FlickrProxy *proxy, const char *token); char * flickr_proxy_sign (FlickrProxy *proxy, GHashTable *params); char * flickr_proxy_build_login_url (FlickrProxy *proxy, const char *frob, const char *perms); gboolean flickr_proxy_is_successful (RestXmlNode *root, GError **error); RestProxyCall * flickr_proxy_new_upload (FlickrProxy *proxy); RestProxyCall * flickr_proxy_new_upload_for_file (FlickrProxy *proxy, const char *filename, GError **error); G_END_DECLS #endif /* _FLICKR_PROXY */ librest/rest-extras/lastfm-proxy-call.c0000664000175000017500000000467312014274314016625 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include "lastfm-proxy-call.h" #include "lastfm-proxy-private.h" #include "rest/rest-proxy-call-private.h" #include "rest/sha1.h" G_DEFINE_TYPE (LastfmProxyCall, lastfm_proxy_call, REST_TYPE_PROXY_CALL) static gboolean _prepare (RestProxyCall *call, GError **error) { LastfmProxy *proxy = NULL; LastfmProxyPrivate *priv; RestProxyCallPrivate *call_priv; GHashTable *params; char *s; g_object_get (call, "proxy", &proxy, NULL); priv = LASTFM_PROXY_GET_PRIVATE (proxy); call_priv = call->priv; /* First reset the URL because Lastfm puts the function in the parameters */ call_priv->url = g_strdup (_rest_proxy_get_bound_url (REST_PROXY (proxy))); rest_proxy_call_add_params (call, "method", call_priv->function, "api_key", priv->api_key, NULL); if (priv->session_key) rest_proxy_call_add_param (call, "sk", priv->session_key); params = rest_params_as_string_hash_table (call_priv->params); s = lastfm_proxy_sign (proxy, params); g_hash_table_unref (params); rest_proxy_call_add_param (call, "api_sig", s); g_free (s); g_object_unref (proxy); return TRUE; } static void lastfm_proxy_call_class_init (LastfmProxyCallClass *klass) { RestProxyCallClass *call_class = REST_PROXY_CALL_CLASS (klass); call_class->prepare = _prepare; } static void lastfm_proxy_call_init (LastfmProxyCall *self) { } #if BUILD_TESTS #warning TODO lastfm signature test cases #endif librest/rest-extras/youtube-proxy.h0000664000175000017500000000652112014274314016121 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _YOUTUBE_PROXY #define _YOUTUBE_PROXY #include G_BEGIN_DECLS #define YOUTUBE_TYPE_PROXY youtube_proxy_get_type() #define YOUTUBE_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), YOUTUBE_TYPE_PROXY, YoutubeProxy)) #define YOUTUBE_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), YOUTUBE_TYPE_PROXY, YoutubeProxyClass)) #define YOUTUBE_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), YOUTUBE_TYPE_PROXY)) #define YOUTUBE_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), YOUTUBE_TYPE_PROXY)) #define YOUTUBE_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), YOUTUBE_TYPE_PROXY, YoutubeProxyClass)) typedef struct _YoutubeProxyPrivate YoutubeProxyPrivate; /** * YoutubeProxy: * * #YoutubeProxy has no publicly available members. */ typedef struct { RestProxy parent; YoutubeProxyPrivate *priv; } YoutubeProxy; typedef struct { RestProxyClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } YoutubeProxyClass; #define YOUTUBE_PROXY_ERROR youtube_proxy_error_quark() GType youtube_proxy_get_type (void); RestProxy* youtube_proxy_new (const gchar *developer_key); RestProxy* youtube_proxy_new_with_auth (const gchar *developer_key, const gchar *user_auth); void youtube_proxy_set_user_auth (YoutubeProxy *proxy, const gchar *user_auth); typedef void (*YoutubeProxyUploadCallback)(YoutubeProxy *proxy, const gchar *payload, gsize total, gsize uploaded, const GError *error, GObject *weak_object, gpointer user_data); gboolean youtube_proxy_upload_async (YoutubeProxy *self, const gchar *filename, GHashTable *fields, gboolean incomplete, YoutubeProxyUploadCallback callback, GObject *weak_object, gpointer user_data, GError **error); G_END_DECLS #endif /* _YOUTUBE_PROXY */ librest/Makefile.am0000664000175000017500000000135212014274314012645 0ustar bobbobSUBDIRS = rest rest-extras examples docs tests %-$(API_VERSION).pc: %.pc $(AM_V_GEN)cp $< $@ pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = rest-$(API_VERSION).pc rest-extras-$(API_VERSION).pc CLEANFILES = $(pkgconfig_DATA) DISTCHECK_CONFIGURE_FLAGS = --enable-gtk-doc ACLOCAL_AMFLAGS = -I build ${ACLOCAL_FLAGS} all-local: rest-$(API_VERSION).pc rest-extras-$(API_VERSION).pc if GCOV_ENABLED cov-reset: @rm -fr coverage @find . -name "*.gcda" -exec rm {} \; @lcov --directory . --zerocounters cov-report: @mkdir -p coverage @lcov --compat-libtool --directory . --capture --output-file coverage/app.info @genhtml -o coverage/ coverage/app.info cov: @make cov-report clean-local: @make cov-reset check: @make cov endif librest/rest/0000775000175000017500000000000012014274315011566 5ustar bobboblibrest/rest/oauth-proxy.c0000664000175000017500000006232012014274314014233 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "oauth-proxy.h" #include "oauth-proxy-private.h" #include "oauth-proxy-call.h" G_DEFINE_TYPE (OAuthProxy, oauth_proxy, REST_TYPE_PROXY) enum { PROP_0, PROP_CONSUMER_KEY, PROP_CONSUMER_SECRET, PROP_TOKEN, PROP_TOKEN_SECRET, PROP_SIGNATURE_HOST, PROP_SIGNATURE_METHOD, }; static RestProxyCall * _new_call (RestProxy *proxy) { RestProxyCall *call; call = g_object_new (OAUTH_TYPE_PROXY_CALL, "proxy", proxy, NULL); return call; } static void oauth_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_CONSUMER_KEY: g_value_set_string (value, priv->consumer_key); break; case PROP_CONSUMER_SECRET: g_value_set_string (value, priv->consumer_secret); break; case PROP_TOKEN: g_value_set_string (value, priv->token); break; case PROP_TOKEN_SECRET: g_value_set_string (value, priv->token_secret); break; case PROP_SIGNATURE_HOST: g_value_set_string (value, priv->signature_host); break; case PROP_SIGNATURE_METHOD: g_value_set_enum (value, priv->method); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void oauth_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (object); switch (property_id) { case PROP_CONSUMER_KEY: if (priv->consumer_key) g_free (priv->consumer_key); priv->consumer_key = g_value_dup_string (value); break; case PROP_CONSUMER_SECRET: if (priv->consumer_secret) g_free (priv->consumer_secret); priv->consumer_secret = g_value_dup_string (value); break; case PROP_TOKEN: if (priv->token) g_free (priv->token); priv->token = g_value_dup_string (value); break; case PROP_TOKEN_SECRET: if (priv->token_secret) g_free (priv->token_secret); priv->token_secret = g_value_dup_string (value); break; case PROP_SIGNATURE_HOST: if (priv->signature_host) g_free (priv->signature_host); priv->signature_host = g_value_dup_string (value); break; case PROP_SIGNATURE_METHOD: priv->method = g_value_get_enum (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void oauth_proxy_finalize (GObject *object) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (object); g_free (priv->consumer_key); g_free (priv->consumer_secret); g_free (priv->token); g_free (priv->token_secret); g_free (priv->verifier); g_free (priv->service_url); G_OBJECT_CLASS (oauth_proxy_parent_class)->finalize (object); } #ifndef G_PARAM_STATIC_STRINGS #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB) #endif static void oauth_proxy_class_init (OAuthProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); RestProxyClass *proxy_class = REST_PROXY_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (OAuthProxyPrivate)); object_class->get_property = oauth_proxy_get_property; object_class->set_property = oauth_proxy_set_property; object_class->finalize = oauth_proxy_finalize; proxy_class->new_call = _new_call; pspec = g_param_spec_string ("consumer-key", "consumer-key", "The consumer key", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_CONSUMER_KEY, pspec); pspec = g_param_spec_string ("consumer-secret", "consumer-secret", "The consumer secret", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_CONSUMER_SECRET, pspec); pspec = g_param_spec_string ("token", "token", "The request or access token", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_TOKEN, pspec); pspec = g_param_spec_string ("token-secret", "token-secret", "The request or access token secret", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_TOKEN_SECRET, pspec); pspec = g_param_spec_string ("signature-host", "signature-host", "The base URL used in the signature string", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_SIGNATURE_HOST, pspec); pspec = g_param_spec_enum ("signature-method", "signature-method", "Signature method used", OAUTH_TYPE_SIGNATURE_METHOD, HMAC_SHA1, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_SIGNATURE_METHOD, pspec); } static void oauth_proxy_init (OAuthProxy *self) { PROXY_GET_PRIVATE (self)->method = HMAC_SHA1; } /** * oauth_proxy_new: * @consumer_key: the Consumer Key * @consumer_secret: the Consumer Secret * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * * Create a new #OAuthProxy for the specified endpoint @url_format, using the * specified API key and secret. * * This proxy won't have the Token or Token Secret set so as such will be * unauthorised. If the tokens are unknown then oauth_proxy_request_token() and * oauth_proxy_access_token() should be called to do the OAuth authorisation, or * the tokens should be set using oauth_proxy_set_token() and * oauth_proxy_set_token_secret(). * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #OAuthProxy. */ RestProxy * oauth_proxy_new (const char *consumer_key, const char *consumer_secret, const gchar *url_format, gboolean binding_required) { return g_object_new (OAUTH_TYPE_PROXY, "consumer-key", consumer_key, "consumer-secret", consumer_secret, "url-format", url_format, "binding-required", binding_required, NULL); } /** * oauth_proxy_new_with_token: * @consumer_key: the Consumer Key * @consumer_secret: the Consumer Secret * @token: the Access Token * @token_secret: the Token Secret * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * * Create a new #OAuthProxy for the specified endpoint @url_format, using the * specified API key and secret. * * @token and @token_secret are used for the Access Token and Token Secret, so * if they are still valid then this proxy is authorised. * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #OAuthProxy. */ RestProxy * oauth_proxy_new_with_token (const char *consumer_key, const char *consumer_secret, const char *token, const char *token_secret, const gchar *url_format, gboolean binding_required) { return g_object_new (OAUTH_TYPE_PROXY, "consumer-key", consumer_key, "consumer-secret", consumer_secret, "token", token, "token-secret", token_secret, "url-format", url_format, "binding-required", binding_required, NULL); } typedef struct { OAuthProxyAuthCallback callback; gpointer user_data; } AuthData; static void auth_callback (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer user_data) { AuthData *data = user_data; OAuthProxy *proxy = NULL; OAuthProxyPrivate *priv; GHashTable *form; g_object_get (call, "proxy", &proxy, NULL); priv = PROXY_GET_PRIVATE (proxy); if (!error) { /* TODO: sanity check response */ form = soup_form_decode (rest_proxy_call_get_payload (call)); priv->token = g_strdup (g_hash_table_lookup (form, "oauth_token")); priv->token_secret = g_strdup (g_hash_table_lookup (form, "oauth_token_secret")); g_hash_table_destroy (form); } data->callback (proxy, error, weak_object, data->user_data); g_slice_free (AuthData, data); g_object_unref (call); g_object_unref (proxy); } /** * oauth_proxy_auth_step_async: * @proxy: an #OAuthProxy * @function: the function to invoke on the proxy * @callback: the callback to invoke when authorisation is complete * @weak_object: the #GObject to weakly reference and tie the lifecycle too * @user_data: data to pass to @callback * @error_out: a #GError, or %NULL * * Perform an OAuth authorisation step. This calls @function and then updates * the token and token secret in the proxy. * * @proxy must not require binding, the function will be invoked using * rest_proxy_call_set_function(). */ gboolean oauth_proxy_auth_step_async (OAuthProxy *proxy, const char *function, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error_out) { RestProxyCall *call; AuthData *data; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function); data = g_slice_new0 (AuthData); data->callback = callback; data->user_data = user_data; return rest_proxy_call_async (call, auth_callback, weak_object, data, error_out); /* TODO: if call_async fails, the call is leaked */ } /** * oauth_proxy_auth_step: * @proxy: an #OAuthProxy * @function: the function to invoke on the proxy * @error: return location for a #GError * * Perform an OAuth authorisation step. This calls @function and then updates * the token and token secret in the proxy. * * @proxy must not require binding, the function will be invoked using * rest_proxy_call_set_function(). */ gboolean oauth_proxy_auth_step (OAuthProxy *proxy, const char *function, GError **error) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (proxy); RestProxyCall *call; GHashTable *form; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function); if (!rest_proxy_call_run (call, NULL, error)) { g_object_unref (call); return FALSE; } /* TODO: sanity check response */ form = soup_form_decode (rest_proxy_call_get_payload (call)); priv->token = g_strdup (g_hash_table_lookup (form, "oauth_token")); priv->token_secret = g_strdup (g_hash_table_lookup (form, "oauth_token_secret")); g_hash_table_destroy (form); g_object_unref (call); return TRUE; } /** * oauth_proxy_request_token: * @proxy: an #OAuthProxy * @function: the function name to invoke * @callback_uri: the callback URI * @error: a #GError, or %NULL * * Perform the Request Token phase of OAuth, invoking @function (defaulting to * "request_token" if @function is NULL). * * The value of @callback depends on whether you wish to use OAuth 1.0 or 1.0a. * If you wish to use 1.0 then callback must be NULL. To use 1.0a then * @callback should either be your callback URI, or "oob" (out-of-band). * * Returns: %TRUE on success, or %FALSE on failure. On failure @error is set. */ gboolean oauth_proxy_request_token (OAuthProxy *proxy, const char *function, /* NULL: 1.0 only, "oob", or URL */ const char *callback_uri, GError **error) { RestProxyCall *call; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function ? function : "request_token"); rest_proxy_call_set_method (call, "POST"); if (callback_uri) rest_proxy_call_add_param (call, "oauth_callback", callback_uri); if (!rest_proxy_call_run (call, NULL, error)) { g_object_unref (call); return FALSE; } /* TODO: sanity check response */ oauth_proxy_call_parse_token_reponse (OAUTH_PROXY_CALL (call)); g_object_unref (call); return TRUE; } static void request_token_cb (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer user_data) { AuthData *data = user_data; OAuthProxy *proxy = NULL; g_object_get (call, "proxy", &proxy, NULL); g_assert (proxy); if (!error) { oauth_proxy_call_parse_token_reponse (OAUTH_PROXY_CALL (call)); } data->callback (proxy, error, weak_object, data->user_data); g_slice_free (AuthData, data); g_object_unref (call); g_object_unref (proxy); } /** * oauth_proxy_request_token_async: * @proxy: an #OAuthProxy * @function: the function name to invoke * @callback_uri: the callback URI * @callback: a #OAuthProxyAuthCallback to invoke on completion * @weak_object: #GObject to weakly reference and tie the lifecycle of the method call too * @user_data: user data to pass to @callback * @error: a #GError, or %NULL * * Perform the Request Token phase of OAuth, invoking @function (defaulting to * "request_token" if @function is NULL). * * The value of @callback depends on whether you wish to use OAuth 1.0 or 1.0a. * If you wish to use 1.0 then callback must be NULL. To use 1.0a then * @callback should either be your callback URI, or "oob" (out-of-band). * * This method will return once the method has been queued, @callback will be * invoked when it has completed. * * Returns: %TRUE if the method was successfully queued, or %FALSE on * failure. On failure @error is set. */ gboolean oauth_proxy_request_token_async (OAuthProxy *proxy, const char *function, const char *callback_uri, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error) { RestProxyCall *call; AuthData *data; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function ? function : "request_token"); rest_proxy_call_set_method (call, "POST"); if (callback_uri) rest_proxy_call_add_param (call, "oauth_callback", callback_uri); data = g_slice_new0 (AuthData); data->callback = callback; data->user_data = user_data; return rest_proxy_call_async (call, request_token_cb, weak_object, data, error); } /** * oauth_proxy_access_token: * @proxy: an #OAuthProxy * @function: the function name to invoke * @verifier: the verifier * @error: a #GError, or %NULL * * Perform the Access Token phase of OAuth, invoking @function (defaulting to * "access_token" if @function is NULL). * * @verifier is only used if you are using OAuth 1.0a. This is either the * "oauth_verifier" parameter that was passed to your callback URI, or a string * that the user enters in some other manner (for example in a popup dialog) if * "oob" was passed to oauth_proxy_request_token(). For OAuth 1.0, pass %NULL. * * Returns: %TRUE on success, or %FALSE on failure. On failure @error is set. */ gboolean oauth_proxy_access_token (OAuthProxy *proxy, const char *function, const char *verifier, GError **error) { RestProxyCall *call; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function ? function : "access_token"); rest_proxy_call_set_method (call, "POST"); if (verifier) rest_proxy_call_add_param (call, "oauth_verifier", verifier); if (!rest_proxy_call_run (call, NULL, error)) { g_object_unref (call); return FALSE; } /* TODO: sanity check response */ oauth_proxy_call_parse_token_reponse (OAUTH_PROXY_CALL (call)); g_object_unref (call); return TRUE; } static void access_token_cb (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer user_data) { AuthData *data = user_data; OAuthProxy *proxy = NULL; g_object_get (call, "proxy", &proxy, NULL); g_assert (proxy); if (!error) { oauth_proxy_call_parse_token_reponse (OAUTH_PROXY_CALL (call)); } data->callback (proxy, error, weak_object, data->user_data); g_slice_free (AuthData, data); g_object_unref (call); g_object_unref (proxy); } /** * oauth_proxy_access_token_async: * @proxy: an #OAuthProxy * @function: the function name to invoke * @verifier: the verifier * @callback: a #OAuthProxyAuthCallback to invoke on completion * @weak_object: #GObject to weakly reference and tie the lifecycle of the method call too * @user_data: user data to pass to @callback * @error: a #GError, or %NULL * * Perform the Access Token phase of OAuth, invoking @function (defaulting to * "access_token" if @function is NULL). * * @verifier is only used if you are using OAuth 1.0a. This is either the * "oauth_verifier" parameter that was passed to your callback URI, or a string * that the user enters in some other manner (for example in a popup dialog) if * "oob" was passed to oauth_proxy_request_token(). For OAuth 1.0, pass %NULL. * * This method will return once the method has been queued, @callback will be * invoked when it has completed. * * Returns: %TRUE if the method was successfully queued, or %FALSE on * failure. On failure @error is set. */ gboolean oauth_proxy_access_token_async (OAuthProxy *proxy, const char *function, const char *verifier, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error) { RestProxyCall *call; AuthData *data; call = rest_proxy_new_call (REST_PROXY (proxy)); rest_proxy_call_set_function (call, function ? function : "access_token"); rest_proxy_call_set_method (call, "POST"); if (verifier) rest_proxy_call_add_param (call, "oauth_verifier", verifier); data = g_slice_new0 (AuthData); data->callback = callback; data->user_data = user_data; return rest_proxy_call_async (call, access_token_cb, weak_object, data, error); } /** * oauth_proxy_get_token: * @proxy: an #OAuthProxy * * Get the current request or access token. * * Returns: the token, or %NULL if there is no token yet. This string is owned * by #OAuthProxy and should not be freed. */ const char * oauth_proxy_get_token (OAuthProxy *proxy) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (proxy); return priv->token; } /** * oauth_proxy_set_token: * @proxy: an #OAuthProxy * @token: the access token * * Set the access token. */ void oauth_proxy_set_token (OAuthProxy *proxy, const char *token) { OAuthProxyPrivate *priv; g_return_if_fail (OAUTH_IS_PROXY (proxy)); priv = PROXY_GET_PRIVATE (proxy); if (priv->token) g_free (priv->token); priv->token = g_strdup (token); } /** * oauth_proxy_get_token_secret: * @proxy: an #OAuthProxy * * Get the current request or access token secret. * * Returns: the token secret, or %NULL if there is no token secret yet. This * string is owned by #OAuthProxy and should not be freed. */ const char * oauth_proxy_get_token_secret (OAuthProxy *proxy) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (proxy); return priv->token_secret; } /** * oauth_proxy_set_token_secret: * @proxy: an #OAuthProxy * @token_secret: the access token secret * * Set the access token secret. */ void oauth_proxy_set_token_secret (OAuthProxy *proxy, const char *token_secret) { OAuthProxyPrivate *priv; g_return_if_fail (OAUTH_IS_PROXY (proxy)); priv = PROXY_GET_PRIVATE (proxy); if (priv->token_secret) g_free (priv->token_secret); priv->token_secret = g_strdup (token_secret); } /** * oauth_proxy_is_oauth10a: * @proxy: a valid #OAuthProxy * * Determines if the server supports OAuth 1.0a with this proxy. This is only * valid after oauth_proxy_request_token() or oauth_proxy_request_token_async() * has been called. * * Returns: %TRUE if the server supports OAuth 1.0a, %FALSE otherwise. */ gboolean oauth_proxy_is_oauth10a (OAuthProxy *proxy) { g_return_val_if_fail (OAUTH_IS_PROXY (proxy), FALSE); return PROXY_GET_PRIVATE (proxy)->oauth_10a; } /** * oauth_proxy_get_signature_host: * @proxy: an #OAuthProxy * * Get the signature hostname used when creating a signature base string. * * Returns: the signature hostname, or %NULL if there is none set. * This string is owned by #OAuthProxy and should not be freed. */ const char * oauth_proxy_get_signature_host (OAuthProxy *proxy) { OAuthProxyPrivate *priv; g_return_val_if_fail (OAUTH_IS_PROXY (proxy), NULL); priv = PROXY_GET_PRIVATE (proxy); return priv->signature_host; } /** * oauth_proxy_set_signature_host: * @proxy: an #OAuthProxy * @signature_host: the signature host * * Set the signature hostname used when creating a signature base string. */ void oauth_proxy_set_signature_host (OAuthProxy *proxy, const char *signature_host) { OAuthProxyPrivate *priv; g_return_if_fail (OAUTH_IS_PROXY (proxy)); priv = PROXY_GET_PRIVATE (proxy); g_free (priv->signature_host); priv->signature_host = g_strdup (signature_host); } /** * oauth_proxy_new_echo_proxy: * @proxy: an #OAuthProxy * @service_url: the service URL * @url_format: the URL format * @binding_required: whether a binding is required * * Create a new OAuth * Echo proxy. * * Returns: (transfer full): a new OAuth Echo proxy */ RestProxy * oauth_proxy_new_echo_proxy (OAuthProxy *proxy, /* TODO: should this be a function on the base url? */ const char *service_url, const gchar *url_format, gboolean binding_required) { OAuthProxy *echo_proxy; OAuthProxyPrivate *priv, *echo_priv; g_return_val_if_fail (OAUTH_IS_PROXY (proxy), NULL); g_return_val_if_fail (service_url, NULL); g_return_val_if_fail (url_format, NULL); priv = PROXY_GET_PRIVATE (proxy); echo_proxy = g_object_new (OAUTH_TYPE_PROXY, "url-format", url_format, "binding-required", binding_required, "user-agent", rest_proxy_get_user_agent ((RestProxy *)proxy), "consumer-key", priv->consumer_key, "consumer-secret", priv->consumer_secret, "token", priv->token, "token-secret", priv->token_secret, NULL); echo_priv = PROXY_GET_PRIVATE (echo_proxy); echo_priv->oauth_echo = TRUE; echo_priv->service_url = g_strdup (service_url); return (RestProxy *)echo_proxy; } GType oauth_signature_method_get_type (void) { static GType enum_type_id = 0; if (G_UNLIKELY (!enum_type_id)) { static const GEnumValue values[] = { { PLAINTEXT, "PLAINTEXT", "plaintext" }, { HMAC_SHA1, "HMAC_SHA1", "hmac-sha1" }, { 0, NULL, NULL } }; enum_type_id = g_enum_register_static ("OAuthSignatureMethod", values); } return enum_type_id; } librest/rest/rest-proxy-call.c0000664000175000017500000012126112014274315015002 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include "rest-private.h" #include "rest-proxy-call-private.h" G_DEFINE_TYPE (RestProxyCall, rest_proxy_call, G_TYPE_OBJECT) #define GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), REST_TYPE_PROXY_CALL, RestProxyCallPrivate)) struct _RestProxyCallAsyncClosure { RestProxyCall *call; RestProxyCallAsyncCallback callback; GObject *weak_object; gpointer userdata; SoupMessage *message; }; struct _RestProxyCallContinuousClosure { RestProxyCall *call; RestProxyCallContinuousCallback callback; GObject *weak_object; gpointer userdata; SoupMessage *message; }; struct _RestProxyCallUploadClosure { RestProxyCall *call; RestProxyCallUploadCallback callback; GObject *weak_object; gpointer userdata; SoupMessage *message; gsize uploaded; }; enum { PROP_0 = 0, PROP_PROXY }; GQuark rest_proxy_call_error_quark (void) { return g_quark_from_static_string ("rest-proxy-call-error-quark"); } static void rest_proxy_call_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { RestProxyCallPrivate *priv = GET_PRIVATE (object); switch (property_id) { case PROP_PROXY: g_value_set_object (value, priv->proxy); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void rest_proxy_call_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { RestProxyCallPrivate *priv = GET_PRIVATE (object); switch (property_id) { case PROP_PROXY: priv->proxy = g_value_dup_object (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void rest_proxy_call_dispose (GObject *object) { RestProxyCallPrivate *priv = GET_PRIVATE (object); if (priv->params) { rest_params_free (priv->params); priv->params = NULL; } if (priv->headers) { g_hash_table_unref (priv->headers); priv->headers = NULL; } if (priv->response_headers) { g_hash_table_unref (priv->response_headers); priv->response_headers = NULL; } if (priv->proxy) { g_object_unref (priv->proxy); priv->proxy = NULL; } G_OBJECT_CLASS (rest_proxy_call_parent_class)->dispose (object); } static void rest_proxy_call_finalize (GObject *object) { RestProxyCallPrivate *priv = GET_PRIVATE (object); g_free (priv->method); g_free (priv->function); g_free (priv->payload); g_free (priv->status_message); g_free (priv->url); G_OBJECT_CLASS (rest_proxy_call_parent_class)->finalize (object); } static void rest_proxy_call_class_init (RestProxyCallClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (RestProxyCallPrivate)); object_class->get_property = rest_proxy_call_get_property; object_class->set_property = rest_proxy_call_set_property; object_class->dispose = rest_proxy_call_dispose; object_class->finalize = rest_proxy_call_finalize; pspec = g_param_spec_object ("proxy", "proxy", "Proxy for this call", REST_TYPE_PROXY, G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_PROXY, pspec); } static void rest_proxy_call_init (RestProxyCall *self) { RestProxyCallPrivate *priv = GET_PRIVATE (self); self->priv = priv; priv->method = g_strdup ("GET"); priv->params = rest_params_new (); priv->headers = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); priv->response_headers = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); } /** * rest_proxy_call_set_method: * @call: The #RestProxyCall * @method: The HTTP method to use * * Set the HTTP method to use when making the call, for example GET or POST. */ void rest_proxy_call_set_method (RestProxyCall *call, const gchar *method) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); g_free (priv->method); if (method) priv->method = g_strdup (method); else priv->method = g_strdup ("GET"); } /** * rest_proxy_call_get_method: * @call: The #RestProxyCall * * Get the HTTP method to use when making the call, for example GET or POST. */ const char * rest_proxy_call_get_method (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return priv->method; } /** * rest_proxy_call_set_function: * @call: The #RestProxyCall * @function: The function to call * * Set the REST "function" to call on the proxy. This is appended to the URL, * so that for example a proxy with the URL * http://www.example.com/ and the function * test would actually access the URL * http://www.example.com/test */ void rest_proxy_call_set_function (RestProxyCall *call, const gchar *function) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); g_free (priv->function); priv->function = g_strdup (function); } /** * rest_proxy_call_add_header: * @call: The #RestProxyCall * @header: The name of the header to set * @value: The value of the header * * Add a header called @header with the value @value to the call. If a * header with this name already exists, the new value will replace the old. */ void rest_proxy_call_add_header (RestProxyCall *call, const gchar *header, const gchar *value) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); g_hash_table_insert (priv->headers, g_strdup (header), g_strdup (value)); } /** * rest_proxy_call_add_headers: * @call: The #RestProxyCall * @Varargs: Header name and value pairs, followed by %NULL. * * Add the specified header name and value pairs to the call. If a header * already exists, the new value will replace the old. */ void rest_proxy_call_add_headers (RestProxyCall *call, ...) { va_list headers; g_return_if_fail (REST_IS_PROXY_CALL (call)); va_start (headers, call); rest_proxy_call_add_headers_from_valist (call, headers); va_end (headers); } /** * rest_proxy_call_add_headers_from_valist: * @call: The #RestProxyCall * @headers: Header name and value pairs, followed by %NULL. * * Add the specified header name and value pairs to the call. If a header * already exists, the new value will replace the old. */ void rest_proxy_call_add_headers_from_valist (RestProxyCall *call, va_list headers) { const gchar *header = NULL; const gchar *value = NULL; g_return_if_fail (REST_IS_PROXY_CALL (call)); while ((header = va_arg (headers, const gchar *)) != NULL) { value = va_arg (headers, const gchar *); rest_proxy_call_add_header (call, header, value); } } /** * rest_proxy_call_lookup_header: * @call: The #RestProxyCall * @header: The header name * * Get the value of the header called @header. * * Returns: The header value, or %NULL if it does not exist. This string is * owned by the #RestProxyCall and should not be freed. */ const gchar * rest_proxy_call_lookup_header (RestProxyCall *call, const gchar *header) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return g_hash_table_lookup (priv->headers, header); } /** * rest_proxy_call_remove_header: * @call: The #RestProxyCall * @header: The header name * * Remove the header named @header from the call. */ void rest_proxy_call_remove_header (RestProxyCall *call, const gchar *header) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); g_hash_table_remove (priv->headers, header); } /** * rest_proxy_call_add_param: * @call: The #RestProxyCall * @name: The name of the parameter to set * @value: The value of the parameter * * Add a query parameter called @param with the string value @value to the call. * If a parameter with this name already exists, the new value will replace the * old. */ void rest_proxy_call_add_param (RestProxyCall *call, const gchar *name, const gchar *value) { RestProxyCallPrivate *priv; RestParam *param; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); param = rest_param_new_string (name, REST_MEMORY_COPY, value); rest_params_add (priv->params, param); } void rest_proxy_call_add_param_full (RestProxyCall *call, RestParam *param) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); g_return_if_fail (param); priv = GET_PRIVATE (call); rest_params_add (priv->params, param); } /** * rest_proxy_call_add_params: * @call: The #RestProxyCall * @Varargs: Parameter name and value pairs, followed by %NULL. * * Add the specified parameter name and value pairs to the call. If a parameter * already exists, the new value will replace the old. */ void rest_proxy_call_add_params (RestProxyCall *call, ...) { va_list params; g_return_if_fail (REST_IS_PROXY_CALL (call)); va_start (params, call); rest_proxy_call_add_params_from_valist (call, params); va_end (params); } /** * rest_proxy_call_add_params_from_valist: * @call: The #RestProxyCall * @params: Parameter name and value pairs, followed by %NULL. * * Add the specified parameter name and value pairs to the call. If a parameter * already exists, the new value will replace the old. */ void rest_proxy_call_add_params_from_valist (RestProxyCall *call, va_list params) { const gchar *param = NULL; const gchar *value = NULL; g_return_if_fail (REST_IS_PROXY_CALL (call)); while ((param = va_arg (params, const gchar *)) != NULL) { value = va_arg (params, const gchar *); rest_proxy_call_add_param (call, param, value); } } /** * rest_proxy_call_lookup_param: * @call: The #RestProxyCall * @name: The paramter name * * Get the value of the parameter called @name. * * Returns: The parameter value, or %NULL if it does not exist. This string is * owned by the #RestProxyCall and should not be freed. */ RestParam * rest_proxy_call_lookup_param (RestProxyCall *call, const gchar *name) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return rest_params_get (priv->params, name); } /** * rest_proxy_call_remove_param: * @call: The #RestProxyCall * @name: The paramter name * * Remove the parameter named @name from the call. */ void rest_proxy_call_remove_param (RestProxyCall *call, const gchar *name) { RestProxyCallPrivate *priv; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); rest_params_remove (priv->params, name); } /** * rest_proxy_call_get_params: * @call: The #RestProxyCall * * Get the parameters as a #GHashTable of parameter names to values. The caller * should call g_hash_table_unref() when they have finished using it. * * Returns: A #GHashTable. */ RestParams * rest_proxy_call_get_params (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return priv->params; } static void _call_async_weak_notify_cb (gpointer *data, GObject *dead_object); static void _call_message_completed_cb (SoupSession *session, SoupMessage *message, gpointer userdata); static void _populate_headers_hash_table (const gchar *name, const gchar *value, gpointer userdata) { GHashTable *headers = (GHashTable *)userdata; g_hash_table_insert (headers, g_strdup (name), g_strdup (value)); } /* I apologise for this macro, but it saves typing ;-) */ #define error_helper(x) g_set_error_literal(error, REST_PROXY_ERROR, x, message->reason_phrase) static gboolean _handle_error_from_message (SoupMessage *message, GError **error) { if (message->status_code < 100) { switch (message->status_code) { case SOUP_STATUS_CANCELLED: error_helper (REST_PROXY_ERROR_CANCELLED); break; case SOUP_STATUS_CANT_RESOLVE: case SOUP_STATUS_CANT_RESOLVE_PROXY: error_helper (REST_PROXY_ERROR_RESOLUTION); break; case SOUP_STATUS_CANT_CONNECT: case SOUP_STATUS_CANT_CONNECT_PROXY: error_helper (REST_PROXY_ERROR_CONNECTION); break; case SOUP_STATUS_SSL_FAILED: error_helper (REST_PROXY_ERROR_SSL); break; case SOUP_STATUS_IO_ERROR: error_helper (REST_PROXY_ERROR_IO); break; case SOUP_STATUS_MALFORMED: case SOUP_STATUS_TRY_AGAIN: default: error_helper (REST_PROXY_ERROR_FAILED); break; } return FALSE; } if (message->status_code >= 200 && message->status_code < 300) { return TRUE; } /* If we are here we must be in some kind of HTTP error, lets try */ g_set_error_literal (error, REST_PROXY_ERROR, message->status_code, message->reason_phrase); return FALSE; } static gboolean finish_call (RestProxyCall *call, SoupMessage *message, GError **error) { RestProxyCallPrivate *priv; g_assert (call); g_assert (message); priv = GET_PRIVATE (call); /* Convert the soup headers in to hash */ /* FIXME: Eeek..are you allowed duplicate headers? ... */ g_hash_table_remove_all (priv->response_headers); soup_message_headers_foreach (message->response_headers, (SoupMessageHeadersForeachFunc)_populate_headers_hash_table, priv->response_headers); priv->payload = g_strdup (message->response_body->data); priv->length = message->response_body->length; priv->status_code = message->status_code; priv->status_message = g_strdup (message->reason_phrase); return _handle_error_from_message (message, error); } static void _call_message_completed_cb (SoupSession *session, SoupMessage *message, gpointer userdata) { RestProxyCallAsyncClosure *closure; RestProxyCall *call; RestProxyCallPrivate *priv; GError *error = NULL; closure = (RestProxyCallAsyncClosure *)userdata; call = closure->call; priv = GET_PRIVATE (call); finish_call (call, message, &error); closure->callback (closure->call, error, closure->weak_object, closure->userdata); g_clear_error (&error); /* Success. We don't need the weak reference any more */ if (closure->weak_object) { g_object_weak_unref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } priv->cur_call_closure = NULL; g_object_unref (closure->call); g_slice_free (RestProxyCallAsyncClosure, closure); } static void _continuous_call_message_completed_cb (SoupSession *session, SoupMessage *message, gpointer userdata) { RestProxyCallContinuousClosure *closure; RestProxyCall *call; RestProxyCallPrivate *priv; GError *error = NULL; closure = (RestProxyCallContinuousClosure *)userdata; call = closure->call; priv = GET_PRIVATE (call); priv->status_code = message->status_code; priv->status_message = g_strdup (message->reason_phrase); _handle_error_from_message (message, &error); closure->callback (closure->call, NULL, 0, error, closure->weak_object, closure->userdata); g_clear_error (&error); /* Success. We don't need the weak reference any more */ if (closure->weak_object) { g_object_weak_unref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } priv->cur_call_closure = NULL; g_object_unref (closure->call); g_slice_free (RestProxyCallContinuousClosure, closure); } static void _call_async_weak_notify_cb (gpointer *data, GObject *dead_object) { RestProxyCallAsyncClosure *closure; closure = (RestProxyCallAsyncClosure *)data; /* Will end up freeing the closure */ rest_proxy_call_cancel (closure->call); } static void set_header (gpointer key, gpointer value, gpointer user_data) { const char *name = key; SoupMessageHeaders *headers = user_data; soup_message_headers_replace (headers, name, value); } static SoupMessage * prepare_message (RestProxyCall *call, GError **error_out) { RestProxyCallPrivate *priv; RestProxyCallClass *call_class; const gchar *bound_url, *user_agent; SoupMessage *message; GError *error = NULL; priv = GET_PRIVATE (call); call_class = REST_PROXY_CALL_GET_CLASS (call); /* Emit a warning if the caller is re-using RestProxyCall objects */ if (priv->url) { g_warning (G_STRLOC ": re-use of RestProxyCall %p, don't do this", call); } bound_url =_rest_proxy_get_bound_url (priv->proxy); if (_rest_proxy_get_binding_required (priv->proxy) && !bound_url) { g_critical (G_STRLOC ": URL requires binding and is unbound"); return FALSE; } /* FIXME: Perhaps excessive memory duplication */ if (priv->function) { if (g_str_has_suffix (bound_url, "/")) { priv->url = g_strdup_printf ("%s%s", bound_url, priv->function); } else { priv->url = g_strdup_printf ("%s/%s", bound_url, priv->function); } } else { priv->url = g_strdup (bound_url); } /* Allow an overrideable prepare function that is called before every * invocation so subclasses can do magic */ if (call_class->prepare) { if (!call_class->prepare (call, &error)) { g_propagate_error (error_out, error); return NULL; } } if (call_class->serialize_params) { gchar *content; gchar *content_type; gsize content_len; if (!call_class->serialize_params (call, &content_type, &content, &content_len, &error)) { g_propagate_error (error_out, error); return NULL; } message = soup_message_new (priv->method, priv->url); soup_message_set_request (message, content_type, SOUP_MEMORY_TAKE, content, content_len); g_free (content_type); } else if (rest_params_are_strings (priv->params)) { GHashTable *hash; hash = rest_params_as_string_hash_table (priv->params); message = soup_form_request_new_from_hash (priv->method, priv->url, hash); g_hash_table_unref (hash); } else { SoupMultipart *mp; RestParamsIter iter; const char *name; RestParam *param; mp = soup_multipart_new (SOUP_FORM_MIME_TYPE_MULTIPART); rest_params_iter_init (&iter, priv->params); while (rest_params_iter_next (&iter, &name, ¶m)) { if (rest_param_is_string (param)) { soup_multipart_append_form_string (mp, name, rest_param_get_content (param)); } else { SoupBuffer *sb; sb = soup_buffer_new_with_owner (rest_param_get_content (param), rest_param_get_content_length (param), rest_param_ref (param), (GDestroyNotify)rest_param_unref); soup_multipart_append_form_file (mp, name, rest_param_get_file_name (param), rest_param_get_content_type (param), sb); soup_buffer_free (sb); } } message = soup_form_request_new_from_multipart (priv->url, mp); soup_multipart_free (mp); } /* Set the user agent, if one was set in the proxy */ user_agent = rest_proxy_get_user_agent (priv->proxy); if (user_agent) { soup_message_headers_append (message->request_headers, "User-Agent", user_agent); } /* Set the headers */ g_hash_table_foreach (priv->headers, set_header, message->request_headers); return message; } /** * rest_proxy_call_async: (skip): * @call: The #RestProxyCall * @callback: a #RestProxyCallAsyncCallback to invoke on completion of the call * @weak_object: The #GObject to weakly reference and tie the lifecycle too * @userdata: data to pass to @callback * @error: a #GError, or %NULL * * Asynchronously invoke @call. * * When the call has finished, @callback will be called. If @weak_object is * disposed during the call then this call will be cancelled. If the call is * cancelled then the callback will be invoked with an error state. * * You may unref the call after calling this function since there is an * internal reference, or you may unref in the callback. */ gboolean rest_proxy_call_async (RestProxyCall *call, RestProxyCallAsyncCallback callback, GObject *weak_object, gpointer userdata, GError **error) { RestProxyCallPrivate *priv; SoupMessage *message; RestProxyCallAsyncClosure *closure; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); priv = GET_PRIVATE (call); g_assert (priv->proxy); if (priv->cur_call_closure) { g_warning (G_STRLOC ": re-use of RestProxyCall %p, don't do this", call); return FALSE; } message = prepare_message (call, error); if (message == NULL) return FALSE; closure = g_slice_new0 (RestProxyCallAsyncClosure); closure->call = g_object_ref (call); closure->callback = callback; closure->weak_object = weak_object; closure->message = message; closure->userdata = userdata; priv->cur_call_closure = closure; /* Weakly reference this object. We remove our callback if it goes away. */ if (closure->weak_object) { g_object_weak_ref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } _rest_proxy_queue_message (priv->proxy, message, _call_message_completed_cb, closure); return TRUE; } static void _call_message_call_cancelled_cb (GCancellable *cancellable, RestProxyCall *call) { rest_proxy_call_cancel (call); } static void _call_message_call_completed_cb (SoupSession *session, SoupMessage *message, gpointer user_data) { GSimpleAsyncResult *result = user_data; RestProxyCall *call; GError *error = NULL; call = REST_PROXY_CALL ( g_async_result_get_source_object (G_ASYNC_RESULT (result))); // FIXME: disconnect cancellable ? finish_call (call, message, &error); if (error != NULL) g_simple_async_result_take_error (result, error); else g_simple_async_result_set_op_res_gboolean (result, TRUE); g_simple_async_result_complete (result); g_object_unref (call); g_object_unref (result); } /** * rest_proxy_call_invoke_async: * @call: a #RestProxyCall * @cancellable: (allow-none): an optional #GCancellable that can be used to * cancel the call, or %NULL * @callback: (scope async): callback to call when the async call is finished * @user_data: (closure): user data for the callback * * A GIO-style version of rest_proxy_call_async(). */ void rest_proxy_call_invoke_async (RestProxyCall *call, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *result; RestProxyCallPrivate *priv; SoupMessage *message; GError *error = NULL; g_return_if_fail (REST_IS_PROXY_CALL (call)); priv = GET_PRIVATE (call); g_assert (priv->proxy); message = prepare_message (call, &error); if (message == NULL) { g_simple_async_report_take_gerror_in_idle (G_OBJECT (call), callback, user_data, error); return; } result = g_simple_async_result_new (G_OBJECT (call), callback, user_data, rest_proxy_call_invoke_async); if (cancellable != NULL) g_signal_connect (cancellable, "cancelled", G_CALLBACK (_call_message_call_cancelled_cb), call); _rest_proxy_queue_message (priv->proxy, message, _call_message_call_completed_cb, result); } /** * rest_proxy_call_invoke_finish: * @call: a #RestProxyCall * @result: the result from the #GAsyncReadyCallback * @error: optional #GError * * Returns: %TRUE on success */ gboolean rest_proxy_call_invoke_finish (RestProxyCall *call, GAsyncResult *result, GError **error) { GSimpleAsyncResult *simple; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE); simple = G_SIMPLE_ASYNC_RESULT (result); g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (call), rest_proxy_call_invoke_async), FALSE); if (g_simple_async_result_propagate_error (simple, error)) return FALSE; return g_simple_async_result_get_op_res_gboolean (simple); } static void _continuous_call_message_got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, RestProxyCallContinuousClosure *closure) { closure->callback (closure->call, chunk->data, chunk->length, NULL, closure->weak_object, closure->userdata); } /** * rest_proxy_call_continuous: * @call: The #RestProxyCall * @callback: a #RestProxyCallContinuousCallback to invoke when data is available * @weak_object: The #GObject to weakly reference and tie the lifecycle to * @userdata: data to pass to @callback * @error: a #GError, or %NULL * * Asynchronously invoke @call but expect a continuous stream of content. This * means that the body data will not be accumulated and thus you cannot use * rest_proxy_call_get_payload() * * When there is data @callback will be called and when the connection is * closed or the stream ends @callback will also be called. * * If @weak_object is disposed during the call then this call will be * cancelled. If the call is cancelled then the callback will be invoked with * an error state. * * You may unref the call after calling this function since there is an * internal reference, or you may unref in the callback. */ gboolean rest_proxy_call_continuous (RestProxyCall *call, RestProxyCallContinuousCallback callback, GObject *weak_object, gpointer userdata, GError **error) { RestProxyCallPrivate *priv; SoupMessage *message; RestProxyCallContinuousClosure *closure; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); priv = GET_PRIVATE (call); g_assert (priv->proxy); if (priv->cur_call_closure) { g_warning (G_STRLOC ": re-use of RestProxyCall %p, don't do this", call); return FALSE; } message = prepare_message (call, error); if (message == NULL) return FALSE; /* Must turn off accumulation */ soup_message_body_set_accumulate (message->response_body, FALSE); closure = g_slice_new0 (RestProxyCallContinuousClosure); closure->call = g_object_ref (call); closure->callback = callback; closure->weak_object = weak_object; closure->message = message; closure->userdata = userdata; priv->cur_call_closure = (RestProxyCallAsyncClosure *)closure; /* Weakly reference this object. We remove our callback if it goes away. */ if (closure->weak_object) { g_object_weak_ref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } g_signal_connect (message, "got-chunk", (GCallback)_continuous_call_message_got_chunk_cb, closure); _rest_proxy_queue_message (priv->proxy, message, _continuous_call_message_completed_cb, closure); return TRUE; } static void _upload_call_message_completed_cb (SoupSession *session, SoupMessage *message, gpointer user_data) { RestProxyCall *call; RestProxyCallPrivate *priv; GError *error = NULL; RestProxyCallUploadClosure *closure; closure = (RestProxyCallUploadClosure *) user_data; call = closure->call; priv = GET_PRIVATE (call); priv->status_code = message->status_code; priv->status_message = g_strdup (message->reason_phrase); _handle_error_from_message (message, &error); closure->callback (closure->call, closure->uploaded, closure->uploaded, error, closure->weak_object, closure->userdata); g_clear_error (&error); /* Success. We don't need the weak reference any more */ if (closure->weak_object) { g_object_weak_unref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } priv->cur_call_closure = NULL; g_object_unref (closure->call); g_slice_free (RestProxyCallUploadClosure, closure); } static void _upload_call_message_wrote_data_cb (SoupMessage *msg, SoupBuffer *chunk, RestProxyCallUploadClosure *closure) { closure->uploaded = closure->uploaded + chunk->length; if (closure->uploaded < msg->request_body->length) closure->callback (closure->call, msg->request_body->length, closure->uploaded, NULL, closure->weak_object, closure->userdata); } /** * rest_proxy_call_upload: * @call: The #RestProxyCall * @callback: a #RestProxyCallUploadCallback to invoke when a chunk of data was * uploaded * @weak_object: The #GObject to weakly reference and tie the lifecycle to * @userdata: data to pass to @callback * @error: a #GError, or %NULL * * Asynchronously invoke @call but expect to have the callback invoked every time a * chunk of our request's body is written. * * When the callback is invoked with the uploaded byte count equaling the message * byte count, the call has completed. * * If @weak_object is disposed during the call then this call will be * cancelled. If the call is cancelled then the callback will be invoked with * an error state. * * You may unref the call after calling this function since there is an * internal reference, or you may unref in the callback. */ gboolean rest_proxy_call_upload (RestProxyCall *call, RestProxyCallUploadCallback callback, GObject *weak_object, gpointer userdata, GError **error) { RestProxyCallPrivate *priv; SoupMessage *message; RestProxyCallUploadClosure *closure; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); priv = GET_PRIVATE (call); g_assert (priv->proxy); if (priv->cur_call_closure) { g_warning (G_STRLOC ": re-use of RestProxyCall %p, don't do this", call); return FALSE; } message = prepare_message (call, error); if (message == NULL) return FALSE; closure = g_slice_new0 (RestProxyCallUploadClosure); closure->call = g_object_ref (call); closure->callback = callback; closure->weak_object = weak_object; closure->message = message; closure->userdata = userdata; closure->uploaded = 0; priv->cur_call_closure = (RestProxyCallAsyncClosure *)closure; /* Weakly reference this object. We remove our callback if it goes away. */ if (closure->weak_object) { g_object_weak_ref (closure->weak_object, (GWeakNotify)_call_async_weak_notify_cb, closure); } g_signal_connect (message, "wrote-body-data", (GCallback) _upload_call_message_wrote_data_cb, closure); _rest_proxy_queue_message (priv->proxy, message, _upload_call_message_completed_cb, closure); return TRUE; } /** * rest_proxy_call_cancel: (skip): * @call: The #RestProxyCall * * Cancel this call. It may be too late to not actually send the message, but * the callback will not be invoked. * * N.B. this method should only be used with rest_proxy_call_async() and NOT * rest_proxy_call_invoke_async(). */ gboolean rest_proxy_call_cancel (RestProxyCall *call) { RestProxyCallPrivate *priv; RestProxyCallAsyncClosure *closure; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); priv = GET_PRIVATE (call); closure = priv->cur_call_closure; if (closure) { /* This will cause the _call_message_completed_cb to be fired which will * tidy up the closure and so forth */ _rest_proxy_cancel_message (priv->proxy, closure->message); } return TRUE; } typedef struct { GMainLoop *loop; GError *error; } RestProxyCallRunClosure; static void _rest_proxy_call_async_cb (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer userdata) { RestProxyCallRunClosure *closure = (RestProxyCallRunClosure *)userdata; /* *duplicate* not propagate the error */ if (error) closure->error = g_error_copy (error); g_main_loop_quit (closure->loop); } gboolean rest_proxy_call_run (RestProxyCall *call, GMainLoop **loop_out, GError **error_out) { gboolean res = TRUE; GError *error = NULL; RestProxyCallRunClosure closure = { NULL, NULL}; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); closure.loop = g_main_loop_new (NULL, FALSE); if (loop_out) *loop_out = closure.loop; res = rest_proxy_call_async (call, _rest_proxy_call_async_cb, NULL, &closure, &error); if (!res) { g_propagate_error (error_out, error); goto error; } g_main_loop_run (closure.loop); if (closure.error) { /* If the caller has asked for the error then propagate else free it */ if (error_out) { g_propagate_error (error_out, closure.error); } else { g_clear_error (&(closure.error)); } res = FALSE; } error: g_main_loop_unref (closure.loop); return res; } gboolean rest_proxy_call_sync (RestProxyCall *call, GError **error_out) { RestProxyCallPrivate *priv; SoupMessage *message; gboolean ret; g_return_val_if_fail (REST_IS_PROXY_CALL (call), FALSE); priv = GET_PRIVATE (call); message = prepare_message (call, error_out); if (!message) return FALSE; _rest_proxy_send_message (priv->proxy, message); ret = finish_call (call, message, error_out); g_object_unref (message); return ret; } /** * rest_proxy_call_lookup_response_header: * @call: The #RestProxyCall * @header: The name of the header to lookup. * * Get the string value of the header @header or %NULL if that header is not * present or there are no headers. */ const gchar * rest_proxy_call_lookup_response_header (RestProxyCall *call, const gchar *header) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); if (!priv->response_headers) { return NULL; } return g_hash_table_lookup (priv->response_headers, header); } /** * rest_proxy_call_get_response_headers: * @call: The #RestProxyCall * * Returns: (transfer container): pointer to a hash table of * headers. This hash table must not be changed. You should call * g_hash_table_unref() when you have finished with it. */ GHashTable * rest_proxy_call_get_response_headers (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); if (!priv->response_headers) { return NULL; } return g_hash_table_ref (priv->response_headers); } /** * rest_proxy_call_get_payload_length: * @call: The #RestProxyCall * * Get the length of the return payload. * * Returns: the length of the payload in bytes. */ goffset rest_proxy_call_get_payload_length (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), 0); priv = GET_PRIVATE (call); return priv->length; } /** * rest_proxy_call_get_payload: * @call: The #RestProxyCall * * Get the return payload. * * Returns: A pointer to the payload. This is owned by #RestProxyCall and should * not be freed. */ const gchar * rest_proxy_call_get_payload (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return priv->payload; } /** * rest_proxy_call_get_status_code: * @call: The #RestProxyCall * * Get the HTTP status code for the call. */ guint rest_proxy_call_get_status_code (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), 0); priv = GET_PRIVATE (call); return priv->status_code; } /** * rest_proxy_call_get_status_message: * @call: The #RestProxyCall * * Get the human-readable HTTP status message for the call. * * Returns: The status message. This string is owned by #RestProxyCall and * should not be freed. */ const gchar * rest_proxy_call_get_status_message (RestProxyCall *call) { RestProxyCallPrivate *priv; g_return_val_if_fail (REST_IS_PROXY_CALL (call), NULL); priv = GET_PRIVATE (call); return priv->status_message; } /** * rest_proxy_call_serialize_params: * @call: The #RestProxyCall * @content_type: (out): Content type of the payload * @content: (out): The payload * @content_len: (out): Length of the payload data * @error: a #GError, or %NULL * * Invoker for a virtual method to serialize the parameters for this * #RestProxyCall. * * Returns: TRUE if the serialization was successful, FALSE otherwise. */ gboolean rest_proxy_call_serialize_params (RestProxyCall *call, gchar **content_type, gchar **content, gsize *content_len, GError **error) { RestProxyCallClass *call_class; call_class = REST_PROXY_CALL_GET_CLASS (call); if (call_class->serialize_params) { return call_class->serialize_params (call, content_type, content, content_len, error); } return FALSE; } librest/rest/rest-params.h0000664000175000017500000000322612014274315014200 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PARAMS #define _REST_PARAMS #include #include "rest-param.h" G_BEGIN_DECLS typedef struct _RestParams RestParams; typedef struct _GHashTableIter RestParamsIter; RestParams * rest_params_new (void); void rest_params_free (RestParams *params); void rest_params_add (RestParams *params, RestParam *param); RestParam *rest_params_get (RestParams *params, const char *name); void rest_params_remove (RestParams *params, const char *name); gboolean rest_params_are_strings (RestParams *params); GHashTable * rest_params_as_string_hash_table (RestParams *params); void rest_params_iter_init (RestParamsIter *iter, RestParams *params); gboolean rest_params_iter_next (RestParamsIter *iter, const char **name, RestParam **param); G_END_DECLS #endif /* _REST_PARAMS */ librest/rest/rest-xml-node.c0000664000175000017500000002270512014274315014436 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2011, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Tomas Frydrych * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "rest-xml-node.h" #define G(x) (gchar *)x static RestXmlNode * rest_xml_node_reverse_siblings (RestXmlNode *current) { RestXmlNode *next; RestXmlNode *prev = NULL; while (current) { next = current->next; current->next = prev; prev = current; current = next; } return prev; } void _rest_xml_node_reverse_children_siblings (RestXmlNode *node) { GList *l, *children; RestXmlNode *new_node; children = g_hash_table_get_values (node->children); for (l = children; l; l = l->next) { new_node = rest_xml_node_reverse_siblings ((RestXmlNode *)l->data); g_hash_table_insert (node->children, new_node->name, new_node); } if (children) g_list_free (children); } /* * _rest_xml_node_prepend: * @cur_node: a sibling #RestXmlNode to prepend the new before * @new_node: new #RestXmlNode to prepend to the siblings list * * Prepends new_node to the list of siblings starting at cur_node. * * Return value: (transfer none): returns new start of the sibling list */ RestXmlNode * _rest_xml_node_prepend (RestXmlNode *cur_node, RestXmlNode *new_node) { g_assert (new_node->next == NULL); new_node->next = cur_node; return new_node; } /* * rest_xml_node_append_end: * @cur_node: a member of the sibling #RestXmlNode list * @new_node: new #RestXmlNode to append to the siblings list * * Appends new_node to end of the list of siblings containing cur_node. */ static void rest_xml_node_append_end (RestXmlNode *cur_node, RestXmlNode *new_node) { RestXmlNode *tmp = cur_node; g_return_if_fail (cur_node); while (tmp->next) tmp = tmp->next; tmp->next = new_node; } GType rest_xml_node_get_type (void) { static GType type = 0; if (G_UNLIKELY (type == 0)) { type = g_boxed_type_register_static ("RestXmlNode", (GBoxedCopyFunc)rest_xml_node_ref, (GBoxedFreeFunc)rest_xml_node_unref); } return type; } /* * _rest_xml_node_new: * * Creates a new instance of #RestXmlNode. * * Return value: (transfer full): newly allocated #RestXmlNode. */ RestXmlNode * _rest_xml_node_new () { RestXmlNode *node; node = g_slice_new0 (RestXmlNode); node->ref_count = 1; node->children = g_hash_table_new (NULL, NULL); node->attrs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); return node; } /** * rest_xml_node_ref: (skip): * @node: a #RestXmlNode * * Increases the reference count of @node. * * Returns: the same @node. */ RestXmlNode * rest_xml_node_ref (RestXmlNode *node) { g_return_val_if_fail (node, NULL); g_return_val_if_fail (node->ref_count > 0, NULL); g_atomic_int_inc (&node->ref_count); return node; } /** * rest_xml_node_unref: (skip): * @node: a #RestXmlNode * * Decreases the reference count of @node. When its reference count drops to 0, * the node is finalized (i.e. its memory is freed). */ void rest_xml_node_unref (RestXmlNode *node) { GList *l; RestXmlNode *next = NULL; g_return_if_fail (node); g_return_if_fail (node->ref_count > 0); /* Try and unref the chain, this is equivalent to being tail recursively * unreffing the next pointer */ while (node && g_atomic_int_dec_and_test (&node->ref_count)) { /* * Save this pointer now since we are going to free the structure it * contains soon. */ next = node->next; l = g_hash_table_get_values (node->children); while (l) { rest_xml_node_unref ((RestXmlNode *)l->data); l = g_list_delete_link (l, l); } g_hash_table_unref (node->children); g_hash_table_unref (node->attrs); g_free (node->content); g_slice_free (RestXmlNode, node); /* * Free the next in the chain by updating node. If we're at the end or * there are no siblings then the next = NULL definition deals with this * case */ node = next; } } G_GNUC_DEPRECATED void rest_xml_node_free (RestXmlNode *node) { rest_xml_node_unref (node); } /** * rest_xml_node_get_attr: * @node: a #RestXmlNode * @attr_name: the name of an attribute * * Get the value of the attribute named @attr_name, or %NULL if it doesn't * exist. * * Returns: the attribute value. This string is owned by #RestXmlNode and should * not be freed. */ const gchar * rest_xml_node_get_attr (RestXmlNode *node, const gchar *attr_name) { return g_hash_table_lookup (node->attrs, attr_name); } /** * rest_xml_node_find: * @start: a #RestXmlNode * @tag: the name of a node * * Searches for the first child node of @start named @tag. * * Returns: the first child node, or %NULL if it doesn't exist. */ RestXmlNode * rest_xml_node_find (RestXmlNode *start, const gchar *tag) { RestXmlNode *node; RestXmlNode *tmp; GQueue stack = G_QUEUE_INIT; GList *children, *l; const char *tag_interned; g_return_val_if_fail (start, NULL); g_return_val_if_fail (start->ref_count > 0, NULL); tag_interned = g_intern_string (tag); g_queue_push_head (&stack, start); while ((node = g_queue_pop_head (&stack)) != NULL) { if ((tmp = g_hash_table_lookup (node->children, tag_interned)) != NULL) { g_queue_clear (&stack); return tmp; } children = g_hash_table_get_values (node->children); for (l = children; l; l = l->next) { g_queue_push_head (&stack, l->data); } g_list_free (children); } g_queue_clear (&stack); return NULL; } /** * rest_xml_node_print_node: * @node: #RestXmlNode * * Recursively outputs given node and it's children. * * Return value: (transfer: full): xml string representing the node. */ char * rest_xml_node_print (RestXmlNode *node) { GHashTableIter iter; gpointer key, value; char *xml = g_strconcat ("<", node->name, NULL); RestXmlNode *n; g_hash_table_iter_init (&iter, node->attrs); while (g_hash_table_iter_next (&iter, &key, &value)) xml = g_strconcat (xml, " ", key, "=\'", value, "\'", NULL); xml = g_strconcat (xml, ">", NULL); g_hash_table_iter_init (&iter, node->children); while (g_hash_table_iter_next (&iter, &key, &value)) { char *child = rest_xml_node_print ((RestXmlNode *) value); xml = g_strconcat (xml, child, NULL); g_free (child); } if (node->content) xml = g_strconcat (xml, node->content, "name, ">", NULL); else xml = g_strconcat (xml, "name, ">", NULL); for (n = node->next; n; n = n->next) { char *sibling = rest_xml_node_print (n); xml = g_strconcat (xml, sibling, NULL); g_free (sibling); } return xml; } /** * rest_xml_node_add_child: * @parent: parent #RestXmlNode, or %NULL for the top-level node * @tag: name of the child node * * Adds a new node to the given parent node; to create the top-level node, * parent should be %NULL. * * Return value: (transfer none): the newly added #RestXmlNode; the node object * is owned by, and valid for the life time of, the #RestXmlCreator. */ RestXmlNode * rest_xml_node_add_child (RestXmlNode *parent, const char *tag) { RestXmlNode *node; char *escaped; g_return_val_if_fail (tag && *tag, NULL); escaped = g_markup_escape_text (tag, -1); node = _rest_xml_node_new (); node->name = (char *) g_intern_string (escaped); if (parent) { RestXmlNode *tmp_node; tmp_node = g_hash_table_lookup (parent->children, node->name); if (tmp_node) { rest_xml_node_append_end (tmp_node, node); } else { g_hash_table_insert (parent->children, G(node->name), node); } } g_free (escaped); return node; } /** * rest_xml_node_add_attr: * @node: #RestXmlNode to add attribute to * @attribute: name of the attribute * @value: value to set attribute to * * Adds attribute to the given node. */ void rest_xml_node_add_attr (RestXmlNode *node, const char *attribute, const char *value) { g_return_if_fail (node && attribute && *attribute); g_hash_table_insert (node->attrs, g_markup_escape_text (attribute, -1), g_markup_escape_text (value, -1)); } /** * rest_xml_node_set_content: * @node: #RestXmlNode to set content * @value: the content * * Sets content for the given node. */ void rest_xml_node_set_content (RestXmlNode *node, const char *value) { g_return_if_fail (node && value && *value); g_free (node->content); node->content = g_markup_escape_text (value, -1); } librest/rest/rest-proxy.c0000664000175000017500000005117112014274315014073 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #if WITH_GNOME #include #endif #include "rest-proxy-auth-private.h" #include "rest-proxy.h" #include "rest-private.h" G_DEFINE_TYPE (RestProxy, rest_proxy, G_TYPE_OBJECT) #define GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), REST_TYPE_PROXY, RestProxyPrivate)) typedef struct _RestProxyPrivate RestProxyPrivate; struct _RestProxyPrivate { gchar *url_format; gchar *url; gchar *user_agent; gchar *username; gchar *password; gboolean binding_required; SoupSession *session; SoupSession *session_sync; gboolean disable_cookies; }; enum { PROP0 = 0, PROP_URL_FORMAT, PROP_BINDING_REQUIRED, PROP_USER_AGENT, PROP_DISABLE_COOKIES, PROP_USERNAME, PROP_PASSWORD, PROP_SSL_STRICT }; enum { AUTHENTICATE, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; static gboolean _rest_proxy_simple_run_valist (RestProxy *proxy, char **payload, goffset *len, GError **error, va_list params); static RestProxyCall *_rest_proxy_new_call (RestProxy *proxy); static gboolean _rest_proxy_bind_valist (RestProxy *proxy, va_list params); GQuark rest_proxy_error_quark (void) { return g_quark_from_static_string ("rest-proxy-error-quark"); } static void rest_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { RestProxyPrivate *priv = GET_PRIVATE (object); switch (property_id) { case PROP_URL_FORMAT: g_value_set_string (value, priv->url_format); break; case PROP_BINDING_REQUIRED: g_value_set_boolean (value, priv->binding_required); break; case PROP_USER_AGENT: g_value_set_string (value, priv->user_agent); break; case PROP_DISABLE_COOKIES: g_value_set_boolean (value, priv->disable_cookies); break; case PROP_USERNAME: g_value_set_string (value, priv->username); break; case PROP_PASSWORD: g_value_set_string (value, priv->password); break; case PROP_SSL_STRICT: { gboolean ssl_strict; g_object_get (G_OBJECT(priv->session), "ssl-strict", &ssl_strict, NULL); g_value_set_boolean (value, ssl_strict); break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void rest_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { RestProxyPrivate *priv = GET_PRIVATE (object); switch (property_id) { case PROP_URL_FORMAT: g_free (priv->url_format); priv->url_format = g_value_dup_string (value); /* Clear the cached url */ g_free (priv->url); priv->url = NULL; break; case PROP_BINDING_REQUIRED: priv->binding_required = g_value_get_boolean (value); /* Clear cached url */ g_free (priv->url); priv->url = NULL; break; case PROP_USER_AGENT: g_free (priv->user_agent); priv->user_agent = g_value_dup_string (value); break; case PROP_DISABLE_COOKIES: priv->disable_cookies = g_value_get_boolean (value); break; case PROP_USERNAME: g_free (priv->username); priv->username = g_value_dup_string (value); break; case PROP_PASSWORD: g_free (priv->password); priv->password = g_value_dup_string (value); break; case PROP_SSL_STRICT: g_object_set (G_OBJECT(priv->session), "ssl-strict", g_value_get_boolean (value), NULL); g_object_set (G_OBJECT(priv->session_sync), "ssl-strict", g_value_get_boolean (value), NULL); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void rest_proxy_dispose (GObject *object) { RestProxyPrivate *priv = GET_PRIVATE (object); if (priv->session) { g_object_unref (priv->session); priv->session = NULL; } if (priv->session_sync) { g_object_unref (priv->session_sync); priv->session_sync = NULL; } G_OBJECT_CLASS (rest_proxy_parent_class)->dispose (object); } static gboolean default_authenticate_cb (RestProxy *self, G_GNUC_UNUSED RestProxyAuth *auth, gboolean retrying) { /* We only want to try the credentials once, otherwise we get in an * infinite loop with failed credentials, retrying the same invalid * ones again and again */ return !retrying; } static void authenticate (RestProxy *self, SoupMessage *msg, SoupAuth *soup_auth, gboolean retrying, SoupSession *session) { RestProxyPrivate *priv = GET_PRIVATE (self); RestProxyAuth *rest_auth; gboolean try_auth; rest_auth = rest_proxy_auth_new (self, session, msg, soup_auth); g_signal_emit(self, signals[AUTHENTICATE], 0, rest_auth, retrying, &try_auth); if (try_auth && !rest_proxy_auth_is_paused (rest_auth)) soup_auth_authenticate (soup_auth, priv->username, priv->password); g_object_unref (G_OBJECT (rest_auth)); } static void rest_proxy_constructed (GObject *object) { RestProxyPrivate *priv = GET_PRIVATE (object); if (!priv->disable_cookies) { SoupSessionFeature *cookie_jar = (SoupSessionFeature *)soup_cookie_jar_new (); soup_session_add_feature (priv->session, cookie_jar); soup_session_add_feature (priv->session_sync, cookie_jar); g_object_unref (cookie_jar); } /* session lifetime is same as self, no need to keep signalid */ g_signal_connect_swapped (priv->session, "authenticate", G_CALLBACK(authenticate), object); g_signal_connect_swapped (priv->session_sync, "authenticate", G_CALLBACK(authenticate), object); } static void rest_proxy_finalize (GObject *object) { RestProxyPrivate *priv = GET_PRIVATE (object); g_free (priv->url); g_free (priv->url_format); g_free (priv->user_agent); g_free (priv->username); g_free (priv->password); G_OBJECT_CLASS (rest_proxy_parent_class)->finalize (object); } static void rest_proxy_class_init (RestProxyClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); RestProxyClass *proxy_class = REST_PROXY_CLASS (klass); _rest_setup_debugging (); g_type_class_add_private (klass, sizeof (RestProxyPrivate)); object_class->get_property = rest_proxy_get_property; object_class->set_property = rest_proxy_set_property; object_class->dispose = rest_proxy_dispose; object_class->constructed = rest_proxy_constructed; object_class->finalize = rest_proxy_finalize; proxy_class->simple_run_valist = _rest_proxy_simple_run_valist; proxy_class->new_call = _rest_proxy_new_call; proxy_class->bind_valist = _rest_proxy_bind_valist; pspec = g_param_spec_string ("url-format", "url-format", "Format string for the RESTful url", NULL, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_URL_FORMAT, pspec); pspec = g_param_spec_boolean ("binding-required", "binding-required", "Whether the URL format requires binding", FALSE, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_BINDING_REQUIRED, pspec); pspec = g_param_spec_string ("user-agent", "user-agent", "The User-Agent of the client", NULL, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_USER_AGENT, pspec); pspec = g_param_spec_boolean ("disable-cookies", "disable-cookies", "Whether to disable cookie support", FALSE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); g_object_class_install_property (object_class, PROP_DISABLE_COOKIES, pspec); pspec = g_param_spec_string ("username", "username", "The username for authentication", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_USERNAME, pspec); pspec = g_param_spec_string ("password", "password", "The password for authentication", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_PASSWORD, pspec); pspec = g_param_spec_boolean ("ssl-strict", "Strictly validate SSL certificates", "Whether certificate errors should be considered a connection error", TRUE, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_SSL_STRICT, pspec); /** * RestProxy::authenticate: * @proxy: the proxy * @retrying: %TRUE if this is the second (or later) attempt * * Emitted when the proxy requires authentication. If * credentials are available, set the 'username' and 'password' * properties on @proxy and return TRUE from the callback. * This will cause the signal emission to stop, and librest will * try to connect with these credentials * If these credentials fail, the signal will be * emitted again, with @retrying set to %TRUE, which will * continue until FALSE is returned from the callback. * * If you call rest_proxy_auth_pause() on @auth before * returning, then you can the authentication credentials on * the RestProxy object asynchronously. You have to make sure * that @auth does not get destroyed with g_object_ref(). * You can then unpause the authentication with * rest_proxy_auth_unpause() when everything is ready for it * to continue. **/ signals[AUTHENTICATE] = g_signal_new ("authenticate", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RestProxyClass, authenticate), g_signal_accumulator_true_handled, NULL, NULL, G_TYPE_BOOLEAN, 2, REST_TYPE_PROXY_AUTH, G_TYPE_BOOLEAN); proxy_class->authenticate = default_authenticate_cb; } static void rest_proxy_init (RestProxy *self) { RestProxyPrivate *priv = GET_PRIVATE (self); priv->session = soup_session_async_new (); priv->session_sync = soup_session_sync_new (); /* with ssl-strict (defaults TRUE) setting ssl-ca-file forces all * certificates to be trusted */ g_object_set (priv->session, "ssl-ca-file", REST_SYSTEM_CA_FILE, NULL); g_object_set (priv->session_sync, "ssl-ca-file", REST_SYSTEM_CA_FILE, NULL); #if WITH_GNOME soup_session_add_feature_by_type (priv->session, SOUP_TYPE_PROXY_RESOLVER_GNOME); soup_session_add_feature_by_type (priv->session_sync, SOUP_TYPE_PROXY_RESOLVER_GNOME); #endif if (REST_DEBUG_ENABLED(PROXY)) { SoupSessionFeature *logger = (SoupSessionFeature*)soup_logger_new (SOUP_LOGGER_LOG_BODY, 0); soup_session_add_feature (priv->session, logger); g_object_unref (logger); logger = (SoupSessionFeature*)soup_logger_new (SOUP_LOGGER_LOG_BODY, 0); soup_session_add_feature (priv->session_sync, logger); g_object_unref (logger); } } /** * rest_proxy_new: * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * * Create a new #RestProxy for the specified endpoint @url_format, using the * "GET" method. * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #RestProxy. */ RestProxy * rest_proxy_new (const gchar *url_format, gboolean binding_required) { return g_object_new (REST_TYPE_PROXY, "url-format", url_format, "binding-required", binding_required, NULL); } /** * rest_proxy_new_with_authentication: * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * @username: the username provided by the user or client * @password: the password provided by the user or client * * Create a new #RestProxy for the specified endpoint @url_format, using the * "GET" method. * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #RestProxy. */ RestProxy * rest_proxy_new_with_authentication (const gchar *url_format, gboolean binding_required, const gchar *username, const gchar *password) { return g_object_new (REST_TYPE_PROXY, "url-format", url_format, "binding-required", binding_required, "username", username, "password", password, NULL); } static gboolean _rest_proxy_bind_valist (RestProxy *proxy, va_list params) { RestProxyPrivate *priv = GET_PRIVATE (proxy); g_return_val_if_fail (proxy != NULL, FALSE); g_return_val_if_fail (priv->url_format != NULL, FALSE); g_return_val_if_fail (priv->binding_required == TRUE, FALSE); g_free (priv->url); priv->url = g_strdup_vprintf (priv->url_format, params); return TRUE; } gboolean rest_proxy_bind_valist (RestProxy *proxy, va_list params) { RestProxyClass *proxy_class = REST_PROXY_GET_CLASS (proxy); return proxy_class->bind_valist (proxy, params); } gboolean rest_proxy_bind (RestProxy *proxy, ...) { g_return_val_if_fail (REST_IS_PROXY (proxy), FALSE); gboolean res; va_list params; va_start (params, proxy); res = rest_proxy_bind_valist (proxy, params); va_end (params); return res; } void rest_proxy_set_user_agent (RestProxy *proxy, const char *user_agent) { g_return_if_fail (REST_IS_PROXY (proxy)); g_object_set (proxy, "user-agent", user_agent, NULL); } const gchar * rest_proxy_get_user_agent (RestProxy *proxy) { RestProxyPrivate *priv; g_return_val_if_fail (REST_IS_PROXY (proxy), NULL); priv = GET_PRIVATE (proxy); return priv->user_agent; } static RestProxyCall * _rest_proxy_new_call (RestProxy *proxy) { RestProxyCall *call; call = g_object_new (REST_TYPE_PROXY_CALL, "proxy", proxy, NULL); return call; } /** * rest_proxy_new_call: * @proxy: the #RestProxy * * Create a new #RestProxyCall for making a call to the web service. This call * is one-shot and should not be re-used for making multiple calls. * * Returns: (transfer full): a new #RestProxyCall. */ RestProxyCall * rest_proxy_new_call (RestProxy *proxy) { RestProxyClass *proxy_class = REST_PROXY_GET_CLASS (proxy); return proxy_class->new_call (proxy); } gboolean _rest_proxy_get_binding_required (RestProxy *proxy) { RestProxyPrivate *priv; g_return_val_if_fail (REST_IS_PROXY (proxy), FALSE); priv = GET_PRIVATE (proxy); return priv->binding_required; } const gchar * _rest_proxy_get_bound_url (RestProxy *proxy) { RestProxyPrivate *priv; g_return_val_if_fail (REST_IS_PROXY (proxy), NULL); priv = GET_PRIVATE (proxy); if (!priv->url && !priv->binding_required) { priv->url = g_strdup (priv->url_format); } return priv->url; } static gboolean _rest_proxy_simple_run_valist (RestProxy *proxy, gchar **payload, goffset *len, GError **error, va_list params) { RestProxyCall *call; gboolean ret; g_return_val_if_fail (REST_IS_PROXY (proxy), FALSE); g_return_val_if_fail (payload, FALSE); call = rest_proxy_new_call (proxy); rest_proxy_call_add_params_from_valist (call, params); ret = rest_proxy_call_run (call, NULL, error); if (ret) { *payload = g_strdup (rest_proxy_call_get_payload (call)); if (len) *len = rest_proxy_call_get_payload_length (call); } else { *payload = NULL; if (len) *len = 0; } g_object_unref (call); return ret; } gboolean rest_proxy_simple_run_valist (RestProxy *proxy, char **payload, goffset *len, GError **error, va_list params) { RestProxyClass *proxy_class = REST_PROXY_GET_CLASS (proxy); return proxy_class->simple_run_valist (proxy, payload, len, error, params); } gboolean rest_proxy_simple_run (RestProxy *proxy, gchar **payload, goffset *len, GError **error, ...) { va_list params; gboolean ret; g_return_val_if_fail (REST_IS_PROXY (proxy), FALSE); g_return_val_if_fail (payload, FALSE); va_start (params, error); ret = rest_proxy_simple_run_valist (proxy, payload, len, error, params); va_end (params); return ret; } void _rest_proxy_queue_message (RestProxy *proxy, SoupMessage *message, SoupSessionCallback callback, gpointer user_data) { RestProxyPrivate *priv; g_return_if_fail (REST_IS_PROXY (proxy)); g_return_if_fail (SOUP_IS_MESSAGE (message)); priv = GET_PRIVATE (proxy); soup_session_queue_message (priv->session, message, callback, user_data); } void _rest_proxy_cancel_message (RestProxy *proxy, SoupMessage *message) { RestProxyPrivate *priv; g_return_if_fail (REST_IS_PROXY (proxy)); g_return_if_fail (SOUP_IS_MESSAGE (message)); priv = GET_PRIVATE (proxy); soup_session_cancel_message (priv->session, message, SOUP_STATUS_CANCELLED); } guint _rest_proxy_send_message (RestProxy *proxy, SoupMessage *message) { RestProxyPrivate *priv; g_return_val_if_fail (REST_IS_PROXY (proxy), 0); g_return_val_if_fail (SOUP_IS_MESSAGE (message), 0); priv = GET_PRIVATE (proxy); return soup_session_send_message (priv->session_sync, message); } librest/rest/rest-proxy-auth-private.h0000664000175000017500000000247112014274315016506 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2012, Red Hat, Inc. * * Authors: Christophe Fergeau * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PROXY_AUTH_PRIVATE #define _REST_PROXY_AUTH_PRIVATE #include #include #include G_BEGIN_DECLS RestProxyAuth* rest_proxy_auth_new (RestProxy *proxy, SoupSession *session, SoupMessage *message, SoupAuth *auth); gboolean rest_proxy_auth_is_paused (RestProxyAuth *auth); G_END_DECLS #endif /* _REST_PROXY_AUTH_PRIVATE */ librest/rest/rest-proxy-call.h0000664000175000017500000002131312014274315015004 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PROXY_CALL #define _REST_PROXY_CALL #include #include #include G_BEGIN_DECLS #define REST_TYPE_PROXY_CALL rest_proxy_call_get_type() #define REST_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), REST_TYPE_PROXY_CALL, RestProxyCall)) #define REST_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), REST_TYPE_PROXY_CALL, RestProxyCallClass)) #define REST_IS_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), REST_TYPE_PROXY_CALL)) #define REST_IS_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), REST_TYPE_PROXY_CALL)) #define REST_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), REST_TYPE_PROXY_CALL, RestProxyCallClass)) typedef struct _RestProxyCallPrivate RestProxyCallPrivate; /** * RestProxyCall: * * #RestProxyCall has no publicly available members. */ typedef struct { GObject parent; RestProxyCallPrivate *priv; } RestProxyCall; /** * RestProxyCallClass: * @prepare: Virtual function called before making the request, This allows the * call to be modified, for example to add a signature. * @serialize_params: Virtual function allowing custom serialization of the * parameters, for example when the API doesn't expect standard form content. * * Class structure for #RestProxyCall for subclasses to implement specialised * behaviour. */ typedef struct { /*< private >*/ GObjectClass parent_class; /*< public >*/ gboolean (*prepare)(RestProxyCall *call, GError **error); gboolean (*serialize_params) (RestProxyCall *call, gchar **content_type, gchar **content, gsize *content_len, GError **error); /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[7]; } RestProxyCallClass; #define REST_PROXY_CALL_ERROR rest_proxy_call_error_quark () /** * RestProxyCallError: * @REST_PROXY_CALL_FAILED: the method call failed * * Error domain used when returning errors from #RestProxyCall. */ typedef enum { REST_PROXY_CALL_FAILED } RestProxyCallError; GQuark rest_proxy_call_error_quark (void); GType rest_proxy_call_get_type (void); /* Functions for dealing with request */ void rest_proxy_call_set_method (RestProxyCall *call, const gchar *method); const char * rest_proxy_call_get_method (RestProxyCall *call); void rest_proxy_call_set_function (RestProxyCall *call, const gchar *function); void rest_proxy_call_add_header (RestProxyCall *call, const gchar *header, const gchar *value); G_GNUC_NULL_TERMINATED void rest_proxy_call_add_headers (RestProxyCall *call, ...); void rest_proxy_call_add_headers_from_valist (RestProxyCall *call, va_list headers); const gchar *rest_proxy_call_lookup_header (RestProxyCall *call, const gchar *header); void rest_proxy_call_remove_header (RestProxyCall *call, const gchar *header); void rest_proxy_call_add_param (RestProxyCall *call, const gchar *name, const gchar *value); void rest_proxy_call_add_param_full (RestProxyCall *call, RestParam *param); G_GNUC_NULL_TERMINATED void rest_proxy_call_add_params (RestProxyCall *call, ...); void rest_proxy_call_add_params_from_valist (RestProxyCall *call, va_list params); RestParam *rest_proxy_call_lookup_param (RestProxyCall *call, const gchar *name); void rest_proxy_call_remove_param (RestProxyCall *call, const gchar *name); RestParams *rest_proxy_call_get_params (RestProxyCall *call); gboolean rest_proxy_call_run (RestProxyCall *call, GMainLoop **loop, GError **error); typedef void (*RestProxyCallAsyncCallback)(RestProxyCall *call, const GError *error, GObject *weak_object, gpointer userdata); gboolean rest_proxy_call_async (RestProxyCall *call, RestProxyCallAsyncCallback callback, GObject *weak_object, gpointer userdata, GError **error); void rest_proxy_call_invoke_async (RestProxyCall *call, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); gboolean rest_proxy_call_invoke_finish (RestProxyCall *call, GAsyncResult *result, GError **error); typedef void (*RestProxyCallContinuousCallback) (RestProxyCall *call, const gchar *buf, gsize len, const GError *error, GObject *weak_object, gpointer userdata); gboolean rest_proxy_call_continuous (RestProxyCall *call, RestProxyCallContinuousCallback callback, GObject *weak_object, gpointer userdata, GError **error); typedef void (*RestProxyCallUploadCallback) (RestProxyCall *call, gsize total, gsize uploaded, const GError *error, GObject *weak_object, gpointer userdata); gboolean rest_proxy_call_upload (RestProxyCall *call, RestProxyCallUploadCallback callback, GObject *weak_object, gpointer userdata, GError **error); gboolean rest_proxy_call_cancel (RestProxyCall *call); gboolean rest_proxy_call_sync (RestProxyCall *call, GError **error_out); /* Functions for dealing with responses */ const gchar *rest_proxy_call_lookup_response_header (RestProxyCall *call, const gchar *header); GHashTable *rest_proxy_call_get_response_headers (RestProxyCall *call); goffset rest_proxy_call_get_payload_length (RestProxyCall *call); const gchar *rest_proxy_call_get_payload (RestProxyCall *call); guint rest_proxy_call_get_status_code (RestProxyCall *call); const gchar *rest_proxy_call_get_status_message (RestProxyCall *call); gboolean rest_proxy_call_serialize_params (RestProxyCall *call, gchar **content_type, gchar **content, gsize *content_len, GError **error); G_END_DECLS #endif /* _REST_PROXY_CALL */ librest/rest/rest-proxy-call-private.h0000664000175000017500000000323112014274315016453 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PROXY_CALL_PRIVATE #define _REST_PROXY_CALL_PRIVATE #include #include #include G_BEGIN_DECLS typedef struct _RestProxyCallAsyncClosure RestProxyCallAsyncClosure; typedef struct _RestProxyCallContinuousClosure RestProxyCallContinuousClosure; typedef struct _RestProxyCallUploadClosure RestProxyCallUploadClosure; struct _RestProxyCallPrivate { gchar *method; gchar *function; GHashTable *headers; RestParams *params; /* The real URL we're about to invoke */ gchar *url; GHashTable *response_headers; goffset length; gchar *payload; guint status_code; gchar *status_message; RestProxy *proxy; RestProxyCallAsyncClosure *cur_call_closure; }; G_END_DECLS #endif /* _REST_PROXY_CALL_PRIVATE */ librest/rest/Makefile.am0000664000175000017500000001045212014274314013623 0ustar bobbobCLEANFILES = # For some reason I can't use $(librest_@API_VERSION@_la_SOURCES) in # test_runner_SOURCES, so we have to do this lib_sources = \ rest-param.c \ rest-params.c \ rest-proxy.c \ rest-proxy-auth.c \ rest-proxy-auth-private.h \ rest-proxy-call.c \ rest-proxy-call-private.h \ rest-xml-node.c \ rest-xml-parser.c \ rest-main.c \ rest-private.h \ rest-enum-types.c \ oauth-proxy.c \ oauth-proxy-call.c \ oauth-proxy-private.h \ oauth2-proxy.c \ oauth2-proxy-call.c \ oauth2-proxy-private.h \ sha1.c \ sha1.h lib_headers = \ rest-param.h \ rest-params.h \ rest-proxy.h \ rest-proxy-auth.h \ rest-proxy-call.h \ rest-enum-types.h \ oauth-proxy.h \ oauth-proxy-call.h \ oauth2-proxy.h \ oauth2-proxy-call.h \ rest-xml-node.h \ rest-xml-parser.h lib_LTLIBRARIES = librest-@API_VERSION@.la librest_@API_VERSION@_la_CFLAGS = $(GLIB_CFLAGS) $(GTHREAD_CFLAGS) \ $(SOUP_CFLAGS) $(SOUP_GNOME_CFLAGS) \ $(XML_CFLAGS) $(GCOV_CFLAGS) \ -I$(top_srcdir) -Wall -DG_LOG_DOMAIN=\"Rest\" librest_@API_VERSION@_la_LDFLAGS = -no-undefined librest_@API_VERSION@_la_LIBADD = $(GLIB_LIBS) $(GTHREAD_LIBS) \ $(SOUP_LIBS) $(SOUP_GNOME_LIBS) $(XML_LIBS) \ $(GCOV_LDFLAGS) librest_@API_VERSION@_la_SOURCES = $(lib_sources) $(lib_headers) librest_@API_VERSION@_la_HEADERS = $(lib_headers) librest_@API_VERSION@_ladir = $(includedir)/rest-@API_VERSION@/rest rest-enum-types.h: stamp-rest-enum-types.h @true stamp-rest-enum-types.h: rest-proxy.h rest-proxy-call.h Makefile $(AM_V_GEN) (cd $(srcdir) && $(GLIB_MKENUMS) \ --fhead "#ifndef __REST_ENUM_TYPES_H__\n#define __REST_ENUM_TYPES_H__\n\n#include \n\nG_BEGIN_DECLS\n" \ --fprod "/* enumerations from \"@filename@\" */\n" \ --vhead "GType @enum_name@_get_type (void) G_GNUC_CONST;\n#define REST_TYPE_@ENUMSHORT@ (@enum_name@_get_type())\n" \ --ftail "G_END_DECLS\n\n#endif /* __REST_ENUM_TYPES_H__ */" rest-proxy.h rest-proxy-call.h) >> xgen-gtbh \ && (cmp -s xgen-gtbh rest-enum-types.h || cp xgen-gtbh rest-enum-types.h ) \ && rm -f xgen-gtbh \ && echo timestamp > $(@F) rest-enum-types.c: rest-proxy.h rest-proxy-call.h Makefile rest-enum-types.h $(AM_V_GEN) (cd $(srcdir) && $(GLIB_MKENUMS) \ --fhead "#include \"rest-proxy.h\"\n#include \"rest-proxy-call.h\"\n#include \"rest-enum-types.h\"" \ --fprod "\n/* enumerations from \"@filename@\" */" \ --vhead "GType\n@enum_name@_get_type (void)\n{\n static GType etype = 0;\n if (etype == 0) {\n static const G@Type@Value values[] = {" \ --vprod " { @VALUENAME@, \"@VALUENAME@\", \"@valuenick@\" }," \ --vtail " { 0, NULL, NULL }\n };\n etype = g_@type@_register_static (\"@EnumName@\", values);\n }\n return etype;\n}\n" \ rest-proxy.h rest-proxy-call.h) > xgen-gtbc \ && cp xgen-gtbc rest-enum-types.c \ && rm -f xgen-gtbc # Test suite TESTS = test-runner check_PROGRAMS = test-runner test_runner_SOURCES = test-runner.c $(lib_sources) $(lib_headers) test_runner_CFLAGS = -DBUILD_TESTS $(librest_@API_VERSION@_la_CFLAGS) $(GCOV_CFLAGS) test_runner_LDFLAGS = $(librest_@API_VERSION@_la_LIBADD) $(GCOV_LDFLAGS) # TODO: use gtester # intospection -include $(INTROSPECTION_MAKEFILE) if HAVE_INTROSPECTION INTROSPECTION_GIRS = Rest-@API_VERSION@.gir Rest-@API_VERSION@.gir: librest-@API_VERSION@.la Makefile Rest_@API_VERSION_AM@_gir_NAMESPACE = Rest Rest_@API_VERSION_AM@_gir_VERSION = @API_VERSION@ Rest_@API_VERSION_AM@_gir_LIBS = librest-@API_VERSION@.la Rest_@API_VERSION_AM@_gir_FILES = \ $(lib_headers) \ $(filter-out %private.h, $(lib_sources)) Rest_@API_VERSION_AM@_gir_CFLAGS = -I$(top_srcdir) Rest_@API_VERSION_AM@_gir_INCLUDES = GObject-2.0 Gio-2.0 Rest_@API_VERSION_AM@_gir_PACKAGES = gobject-2.0 libsoup-2.4 libxml-2.0 gio-2.0 Rest_@API_VERSION_AM@_gir_SCANNERFLAGS = --accept-unprefixed Rest_@API_VERSION_AM@_gir_EXPORT_PACKAGES = rest-@API_VERSION@ REST_CINCLUDES=$(patsubst %,--c-include='rest/%',$(shell echo $(lib_headers))) INTROSPECTION_SCANNER_ARGS = $(REST_CINCLUDES) girdir = $(datadir)/gir-1.0 dist_gir_DATA = $(INTROSPECTION_GIRS) typelibsdir = $(libdir)/girepository-1.0/ typelibs_DATA = $(INTROSPECTION_GIRS:.gir=.typelib) CLEANFILES += $(dist_gir_DATA) \ $(typelibs_DATA) \ rest-enum-types.h \ rest-enum-types.c \ stamp-rest-enum-types.h \ $(NULL) endif # HAVE_INTROSPECTION librest/rest/rest-proxy-auth.c0000664000175000017500000000720312014274315015027 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2012, Red Hat, Inc. * * Authors: Christophe Fergeau * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include G_DEFINE_TYPE (RestProxyAuth, rest_proxy_auth, G_TYPE_OBJECT) #define REST_PROXY_AUTH_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), REST_TYPE_PROXY_AUTH, RestProxyAuthPrivate)) struct _RestProxyAuthPrivate { /* used to hold state during async authentication */ RestProxy *proxy; SoupSession *session; SoupMessage *message; SoupAuth *auth; gboolean paused; }; static void rest_proxy_auth_dispose (GObject *object) { RestProxyAuthPrivate *priv = ((RestProxyAuth*)object)->priv; g_clear_object (&priv->proxy); g_clear_object (&priv->session); g_clear_object (&priv->message); g_clear_object (&priv->auth); G_OBJECT_CLASS (rest_proxy_auth_parent_class)->dispose (object); } static void rest_proxy_auth_class_init (RestProxyAuthClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (RestProxyAuthPrivate)); object_class->dispose = rest_proxy_auth_dispose; } static void rest_proxy_auth_init (RestProxyAuth *proxy) { proxy->priv = REST_PROXY_AUTH_GET_PRIVATE (proxy); } G_GNUC_INTERNAL RestProxyAuth* rest_proxy_auth_new (RestProxy *proxy, SoupSession *session, SoupMessage *message, SoupAuth *soup_auth) { RestProxyAuth *rest_auth; g_return_val_if_fail (REST_IS_PROXY (proxy), NULL); g_return_val_if_fail (SOUP_IS_SESSION (session), NULL); g_return_val_if_fail (SOUP_IS_MESSAGE (message), NULL); g_return_val_if_fail (SOUP_IS_AUTH (soup_auth), NULL); rest_auth = REST_PROXY_AUTH (g_object_new (REST_TYPE_PROXY_AUTH, NULL)); rest_auth->priv->proxy = g_object_ref(proxy); rest_auth->priv->session = g_object_ref(session); rest_auth->priv->message = g_object_ref(message); rest_auth->priv->auth = g_object_ref(soup_auth); return rest_auth; } void rest_proxy_auth_pause (RestProxyAuth *auth) { g_return_if_fail (REST_IS_PROXY_AUTH (auth)); if (auth->priv->paused) return; auth->priv->paused = TRUE; soup_session_pause_message (auth->priv->session, auth->priv->message); } void rest_proxy_auth_unpause (RestProxyAuth *auth) { RestProxy *proxy; gchar *username; gchar *password; g_return_if_fail (REST_IS_PROXY_AUTH (auth)); g_return_if_fail (auth->priv->paused); proxy = REST_PROXY (auth->priv->proxy); g_object_get (G_OBJECT (proxy), "username", &username, "password", &password, NULL); soup_auth_authenticate (auth->priv->auth, username, password); g_free (username); g_free (password); soup_session_unpause_message (auth->priv->session, auth->priv->message); auth->priv->paused = FALSE; } G_GNUC_INTERNAL gboolean rest_proxy_auth_is_paused (RestProxyAuth *auth) { g_return_val_if_fail (REST_IS_PROXY_AUTH (auth), FALSE); return auth->priv->paused; } librest/rest/oauth-proxy.h0000664000175000017500000001433112014274314014237 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _OAUTH_PROXY #define _OAUTH_PROXY #include G_BEGIN_DECLS #define OAUTH_TYPE_PROXY oauth_proxy_get_type() #define OAUTH_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), OAUTH_TYPE_PROXY, OAuthProxy)) #define OAUTH_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), OAUTH_TYPE_PROXY, OAuthProxyClass)) #define OAUTH_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), OAUTH_TYPE_PROXY)) #define OAUTH_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), OAUTH_TYPE_PROXY)) #define OAUTH_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), OAUTH_TYPE_PROXY, OAuthProxyClass)) /** * OAuthProxy: * * #OAuthProxy has no publicly available members. */ typedef struct { RestProxy parent; } OAuthProxy; typedef struct { RestProxyClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } OAuthProxyClass; GType oauth_signature_method_get_type (void) G_GNUC_CONST; #define OAUTH_TYPE_SIGNATURE_METHOD (oauth_signature_method_get_type()) /** * OAuthSignatureMethod: * @PLAINTEXT: plain text signatures (not recommended) * @HMAC_SHA1: HMAC-SHA1 signatures (recommended) * * The signature method to use when signing method calls. @PLAINTEXT is only * recommended for testing, in general @HMAC_SHA1 is well supported and more * secure. */ typedef enum { PLAINTEXT, HMAC_SHA1 } OAuthSignatureMethod; GType oauth_proxy_get_type (void); RestProxy* oauth_proxy_new (const char *consumer_key, const char *consumer_secret, const gchar *url_format, gboolean binding_required); RestProxy* oauth_proxy_new_with_token (const char *consumer_key, const char *consumer_secret, const char *token, const char *token_secret, const gchar *url_format, gboolean binding_required); /** * OAuthProxyAuthCallback: * @proxy: the #OAuthProxy * @error: a #GError if the authentication failed, otherwise %NULL * @weak_object: the weak object passed to the caller * @userdata: the user data passed to the caller * * Callback from oauth_proxy_request_token_async() and * oauth_proxy_access_token_async(). */ typedef void (*OAuthProxyAuthCallback)(OAuthProxy *proxy, const GError *error, GObject *weak_object, gpointer userdata); G_GNUC_DEPRECATED gboolean oauth_proxy_auth_step (OAuthProxy *proxy, const char *function, GError **error); G_GNUC_DEPRECATED gboolean oauth_proxy_auth_step_async (OAuthProxy *proxy, const char *function, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error_out); gboolean oauth_proxy_request_token (OAuthProxy *proxy, const char *function, const char *callback_uri, GError **error); gboolean oauth_proxy_request_token_async (OAuthProxy *proxy, const char *function, const char *callback_uri, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error); gboolean oauth_proxy_is_oauth10a (OAuthProxy *proxy); gboolean oauth_proxy_access_token (OAuthProxy *proxy, const char *function, const char *verifier, GError **error); gboolean oauth_proxy_access_token_async (OAuthProxy *proxy, const char *function, const char *verifier, OAuthProxyAuthCallback callback, GObject *weak_object, gpointer user_data, GError **error); const char * oauth_proxy_get_token (OAuthProxy *proxy); void oauth_proxy_set_token (OAuthProxy *proxy, const char *token); const char * oauth_proxy_get_token_secret (OAuthProxy *proxy); void oauth_proxy_set_token_secret (OAuthProxy *proxy, const char *token_secret); const char * oauth_proxy_get_signature_host (OAuthProxy *proxy); void oauth_proxy_set_signature_host (OAuthProxy *proxy, const char *signature_host); RestProxy *oauth_proxy_new_echo_proxy (OAuthProxy *proxy, const char *service_url, const gchar *url_format, gboolean binding_required); G_END_DECLS #endif /* _OAUTH_PROXY */ librest/rest/oauth2-proxy.h0000664000175000017500000000610012014274314014314 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _OAUTH2_PROXY #define _OAUTH2_PROXY #include G_BEGIN_DECLS #define OAUTH2_TYPE_PROXY oauth2_proxy_get_type() #define OAUTH2_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), OAUTH2_TYPE_PROXY, OAuth2Proxy)) #define OAUTH2_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), OAUTH2_TYPE_PROXY, OAuth2ProxyClass)) #define OAUTH2_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), OAUTH2_TYPE_PROXY)) #define OAUTH2_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), OAUTH2_TYPE_PROXY)) #define OAUTH2_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), OAUTH2_TYPE_PROXY, OAuth2ProxyClass)) typedef struct _OAuth2ProxyPrivate OAuth2ProxyPrivate; /** * OAuth2Proxy: * * #OAuth2Proxy has no publicly available members. */ typedef struct { RestProxy parent; OAuth2ProxyPrivate *priv; } OAuth2Proxy; typedef struct { RestProxyClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } OAuth2ProxyClass; GType oauth2_proxy_get_type (void); RestProxy* oauth2_proxy_new (const char *client_id, const char *auth_endpoint, const gchar *url_format, gboolean binding_required); RestProxy* oauth2_proxy_new_with_token (const char *client_id, const char *access_token, const char *auth_endpoint, const gchar *url_format, gboolean binding_required); char * oauth2_proxy_build_login_url_full (OAuth2Proxy *proxy, const char* redirect_uri, GHashTable* extra_params); char * oauth2_proxy_build_login_url (OAuth2Proxy *proxy, const char* redirect_uri); const char * oauth2_proxy_get_access_token (OAuth2Proxy *proxy); void oauth2_proxy_set_access_token (OAuth2Proxy *proxy, const char *access_token); char * oauth2_proxy_extract_access_token (const char *url); G_END_DECLS #endif /* _OAUTH2_PROXY */ librest/rest/oauth2-proxy.c0000664000175000017500000003074512014274314014323 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "oauth2-proxy.h" #include "oauth2-proxy-private.h" #include "oauth2-proxy-call.h" G_DEFINE_TYPE (OAuth2Proxy, oauth2_proxy, REST_TYPE_PROXY) #define OAUTH2_PROXY_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), OAUTH2_TYPE_PROXY, OAuth2ProxyPrivate)) GQuark oauth2_proxy_error_quark (void) { return g_quark_from_static_string ("rest-oauth2-proxy"); } #define EXTRA_CHARS_ENCODE "!$&'()*+,;=@" enum { PROP_0, PROP_CLIENT_ID, PROP_AUTH_ENDPOINT, PROP_ACCESS_TOKEN }; static RestProxyCall * _new_call (RestProxy *proxy) { RestProxyCall *call; call = g_object_new (OAUTH2_TYPE_PROXY_CALL, "proxy", proxy, NULL); return call; } static void oauth2_proxy_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { OAuth2ProxyPrivate *priv = ((OAuth2Proxy*)object)->priv; switch (property_id) { case PROP_CLIENT_ID: g_value_set_string (value, priv->client_id); break; case PROP_AUTH_ENDPOINT: g_value_set_string (value, priv->auth_endpoint); break; case PROP_ACCESS_TOKEN: g_value_set_string (value, priv->access_token); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void oauth2_proxy_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { OAuth2ProxyPrivate *priv = ((OAuth2Proxy*)object)->priv; switch (property_id) { case PROP_CLIENT_ID: if (priv->client_id) g_free (priv->client_id); priv->client_id = g_value_dup_string (value); break; case PROP_AUTH_ENDPOINT: if (priv->auth_endpoint) g_free (priv->auth_endpoint); priv->auth_endpoint = g_value_dup_string (value); break; case PROP_ACCESS_TOKEN: if (priv->access_token) g_free (priv->access_token); priv->access_token = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void oauth2_proxy_finalize (GObject *object) { OAuth2ProxyPrivate *priv = ((OAuth2Proxy*)object)->priv; g_free (priv->client_id); g_free (priv->auth_endpoint); g_free (priv->access_token); G_OBJECT_CLASS (oauth2_proxy_parent_class)->finalize (object); } static void oauth2_proxy_class_init (OAuth2ProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); RestProxyClass *proxy_class = REST_PROXY_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (OAuth2ProxyPrivate)); object_class->get_property = oauth2_proxy_get_property; object_class->set_property = oauth2_proxy_set_property; object_class->finalize = oauth2_proxy_finalize; proxy_class->new_call = _new_call; pspec = g_param_spec_string ("client-id", "client-id", "The client (application) id", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_CLIENT_ID, pspec); pspec = g_param_spec_string ("auth-endpoint", "auth-endpoint", "The authentication endpoint url", NULL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_AUTH_ENDPOINT, pspec); pspec = g_param_spec_string ("access-token", "access-token", "The request or access token", NULL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_ACCESS_TOKEN, pspec); } static void oauth2_proxy_init (OAuth2Proxy *proxy) { proxy->priv = OAUTH2_PROXY_GET_PRIVATE (proxy); } /** * oauth2_proxy_new: * @client_id: the client (application) id * @auth_endpoint: the authentication endpoint URL * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * * Create a new #OAuth2Proxy for the specified endpoint @url_format, using the * specified API key and secret. * * This proxy won't have the Token set so will be unauthorised. If the token is * unknown then the following steps should be taken to acquire an access token: * - Get the authentication url with oauth2_proxy_build_login_url() * - Display this url in an embedded browser widget * - wait for the browser widget to be redirected to the specified redirect_uri * - extract the token from the fragment of the redirected uri (using * convenience function oauth2_proxy_extract_access_token()) * - set the token with oauth2_proxy_set_access_token() * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #OAuth2Proxy. */ RestProxy * oauth2_proxy_new (const char *client_id, const char *auth_endpoint, const gchar *url_format, gboolean binding_required) { return g_object_new (OAUTH2_TYPE_PROXY, "client-id", client_id, "auth-endpoint", auth_endpoint, "url-format", url_format, "binding-required", binding_required, NULL); } /** * oauth2_proxy_new_with_token: * @client_id: the client (application) id * @access_token: the Access Token * @auth_endpoint: the authentication endpoint URL * @url_format: the endpoint URL * @binding_required: whether the URL needs to be bound before calling * * Create a new #OAuth2Proxy for the specified endpoint @url_format, using the * specified client id * * @access_token is used for the Access Token, so if they are still valid then * this proxy is authorised. * * Set @binding_required to %TRUE if the URL contains string formatting * operations (for example "http://foo.com/%s". These must be expanded * using rest_proxy_bind() before invoking the proxy. * * Returns: A new #OAuth2Proxy. */ RestProxy * oauth2_proxy_new_with_token (const char *client_id, const char *access_token, const char *auth_endpoint, const gchar *url_format, gboolean binding_required) { return g_object_new (OAUTH2_TYPE_PROXY, "client-id", client_id, "access-token", access_token, "auth-endpoint", auth_endpoint, "url-format", url_format, "binding-required", binding_required, NULL); } /* allocates a new string of the form "key=value" */ static void append_query_param (gpointer key, gpointer value, gpointer user_data) { GString *params = (GString*) user_data; char *encoded_val, *encoded_key; char *param; encoded_val = soup_uri_encode (value, EXTRA_CHARS_ENCODE); encoded_key = soup_uri_encode (key, EXTRA_CHARS_ENCODE); param = g_strdup_printf ("%s=%s", encoded_key, encoded_val); g_free (encoded_key); g_free (encoded_val); // if there's already a parameter in the string, we need to add a '&' // separator before adding the new param if (params->len) g_string_append_c (params, '&'); g_string_append (params, param); } /** * oauth2_proxy_build_login_url_full: * @proxy: a OAuth2Proxy object * @redirect_uri: the uri to redirect to after the user authenticates * @extra_params: any extra parameters to add to the login url (e.g. facebook * uses 'scope=foo,bar' to request extended permissions). * * Builds a url at which the user can log in to the specified OAuth2-based web * service. In general, this url should be displayed in an embedded browser * widget, and you should then intercept the browser's redirect to @redirect_uri * and extract the access token from the url fragment. After the access token * has been retrieved, call oauth2_proxy_set_access_token(). This must be done * before making any API calls to the service. * * See the oauth2 spec for more details about the "user-agent" authentication * flow. * * The @extra_params and @redirect_uri should not be uri-encoded, that will be * done automatically * * Returns: a newly allocated uri string */ char * oauth2_proxy_build_login_url_full (OAuth2Proxy *proxy, const char* redirect_uri, GHashTable* extra_params) { char *url; GString *params = 0; char *encoded_uri, *encoded_id; g_return_val_if_fail (proxy, NULL); g_return_val_if_fail (redirect_uri, NULL); if (extra_params && g_hash_table_size (extra_params) > 0) { params = g_string_new (NULL); g_hash_table_foreach (extra_params, append_query_param, params); } encoded_uri = soup_uri_encode (redirect_uri, EXTRA_CHARS_ENCODE); encoded_id = soup_uri_encode (proxy->priv->client_id, EXTRA_CHARS_ENCODE); url = g_strdup_printf ("%s?client_id=%s&redirect_uri=%s&type=user_agent", proxy->priv->auth_endpoint, encoded_id, encoded_uri); g_free (encoded_uri); g_free (encoded_id); if (params) { char * full_url = g_strdup_printf ("%s&%s", url, params->str); g_free (url); url = full_url; g_string_free (params, TRUE); } return url; } /** * oauth2_proxy_build_login_url: * @proxy: an OAuth2Proxy object * @redirect_uri: the uri to redirect to after the user authenticates * * Builds a url at which the user can log in to the specified OAuth2-based web * service. See the documentation for oauth2_proxy_build_login_url_full() for * detailed information. * * Returns: a newly allocated uri string */ char * oauth2_proxy_build_login_url (OAuth2Proxy *proxy, const char* redirect_uri) { return oauth2_proxy_build_login_url_full (proxy, redirect_uri, NULL); } /** * oauth2_proxy_get_access_token: * @proxy: an #OAuth2Proxy * * Get the current request or access token. * * Returns: the token, or %NULL if there is no token yet. This string is owned * by #OAuth2Proxy and should not be freed. */ const char * oauth2_proxy_get_access_token (OAuth2Proxy *proxy) { return proxy->priv->access_token; } /** * oauth2_proxy_set_access_token: * @proxy: an #OAuth2Proxy * @access_token: the access token * * Set the access token. */ void oauth2_proxy_set_access_token (OAuth2Proxy *proxy, const char *access_token) { g_return_if_fail (OAUTH2_IS_PROXY (proxy)); if (proxy->priv->access_token) g_free (proxy->priv->access_token); proxy->priv->access_token = g_strdup (access_token); } /** * oauth2_proxy_extract_access_token: * @url: the url which contains an access token in its fragment * * A utility function to extract the access token from the url that results from * the redirection after the user authenticates */ char * oauth2_proxy_extract_access_token (const char *url) { GHashTable *params; char *token = NULL; SoupURI *soupuri = soup_uri_new (url); if (soupuri->fragment != NULL) { params = soup_form_decode (soupuri->fragment); if (params) { char *encoded = g_hash_table_lookup (params, "access_token"); if (encoded) token = soup_uri_decode (encoded); g_hash_table_destroy (params); } } return token; } librest/rest/rest-private.h0000664000175000017500000000470212014274315014367 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PRIVATE #define _REST_PRIVATE #include #include #include #include #include G_BEGIN_DECLS typedef enum { REST_DEBUG_XML_PARSER = 1 << 0, REST_DEBUG_PROXY = 1 << 1, REST_DEBUG_ALL = REST_DEBUG_XML_PARSER | REST_DEBUG_PROXY } RestDebugFlags; extern guint rest_debug_flags; #define REST_DEBUG_ENABLED(category) (rest_debug_flags & REST_DEBUG_##category) #define REST_DEBUG(category,x,a...) G_STMT_START { \ if (REST_DEBUG_ENABLED(category)) \ { g_message ("[" #category "] " G_STRLOC ": " x, ##a); } \ } G_STMT_END void _rest_setup_debugging (void); gboolean _rest_proxy_get_binding_required (RestProxy *proxy); const gchar *_rest_proxy_get_bound_url (RestProxy *proxy); void _rest_proxy_queue_message (RestProxy *proxy, SoupMessage *message, SoupSessionCallback callback, gpointer user_data); void _rest_proxy_cancel_message (RestProxy *proxy, SoupMessage *message); guint _rest_proxy_send_message (RestProxy *proxy, SoupMessage *message); RestXmlNode *_rest_xml_node_new (void); void _rest_xml_node_reverse_children_siblings (RestXmlNode *node); RestXmlNode *_rest_xml_node_prepend (RestXmlNode *cur_node, RestXmlNode *new_node); G_END_DECLS #endif /* _REST_PRIVATE */ librest/rest/sha1.h0000664000175000017500000000157612014274315012604 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ char * hmac_sha1 (const char *key, const char *message); librest/rest/rest-proxy.h0000664000175000017500000001450212014274315014075 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PROXY #define _REST_PROXY #include #include #include G_BEGIN_DECLS #define REST_TYPE_PROXY rest_proxy_get_type() #define REST_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), REST_TYPE_PROXY, RestProxy)) #define REST_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), REST_TYPE_PROXY, RestProxyClass)) #define REST_IS_PROXY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), REST_TYPE_PROXY)) #define REST_IS_PROXY_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), REST_TYPE_PROXY)) #define REST_PROXY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), REST_TYPE_PROXY, RestProxyClass)) typedef struct _RestProxy RestProxy; typedef struct _RestProxyClass RestProxyClass; /** * RestProxy: * * #RestProxy has no publicly available members. */ struct _RestProxy { GObject parent; }; /** * RestProxyClass: * @bind_valist: Virtual function called to bind parameters. * @new_call: Virtual function called to construct a new #RestProxyCall. * @simple_run_valist: Virtual function called when making a "simple" call. * * Class structure for #RestProxy for subclasses to implement specialised * behaviour. * * Typically subclasses will override @new_call to construct a subclass of * #RestProxyCall. */ struct _RestProxyClass { /*< private >*/ GObjectClass parent_class; /*< public >*/ gboolean (*bind_valist)(RestProxy *proxy, va_list params); RestProxyCall *(*new_call)(RestProxy *proxy); gboolean (*simple_run_valist)(RestProxy *proxy, gchar **payload, goffset *len, GError **error, va_list params); gboolean (*authenticate)(RestProxy *proxy, RestProxyAuth *auth, gboolean retrying); /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[7]; }; #define REST_PROXY_ERROR rest_proxy_error_quark () /** * RestProxyError: * * Error domain used when returning errors from a #RestProxy. */ typedef enum { REST_PROXY_ERROR_CANCELLED = 1, REST_PROXY_ERROR_RESOLUTION, REST_PROXY_ERROR_CONNECTION, REST_PROXY_ERROR_SSL, REST_PROXY_ERROR_IO, REST_PROXY_ERROR_FAILED, REST_PROXY_ERROR_HTTP_MULTIPLE_CHOICES = 300, REST_PROXY_ERROR_HTTP_MOVED_PERMANENTLY = 301, REST_PROXY_ERROR_HTTP_FOUND = 302, REST_PROXY_ERROR_HTTP_SEE_OTHER = 303, REST_PROXY_ERROR_HTTP_NOT_MODIFIED = 304, REST_PROXY_ERROR_HTTP_USE_PROXY = 305, REST_PROXY_ERROR_HTTP_THREEOHSIX = 306, REST_PROXY_ERROR_HTTP_TEMPORARY_REDIRECT = 307, REST_PROXY_ERROR_HTTP_BAD_REQUEST = 400, REST_PROXY_ERROR_HTTP_UNAUTHORIZED = 401, REST_PROXY_ERROR_HTTP_FOUROHTWO = 402, REST_PROXY_ERROR_HTTP_FORBIDDEN = 403, REST_PROXY_ERROR_HTTP_NOT_FOUND = 404, REST_PROXY_ERROR_HTTP_METHOD_NOT_ALLOWED = 405, REST_PROXY_ERROR_HTTP_NOT_ACCEPTABLE = 406, REST_PROXY_ERROR_HTTP_PROXY_AUTHENTICATION_REQUIRED = 407, REST_PROXY_ERROR_HTTP_REQUEST_TIMEOUT = 408, REST_PROXY_ERROR_HTTP_CONFLICT = 409, REST_PROXY_ERROR_HTTP_GONE = 410, REST_PROXY_ERROR_HTTP_LENGTH_REQUIRED = 411, REST_PROXY_ERROR_HTTP_PRECONDITION_FAILED = 412, REST_PROXY_ERROR_HTTP_REQUEST_ENTITY_TOO_LARGE = 413, REST_PROXY_ERROR_HTTP_REQUEST_URI_TOO_LONG = 414, REST_PROXY_ERROR_HTTP_UNSUPPORTED_MEDIA_TYPE = 415, REST_PROXY_ERROR_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416, REST_PROXY_ERROR_HTTP_EXPECTATION_FAILED = 417, REST_PROXY_ERROR_HTTP_INTERNAL_SERVER_ERROR = 500, REST_PROXY_ERROR_HTTP_NOT_IMPLEMENTED = 501, REST_PROXY_ERROR_HTTP_BAD_GATEWAY = 502, REST_PROXY_ERROR_HTTP_SERVICE_UNAVAILABLE = 503, REST_PROXY_ERROR_HTTP_GATEWAY_TIMEOUT = 504, REST_PROXY_ERROR_HTTP_HTTP_VERSION_NOT_SUPPORTED = 505, } RestProxyError; GQuark rest_proxy_error_quark (void); GType rest_proxy_get_type (void); RestProxy *rest_proxy_new (const gchar *url_format, gboolean binding_required); RestProxy * rest_proxy_new_with_authentication (const gchar *url_format, gboolean binding_required, const gchar *username, const gchar *password); gboolean rest_proxy_bind (RestProxy *proxy, ...); gboolean rest_proxy_bind_valist (RestProxy *proxy, va_list params); void rest_proxy_set_user_agent (RestProxy *proxy, const char *user_agent); const gchar *rest_proxy_get_user_agent (RestProxy *proxy); RestProxyCall *rest_proxy_new_call (RestProxy *proxy); G_GNUC_NULL_TERMINATED gboolean rest_proxy_simple_run (RestProxy *proxy, gchar **payload, goffset *len, GError **error, ...); gboolean rest_proxy_simple_run_valist (RestProxy *proxy, gchar **payload, goffset *len, GError **error, va_list params); G_END_DECLS #endif /* _REST_PROXY */ librest/rest/test-runner.c0000664000175000017500000000226112014274315014221 0ustar bobbob/* * librest - RESTful web services access * Copyright (C) 2009 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include #include #define test_add(unit_name, func) G_STMT_START { \ extern void func (void); \ g_test_add_func (unit_name, func); } G_STMT_END int main (int argc, char *argv[]) { g_type_init (); g_test_init (&argc, &argv, NULL); test_add ("/oauth/param-encoding", test_param_encoding); return g_test_run (); } librest/rest/rest-xml-parser.h0000664000175000017500000000402212014274315015002 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_XML_PARSER #define _REST_XML_PARSER #include #include G_BEGIN_DECLS #define REST_TYPE_XML_PARSER rest_xml_parser_get_type() #define REST_XML_PARSER(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), REST_TYPE_XML_PARSER, RestXmlParser)) #define REST_XML_PARSER_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), REST_TYPE_XML_PARSER, RestXmlParserClass)) #define REST_IS_XML_PARSER(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), REST_TYPE_XML_PARSER)) #define REST_IS_XML_PARSER_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), REST_TYPE_XML_PARSER)) #define REST_XML_PARSER_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), REST_TYPE_XML_PARSER, RestXmlParserClass)) typedef struct { GObject parent; } RestXmlParser; typedef struct { GObjectClass parent_class; } RestXmlParserClass; GType rest_xml_parser_get_type (void); RestXmlParser *rest_xml_parser_new (void); RestXmlNode *rest_xml_parser_parse_from_data (RestXmlParser *parser, const gchar *data, goffset len); G_END_DECLS #endif /* _REST_XML_PARSER */ librest/rest/oauth2-proxy-private.h0000664000175000017500000000222412014274314015767 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _OAUTH2_PROXY_PRIVATE #define _OAUTH2_PROXY_PRIVATE #include "oauth2-proxy.h" struct _OAuth2ProxyPrivate { char *client_id; char *auth_endpoint; char *access_token; }; #endif /* _OAUTH2_PROXY_PRIVATE */ librest/rest/oauth-proxy-call.h0000664000175000017500000000402212014274314015144 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _OAUTH_PROXY_CALL #define _OAUTH_PROXY_CALL #include G_BEGIN_DECLS #define OAUTH_TYPE_PROXY_CALL oauth_proxy_call_get_type() #define OAUTH_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), OAUTH_TYPE_PROXY_CALL, OAuthProxyCall)) #define OAUTH_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), OAUTH_TYPE_PROXY_CALL, OAuthProxyCallClass)) #define OAUTH_IS_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), OAUTH_TYPE_PROXY_CALL)) #define OAUTH_IS_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), OAUTH_TYPE_PROXY_CALL)) #define OAUTH_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), OAUTH_TYPE_PROXY_CALL, OAuthProxyCallClass)) /** * OAuthProxyCall: * * #OAuthProxyCall has no publicly available members. */ typedef struct { RestProxyCall parent; } OAuthProxyCall; typedef struct { RestProxyCallClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } OAuthProxyCallClass; GType oauth_proxy_call_get_type (void); void oauth_proxy_call_parse_token_reponse (OAuthProxyCall *call); G_END_DECLS #endif /* _OAUTH_PROXY_CALL */ librest/rest/rest-xml-node.h0000664000175000017500000000472312014274315014443 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2011 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Tomas Frydrych * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_XML_NODE #define _REST_XML_NODE #include G_BEGIN_DECLS #define REST_TYPE_XML_NODE rest_xml_node_get_type () /** * RestXmlNode: * @name: the name of the element * @content: the textual content of the element * @children: a #GHashTable of string name to #RestXmlNode for the children of * the element. * @attrs: a #GHashTable of string name to string values for the attributes of * the element. * @next: the sibling #RestXmlNode with the same name */ typedef struct _RestXmlNode RestXmlNode; struct _RestXmlNode { /*< private >*/ volatile int ref_count; /*< public >*/ gchar *name; gchar *content; GHashTable *children; GHashTable *attrs; RestXmlNode *next; }; GType rest_xml_node_get_type (void); RestXmlNode *rest_xml_node_ref (RestXmlNode *node); void rest_xml_node_unref (RestXmlNode *node); const gchar *rest_xml_node_get_attr (RestXmlNode *node, const gchar *attr_name); RestXmlNode *rest_xml_node_find (RestXmlNode *start, const gchar *tag); RestXmlNode *rest_xml_node_add_child (RestXmlNode *parent, const char *tag); char *rest_xml_node_print (RestXmlNode *node); void rest_xml_node_add_attr (RestXmlNode *node, const char *attribute, const char *value); void rest_xml_node_set_content (RestXmlNode *node, const char *value); G_GNUC_DEPRECATED void rest_xml_node_free (RestXmlNode *node); G_END_DECLS #endif /* _REST_XML_NODE */ librest/rest/rest-main.c0000664000175000017500000000271012014274314013630 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "rest-private.h" guint rest_debug_flags = 0; /* * "Private" function used to set debugging flags based on environment * variables. Called upon entry into all public functions. */ void _rest_setup_debugging (void) { static gboolean setup_done = FALSE; static const GDebugKey keys[] = { { "xml-parser", REST_DEBUG_XML_PARSER }, { "proxy", REST_DEBUG_PROXY } }; if (G_LIKELY (setup_done)) return; rest_debug_flags = g_parse_debug_string (g_getenv ("REST_DEBUG"), keys, G_N_ELEMENTS (keys)); setup_done = TRUE; } librest/rest/rest-param.h0000664000175000017500000000575712014274315014030 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Ross Burton * Rob Bradford * * RestParam is inspired by libsoup's SoupBuffer * Copyright (C) 2000-2030 Ximian, Inc * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PARAM #define _REST_PARAM #include G_BEGIN_DECLS #define REST_TYPE_PARAM (gtk_css_section_get_type ()) /** * RestMemoryUse: * @REST_MEMORY_STATIC: the memory block can be assumed to always exist for the * lifetime of the parameter, #RestParam will use it directly. * @REST_MEMORY_TAKE: #RestParam will take ownership of the memory block, and * g_free() it when it isn't used. * @REST_MEMORY_COPY: #RestParam will make a copy of the memory block. */ typedef enum { REST_MEMORY_STATIC, REST_MEMORY_TAKE, REST_MEMORY_COPY, } RestMemoryUse; typedef struct _RestParam RestParam; GType rest_param_get_type (void) G_GNUC_CONST; RestParam *rest_param_new_string (const char *name, RestMemoryUse use, const char *string); RestParam *rest_param_new_full (const char *name, RestMemoryUse use, gconstpointer data, gsize length, const char *content_type, const char *filename); RestParam *rest_param_new_with_owner (const char *name, gconstpointer data, gsize length, const char *content_type, const char *filename, gpointer owner, GDestroyNotify owner_dnotify); gboolean rest_param_is_string (RestParam *param); const char *rest_param_get_name (RestParam *param); const char *rest_param_get_content_type (RestParam *param); const char *rest_param_get_file_name (RestParam *param); gconstpointer rest_param_get_content (RestParam *param); gsize rest_param_get_content_length (RestParam *param); RestParam *rest_param_ref (RestParam *param); void rest_param_unref (RestParam *param); G_END_DECLS #endif /* _REST_PARAM */ librest/rest/oauth-proxy-call.c0000664000175000017500000002347412014274314015153 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include "oauth-proxy-call.h" #include "oauth-proxy-private.h" #include "rest-proxy-call-private.h" #include "sha1.h" G_DEFINE_TYPE (OAuthProxyCall, oauth_proxy_call, REST_TYPE_PROXY_CALL) #define OAUTH_ENCODE_STRING(x_) (x_ ? soup_uri_encode( (x_), "!$&'()*+,;=@") : g_strdup ("")) static char * sign_plaintext (OAuthProxyPrivate *priv) { char *cs; char *ts; char *rv; cs = OAUTH_ENCODE_STRING (priv->consumer_secret); ts = OAUTH_ENCODE_STRING (priv->token_secret); rv = g_strconcat (cs, "&", ts, NULL); g_free (cs); g_free (ts); return rv; } static char * encode_params (GHashTable *hash) { GList *l, *keys; GString *s; s = g_string_new (NULL); keys = g_hash_table_get_keys (hash); keys = g_list_sort (keys, (GCompareFunc)strcmp); for (l = keys; l; l = l->next) { const char *key; const char *value; char *k, *v; key = l->data; value = g_hash_table_lookup (hash, key); k = OAUTH_ENCODE_STRING (key); v = OAUTH_ENCODE_STRING (value); if (s->len) g_string_append (s, "&"); g_string_append_printf (s, "%s=%s", k, v); g_free (k); g_free (v); } g_list_free (keys); return g_string_free (s, FALSE); } /* * Add the keys in @from to @hash. */ static void merge_hashes (GHashTable *hash, GHashTable *from) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter, from); while (g_hash_table_iter_next (&iter, &key, &value)) { g_hash_table_insert (hash, key, value); } } static void merge_params (GHashTable *hash, RestParams *params) { RestParamsIter iter; const char *name; RestParam *param; rest_params_iter_init (&iter, params); while (rest_params_iter_next (&iter, &name, ¶m)) { if (rest_param_is_string (param)) g_hash_table_insert (hash, (gpointer)name, (gpointer)rest_param_get_content (param)); } } static char * sign_hmac (OAuthProxy *proxy, RestProxyCall *call, GHashTable *oauth_params) { OAuthProxyPrivate *priv; RestProxyCallPrivate *callpriv; char *key, *signature, *ep, *eep; GString *text; GHashTable *all_params; priv = PROXY_GET_PRIVATE (proxy); callpriv = call->priv; text = g_string_new (NULL); g_string_append (text, rest_proxy_call_get_method (REST_PROXY_CALL (call))); g_string_append_c (text, '&'); if (priv->oauth_echo) { g_string_append_uri_escaped (text, priv->service_url, NULL, FALSE); } else if (priv->signature_host != NULL) { SoupURI *url = soup_uri_new (callpriv->url); gchar *signing_url; soup_uri_set_host (url, priv->signature_host); signing_url = soup_uri_to_string (url, FALSE); g_string_append_uri_escaped (text, signing_url, NULL, FALSE); soup_uri_free (url); g_free (signing_url); } else { g_string_append_uri_escaped (text, callpriv->url, NULL, FALSE); } g_string_append_c (text, '&'); /* Merge the OAuth parameters with the query parameters */ all_params = g_hash_table_new (g_str_hash, g_str_equal); merge_hashes (all_params, oauth_params); if (!priv->oauth_echo) merge_params (all_params, callpriv->params); ep = encode_params (all_params); eep = OAUTH_ENCODE_STRING (ep); g_string_append (text, eep); g_free (ep); g_free (eep); g_hash_table_destroy (all_params); /* PLAINTEXT signature value is the HMAC-SHA1 key value */ key = sign_plaintext (priv); signature = hmac_sha1 (key, text->str); g_free (key); g_string_free (text, TRUE); return signature; } /* * From the OAuth parameters in @params, construct a HTTP Authorized header. */ static char * make_authorized_header (GHashTable *oauth_params) { GString *auth; GHashTableIter iter; const char *key, *value; g_assert (oauth_params); /* TODO: is "" okay for the realm, or should this be magically calculated or a parameter? */ auth = g_string_new ("OAuth realm=\"\""); g_hash_table_iter_init (&iter, oauth_params); while (g_hash_table_iter_next (&iter, (gpointer)&key, (gpointer)&value)) { gchar *encoded_value = OAUTH_ENCODE_STRING (value); g_string_append_printf (auth, ", %s=\"%s\"", key, encoded_value); g_free (encoded_value); } return g_string_free (auth, FALSE); } /* * Remove any OAuth parameters from the @call parameters and add them to * @oauth_params for building an Authorized header with. */ static void steal_oauth_params (RestProxyCall *call, GHashTable *oauth_params) { RestParams *params; RestParamsIter iter; const char *name; RestParam *param; GList *to_remove = NULL; params = rest_proxy_call_get_params (call); rest_params_iter_init (&iter, params); while (rest_params_iter_next (&iter, &name, ¶m)) { if (rest_param_is_string (param) && g_str_has_prefix (name, "oauth_")) { g_hash_table_insert (oauth_params, g_strdup (name), g_strdup (rest_param_get_content (param))); to_remove = g_list_prepend (to_remove, g_strdup (name)); } } while (to_remove) { rest_params_remove (params, to_remove->data); to_remove = g_list_delete_link (to_remove, to_remove); } } static gboolean _prepare (RestProxyCall *call, GError **error) { OAuthProxy *proxy = NULL; OAuthProxyPrivate *priv; char *s; GHashTable *oauth_params; g_object_get (call, "proxy", &proxy, NULL); priv = PROXY_GET_PRIVATE (proxy); /* We have to make this hash free the strings and thus duplicate when we put * them in since when we call call steal_oauth_params that has to duplicate * the param names since it removes them from the main hash */ oauth_params = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); /* First, steal any OAuth properties in the regular params */ steal_oauth_params (call, oauth_params); g_hash_table_insert (oauth_params, g_strdup ("oauth_version"), g_strdup ("1.0")); s = g_strdup_printf ("%"G_GINT64_FORMAT , (gint64) time (NULL)); g_hash_table_insert (oauth_params, g_strdup ("oauth_timestamp"), s); s = g_strdup_printf ("%u", g_random_int ()); g_hash_table_insert (oauth_params, g_strdup ("oauth_nonce"), s); g_hash_table_insert (oauth_params, g_strdup ("oauth_consumer_key"), g_strdup (priv->consumer_key)); if (priv->token) g_hash_table_insert (oauth_params, g_strdup ("oauth_token"), g_strdup (priv->token)); switch (priv->method) { case PLAINTEXT: g_hash_table_insert (oauth_params, g_strdup ("oauth_signature_method"), g_strdup ("PLAINTEXT")); s = sign_plaintext (priv); break; case HMAC_SHA1: g_hash_table_insert (oauth_params, g_strdup ("oauth_signature_method"), g_strdup ("HMAC-SHA1")); s = sign_hmac (proxy, call, oauth_params); break; } g_hash_table_insert (oauth_params, g_strdup ("oauth_signature"), s); s = make_authorized_header (oauth_params); if (priv->oauth_echo) { rest_proxy_call_add_header (call, "X-Verify-Credentials-Authorization", s); rest_proxy_call_add_param (call, "X-Auth-Service-Provider", priv->service_url); } else { rest_proxy_call_add_header (call, "Authorization", s); } g_free (s); g_hash_table_destroy (oauth_params); g_object_unref (proxy); return TRUE; } static void oauth_proxy_call_class_init (OAuthProxyCallClass *klass) { RestProxyCallClass *call_class = REST_PROXY_CALL_CLASS (klass); call_class->prepare = _prepare; } static void oauth_proxy_call_init (OAuthProxyCall *self) { } void oauth_proxy_call_parse_token_reponse (OAuthProxyCall *call) { OAuthProxyPrivate *priv; GHashTable *form; /* TODO: sanity checks, error handling, probably return gboolean */ g_return_if_fail (OAUTH_IS_PROXY_CALL (call)); priv = PROXY_GET_PRIVATE (REST_PROXY_CALL (call)->priv->proxy); g_assert (priv); form = soup_form_decode (rest_proxy_call_get_payload (REST_PROXY_CALL (call))); priv->token = g_strdup (g_hash_table_lookup (form, "oauth_token")); priv->token_secret = g_strdup (g_hash_table_lookup (form, "oauth_token_secret")); /* This header should only exist for request_token replies, but its easier just to always check it */ priv->oauth_10a = g_hash_table_lookup (form, "oauth_callback_confirmed") != NULL; g_hash_table_destroy (form); } #if BUILD_TESTS /* Test cases from http://wiki.oauth.net/TestCases */ void test_param_encoding (void) { GHashTable *hash; char *s; #define TEST(expected) \ s = encode_params (hash); \ g_assert_cmpstr (s, ==, expected); \ g_free (s); \ g_hash_table_remove_all (hash); hash = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (hash, "name", NULL); TEST("name="); g_hash_table_insert (hash, "a", "b"); TEST("a=b"); g_hash_table_insert (hash, "a", "b"); g_hash_table_insert (hash, "c", "d"); TEST("a=b&c=d"); /* Because we don't (yet) support multiple parameters with the same key we've changed this case slightly */ g_hash_table_insert (hash, "b", "x!y"); g_hash_table_insert (hash, "a", "x y"); TEST("a=x%20y&b=x%21y"); #undef TEST } #endif librest/rest/oauth2-proxy-call.h0000664000175000017500000000404512014274314015233 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _OAUTH2_PROXY_CALL #define _OAUTH2_PROXY_CALL #include G_BEGIN_DECLS #define OAUTH2_TYPE_PROXY_CALL oauth2_proxy_call_get_type() #define OAUTH2_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), OAUTH2_TYPE_PROXY_CALL, OAuth2ProxyCall)) #define OAUTH2_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), OAUTH2_TYPE_PROXY_CALL, OAuth2ProxyCallClass)) #define OAUTH2_IS_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), OAUTH2_TYPE_PROXY_CALL)) #define OAUTH2_IS_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), OAUTH2_TYPE_PROXY_CALL)) #define OAUTH2_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), OAUTH2_TYPE_PROXY_CALL, OAuth2ProxyCallClass)) /** * OAuth2ProxyCall: * * #OAuth2ProxyCall has no publicly available members. */ typedef struct { RestProxyCall parent; } OAuth2ProxyCall; typedef struct { RestProxyCallClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } OAuth2ProxyCallClass; GType oauth2_proxy_call_get_type (void); G_END_DECLS #endif /* _OAUTH2_PROXY_CALL */ librest/rest/rest-xml-parser.c0000664000175000017500000001467612014274315015015 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "rest-private.h" #include "rest-xml-parser.h" G_DEFINE_TYPE (RestXmlParser, rest_xml_parser, G_TYPE_OBJECT) #define G(x) (gchar *)x static void rest_xml_parser_class_init (RestXmlParserClass *klass) { } static void rest_xml_parser_init (RestXmlParser *self) { } /** * rest_xml_parser_new: * * Create a new #RestXmlParser, for parsing XML documents. * * Returns: a new #RestXmlParser. */ RestXmlParser * rest_xml_parser_new (void) { return g_object_new (REST_TYPE_XML_PARSER, NULL); } /** * rest_xml_parser_parse_from_data: * @parser: a #RestXmlParser * @data: the XML content to parse * @len: the length of @data, or -1 if @data is a nul-terminated string * * Parse the XML in @data, and return a new #RestXmlNode. If @data is invalid * XML, %NULL is returned. * * Returns: a new #RestXmlNode, or %NULL if the XML was invalid. */ RestXmlNode * rest_xml_parser_parse_from_data (RestXmlParser *parser, const gchar *data, goffset len) { xmlTextReaderPtr reader; RestXmlNode *cur_node = NULL; RestXmlNode *new_node = NULL; RestXmlNode *tmp_node = NULL; RestXmlNode *root_node = NULL; RestXmlNode *node = NULL; const gchar *name = NULL; const gchar *attr_name = NULL; const gchar *attr_value = NULL; GQueue nodes = G_QUEUE_INIT; g_return_val_if_fail (REST_IS_XML_PARSER (parser), NULL); if (len == -1) len = strlen (data); _rest_setup_debugging (); reader = xmlReaderForMemory (data, len, NULL, /* URL? */ NULL, /* encoding */ XML_PARSE_RECOVER | XML_PARSE_NOCDATA); while (xmlTextReaderRead (reader) == 1) { switch (xmlTextReaderNodeType (reader)) { case XML_READER_TYPE_ELEMENT: /* Lookup the "name" for the tag */ name = G(xmlTextReaderConstName (reader)); REST_DEBUG (XML_PARSER, "Opening tag: %s", name); /* Create our new node for this tag */ new_node = _rest_xml_node_new (); new_node->name = G (g_intern_string (name)); if (!root_node) { root_node = new_node; } /* * Check if we are not the root node because we need to update it's * children set to include the new node. */ if (cur_node) { tmp_node = g_hash_table_lookup (cur_node->children, new_node->name); if (tmp_node) { REST_DEBUG (XML_PARSER, "Existing node found for this name. " "Prepending to the list."); g_hash_table_insert (cur_node->children, G(tmp_node->name), _rest_xml_node_prepend (tmp_node, new_node)); } else { REST_DEBUG (XML_PARSER, "Unseen name. Adding to the children table."); g_hash_table_insert (cur_node->children, G(new_node->name), new_node); } } /* * Check for empty element. If empty we needn't worry about children * or text and thus we don't need to update the stack or state */ if (xmlTextReaderIsEmptyElement (reader)) { REST_DEBUG (XML_PARSER, "We have an empty element. No children or text."); } else { REST_DEBUG (XML_PARSER, "Non-empty element found." " Pushing to stack and updating current state."); g_queue_push_head (&nodes, new_node); cur_node = new_node; } /* * Check if we have attributes. These get stored in the node's attrs * hash table. */ if (xmlTextReaderHasAttributes (reader)) { xmlTextReaderMoveToFirstAttribute (reader); do { attr_name = G(xmlTextReaderConstLocalName (reader)); attr_value = G(xmlTextReaderConstValue (reader)); g_hash_table_insert (new_node->attrs, g_strdup (attr_name), g_strdup (attr_value)); REST_DEBUG (XML_PARSER, "Attribute found: %s = %s", attr_name, attr_value); } while (xmlTextReaderMoveToNextAttribute (reader) == 1); } break; case XML_READER_TYPE_END_ELEMENT: REST_DEBUG (XML_PARSER, "Closing tag: %s", xmlTextReaderConstLocalName (reader)); REST_DEBUG (XML_PARSER, "Popping from stack and updating state."); /* For those children that have siblings, reverse the siblings */ node = (RestXmlNode *)g_queue_pop_head (&nodes); _rest_xml_node_reverse_children_siblings (node); /* Update the current node to the new top of the stack */ cur_node = (RestXmlNode *)g_queue_peek_head (&nodes); if (cur_node) { REST_DEBUG (XML_PARSER, "Head is now %s", cur_node->name); } else { REST_DEBUG (XML_PARSER, "At the top level"); } break; case XML_READER_TYPE_TEXT: cur_node->content = g_strdup (G(xmlTextReaderConstValue (reader))); REST_DEBUG (XML_PARSER, "Text content found: %s", cur_node->content); default: REST_DEBUG (XML_PARSER, "Found unknown content with type: 0x%x", xmlTextReaderNodeType (reader)); break; } } xmlTextReaderClose (reader); xmlFreeTextReader (reader); return root_node; } librest/rest/oauth-proxy-private.h0000664000175000017500000000265012014274314015710 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "oauth-proxy.h" #define PROXY_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), OAUTH_TYPE_PROXY, OAuthProxyPrivate)) typedef struct { /* Application "consumer" keys */ char *consumer_key; char *consumer_secret; /* Authorisation "user" tokens */ char *token; char *token_secret; /* How we're signing */ OAuthSignatureMethod method; /* OAuth 1.0a */ gboolean oauth_10a; char *verifier; /* OAuth Echo */ gboolean oauth_echo; char *service_url; /* URL to use for signatures */ char *signature_host; } OAuthProxyPrivate; librest/rest/oauth2-proxy-call.c0000664000175000017500000000374312014274314015232 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include "oauth2-proxy-call.h" #include "oauth2-proxy-private.h" #include "rest-proxy-call-private.h" #include "sha1.h" G_DEFINE_TYPE (OAuth2ProxyCall, oauth2_proxy_call, REST_TYPE_PROXY_CALL) static gboolean _prepare (RestProxyCall *call, GError **error) { OAuth2Proxy *proxy = NULL; gboolean result = TRUE; g_object_get (call, "proxy", &proxy, NULL); if (!proxy->priv->access_token) { g_set_error (error, REST_PROXY_CALL_ERROR, REST_PROXY_CALL_FAILED, "Missing access token, web service not properly authenticated"); result = FALSE; } else { rest_proxy_call_add_param (call, "access_token", proxy->priv->access_token); } g_object_unref (proxy); return result; } static void oauth2_proxy_call_class_init (OAuth2ProxyCallClass *klass) { RestProxyCallClass *call_class = REST_PROXY_CALL_CLASS (klass); call_class->prepare = _prepare; } static void oauth2_proxy_call_init (OAuth2ProxyCall *self) { } librest/rest/sha1.c0000664000175000017500000000607712014274315012600 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "sha1.h" #define SHA1_BLOCK_SIZE 64 #define SHA1_LENGTH 20 /* * hmac_sha1: * @key: The key * @message: The message * * Given the key and message, compute the HMAC-SHA1 hash and return the base-64 * encoding of it. This is very geared towards OAuth, and as such both key and * message must be NULL-terminated strings, and the result is base-64 encoded. */ char * hmac_sha1 (const char *key, const char *message) { GChecksum *checksum; char *real_key; guchar ipad[SHA1_BLOCK_SIZE]; guchar opad[SHA1_BLOCK_SIZE]; guchar inner[SHA1_LENGTH]; guchar digest[SHA1_LENGTH]; gsize key_length, inner_length, digest_length; int i; g_return_val_if_fail (key, NULL); g_return_val_if_fail (message, NULL); checksum = g_checksum_new (G_CHECKSUM_SHA1); /* If the key is longer than the block size, hash it first */ if (strlen (key) > SHA1_BLOCK_SIZE) { guchar new_key[SHA1_LENGTH]; key_length = sizeof (new_key); g_checksum_update (checksum, (guchar*)key, strlen (key)); g_checksum_get_digest (checksum, new_key, &key_length); g_checksum_reset (checksum); real_key = g_memdup (new_key, key_length); } else { real_key = g_strdup (key); key_length = strlen (key); } /* Sanity check the length */ g_assert (key_length <= SHA1_BLOCK_SIZE); /* Protect against use of the provided key by NULLing it */ key = NULL; /* Stage 1 */ memset (ipad, 0, sizeof (ipad)); memset (opad, 0, sizeof (opad)); memcpy (ipad, real_key, key_length); memcpy (opad, real_key, key_length); /* Stage 2 and 5 */ for (i = 0; i < sizeof (ipad); i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5C; } /* Stage 3 and 4 */ g_checksum_update (checksum, ipad, sizeof (ipad)); g_checksum_update (checksum, (guchar*)message, strlen (message)); inner_length = sizeof (inner); g_checksum_get_digest (checksum, inner, &inner_length); g_checksum_reset (checksum); /* Stage 6 and 7 */ g_checksum_update (checksum, opad, sizeof (opad)); g_checksum_update (checksum, inner, inner_length); digest_length = sizeof (digest); g_checksum_get_digest (checksum, digest, &digest_length); g_checksum_free (checksum); g_free (real_key); return g_base64_encode (digest, digest_length); } librest/rest/rest-proxy-auth.h0000664000175000017500000000405712014274315015040 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2012, Red Hat, Inc. * * Authors: Christophe Fergeau * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef _REST_PROXY_AUTH #define _REST_PROXY_AUTH #include G_BEGIN_DECLS #define REST_TYPE_PROXY_AUTH rest_proxy_auth_get_type() #define REST_PROXY_AUTH(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), REST_TYPE_PROXY_AUTH, RestProxyAuth)) #define REST_PROXY_AUTH_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), REST_TYPE_PROXY_AUTH, RestProxyAuthClass)) #define REST_IS_PROXY_AUTH(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), REST_TYPE_PROXY_AUTH)) #define REST_IS_PROXY_AUTH_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), REST_TYPE_PROXY_AUTH)) #define REST_PROXY_AUTH_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), REST_TYPE_PROXY_AUTH, RestProxyAuthClass)) typedef struct _RestProxyAuthPrivate RestProxyAuthPrivate; /** * RestProxyAuth: * * #RestProxyAuth has no publicly available members. */ typedef struct { GObject parent; RestProxyAuthPrivate *priv; } RestProxyAuth; typedef struct { GObjectClass parent_class; /*< private >*/ /* padding for future expansion */ gpointer _padding_dummy[8]; } RestProxyAuthClass; GType rest_proxy_auth_get_type (void); void rest_proxy_auth_pause (RestProxyAuth *auth); void rest_proxy_auth_unpause (RestProxyAuth *auth); G_END_DECLS #endif /* _REST_PROXY_AUTH */ librest/rest/rest-param.c0000664000175000017500000002072012014274314014005 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Ross Burton * Rob Bradford * * RestParam is inspired by libsoup's SoupBuffer * Copyright (C) 2000-2030 Ximian, Inc * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "rest-param.h" /** * SECTION:rest-param * @short_description: Name/value parameter data type with intelligent memory * management * @see_also: #RestParams, #RestProxyCall. */ /* Internal RestMemoryUse values */ enum { REST_MEMORY_OWNED = REST_MEMORY_COPY + 1 }; struct _RestParam { char *name; RestMemoryUse use; gconstpointer data; gsize length; const char *content_type; char *filename; volatile gint ref_count; gpointer owner; GDestroyNotify owner_dnotify; }; G_DEFINE_BOXED_TYPE (RestParam, rest_param, rest_param_ref, rest_param_unref) /** * rest_param_new_full: * @name: the parameter name * @use: the #RestMemoryUse describing how the memory can be used * @data: (array length=length) (element-type guint8): a pointer to * the start of the data * @length: the length of the data * @content_type: the content type of the data * @filename: the original filename, or %NULL * * Create a new #RestParam called @name with @length bytes of @data as the * value. @content_type is the type of the data as a MIME type, for example * "text/plain" for simple string parameters. * * If the parameter is a file upload it can be passed as @filename. * * Returns: a new #RestParam. **/ RestParam * rest_param_new_full (const char *name, RestMemoryUse use, gconstpointer data, gsize length, const char *content_type, const char *filename) { RestParam *param; param = g_slice_new0 (RestParam); if (use == REST_MEMORY_COPY) { data = g_memdup (data, length); use = REST_MEMORY_TAKE; } param->name = g_strdup (name); param->use = use; param->data = data; param->length = length; param->content_type = g_intern_string (content_type); param->filename = g_strdup (filename); param->ref_count = 1; if (use == REST_MEMORY_TAKE) { param->owner = (gpointer)data; param->owner_dnotify = g_free; } return param; } /** * rest_param_new_with_owner: * @name: the parameter name * @data: (array length=length) (element-type guint8): a pointer to * the start of the data * @length: the length of the data * @content_type: the content type of the data * @filename: (allow-none): the original filename, or %NULL * @owner: (transfer full): pointer to an object that owns @data * @owner_dnotify: (allow-none): a function to free/unref @owner when * the buffer is freed * * Create a new #RestParam called @name with @length bytes of @data as the * value. @content_type is the type of the data as a MIME type, for example * "text/plain" for simple string parameters. * * If the parameter is a file upload it can be passed as @filename. * * When the #RestParam is freed, it will call @owner_dnotify, passing @owner to * it. This allows you to do something like this: * * |[ * GMappedFile *map = g_mapped_file_new (filename, FALSE, &error); * RestParam *param = rest_param_new_with_owner ("media", * g_mapped_file_get_contents (map), * g_mapped_file_get_length (map), * "image/jpeg", * filename, * map, * (GDestroyNotify)g_mapped_file_unref); * ]| * * Returns: a new #RestParam. **/ RestParam * rest_param_new_with_owner (const char *name, gconstpointer data, gsize length, const char *content_type, const char *filename, gpointer owner, GDestroyNotify owner_dnotify) { RestParam *param; param = g_slice_new0 (RestParam); param->name = g_strdup (name); param->use = REST_MEMORY_OWNED; param->data = data; param->length = length; param->content_type = g_intern_string (content_type); param->filename = g_strdup (filename); param->ref_count = 1; param->owner = owner; param->owner_dnotify = owner_dnotify; return param; } /** * rest_param_new_string: * @name: the parameter name * @use: the #RestMemoryUse describing how the memory can be used * @string: the parameter value * * A convience constructor to create a #RestParam from a given UTF-8 string. * The resulting #RestParam will have a content type of "text/plain". * * Returns: a new #RestParam. **/ RestParam * rest_param_new_string (const char *name, RestMemoryUse use, const char *string) { if (string == NULL) { use = REST_MEMORY_STATIC; string = ""; } return rest_param_new_full (name, use, string, strlen (string) + 1, g_intern_static_string ("text/plain"), NULL); } /** * rest_param_get_name: * @param: a valid #RestParam * * Get the name of the parameter. * * Returns: the parameter name. **/ const char * rest_param_get_name (RestParam *param) { return param->name; } /** * rest_param_get_content_type: * @param: a valid #RestParam * * Get the MIME type of the parameter. For example, basic strings have the MIME * type "text/plain". * * Returns: the MIME type **/ const char * rest_param_get_content_type (RestParam *param) { return param->content_type; } /** * rest_param_get_file_name: * @param: a valid #RestParam * * Get the original file name of the parameter, if one is available. * * Returns: the filename if set, or %NULL. **/ const char * rest_param_get_file_name (RestParam *param) { return param->filename; } /** * rest_param_is_string: * @param: a valid #RestParam * * Determine if the parameter is a string value, i.e. the content type is "text/plain". * * Returns: %TRUE if the parameter is a string, %FALSE otherwise. */ gboolean rest_param_is_string (RestParam *param) { return param->content_type == g_intern_static_string ("text/plain"); } /** * rest_param_get_content: * @param: a valid #RestParam * * Get the content of @param. The content should be treated as read-only and * not modified in any way. * * Returns: (transfer none): the content. **/ gconstpointer rest_param_get_content (RestParam *param) { return param->data; } /** * rest_param_get_content_length: * @param: a valid #RestParam * * Get the length of the content of @param. * * Returns: the length of the content **/ gsize rest_param_get_content_length (RestParam *param) { return param->length; } /** * rest_param_ref: * @param: a valid #RestParam * * Increase the reference count on @param. * * Returns: the #RestParam **/ RestParam * rest_param_ref (RestParam *param) { /* TODO: bring back REST_MEMORY_TEMPORARY? */ g_return_val_if_fail (param, NULL); g_return_val_if_fail (param->ref_count > 0, NULL); g_atomic_int_inc (¶m->ref_count); return param; } /** * rest_param_unref: * @param: a valid #RestParam * * Decrease the reference count on @param, destroying it if the reference count * reaches 0. **/ void rest_param_unref (RestParam *param) { g_return_if_fail (param); if (g_atomic_int_dec_and_test (¶m->ref_count)) { if (param->owner_dnotify) param->owner_dnotify (param->owner); g_free (param->name); g_free (param->filename); g_slice_free (RestParam, param); } } librest/rest/rest-params.c0000664000175000017500000001441712014274315014177 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "rest-params.h" /** * SECTION:rest-params * @short_description: Container for call parameters * @see_also: #RestParam, #RestProxyCall. */ /* * RestParams is an alias for GHashTable achieved by opaque types in the public * headers and casting internally. This has several limitations, mainly * supporting multiple parameters with the same name and preserving the ordering * of parameters. * * These are not requirements for the bulk of the web services, but this * limitation does mean librest can't be used for a few web services. * * TODO: this should be a list to support multiple parameters with the same * name. */ /** * rest_params_new: * * Create a new #RestParams. * * Returns: A empty #RestParams. **/ RestParams * rest_params_new (void) { /* The key is a string that is owned by the RestParam, so we don't need to explicitly free it on removal. */ return (RestParams *) g_hash_table_new_full (g_str_hash, g_str_equal, NULL, (GDestroyNotify)rest_param_unref); } /** * rest_params_free: * @params: a valid #RestParams * * Destroy the #RestParams and the #RestParam objects that it contains. **/ void rest_params_free (RestParams *params) { GHashTable *hash = (GHashTable *)params; g_return_if_fail (params); g_hash_table_destroy (hash); } /** * rest_params_add: * @params: a valid #RestParams * @param: a valid #RestParam * * Add @param to @params. **/ void rest_params_add (RestParams *params, RestParam *param) { GHashTable *hash = (GHashTable *)params; g_return_if_fail (params); g_return_if_fail (param); g_hash_table_insert (hash, (gpointer)rest_param_get_name (param), param); } /** * rest_params_get: * @params: a valid #RestParams * @name: a parameter name * * Return the #RestParam called @name, or %NULL if it doesn't exist. * * Returns: a #RestParam or %NULL if the name doesn't exist **/ RestParam * rest_params_get (RestParams *params, const char *name) { GHashTable *hash = (GHashTable *)params; g_return_val_if_fail (params, NULL); g_return_val_if_fail (name, NULL); return g_hash_table_lookup (hash, name); } /** * rest_params_remove: * @params: a valid #RestParams * @name: a parameter name * * Remove the #RestParam called @name. **/ void rest_params_remove (RestParams *params, const char *name) { GHashTable *hash = (GHashTable *)params; g_return_if_fail (params); g_return_if_fail (name); g_hash_table_remove (hash, name); } /** * rest_params_are_strings: * @params: a valid #RestParams * * Checks if the parameters are all simple strings (have a content type of * "text/plain"). * * Returns: %TRUE if all of the parameters are simple strings, %FALSE otherwise. **/ gboolean rest_params_are_strings (RestParams *params) { GHashTable *hash = (GHashTable *)params; GHashTableIter iter; RestParam *param; g_return_val_if_fail (params, FALSE); g_hash_table_iter_init (&iter, hash); while (g_hash_table_iter_next (&iter, NULL, (gpointer)¶m)) { if (!rest_param_is_string (param)) return FALSE; } return TRUE; } /** * rest_params_as_string_hash_table: * @params: a valid #RestParams * * Create a new #GHashTable which contains the name and value of all string * (content type of text/plain) parameters. * * The values are owned by the #RestParams, so don't destroy the #RestParams * before the hash table. * * Returns: (element-type utf8 Rest.Param) (transfer container): a new #GHashTable. **/ GHashTable * rest_params_as_string_hash_table (RestParams *params) { GHashTable *hash, *strings; GHashTableIter iter; const char *name = NULL; RestParam *param = NULL; g_return_val_if_fail (params, NULL); hash = (GHashTable *)params; strings = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_iter_init (&iter, hash); while (g_hash_table_iter_next (&iter, (gpointer)&name, (gpointer)¶m)) { if (rest_param_is_string (param)) g_hash_table_insert (strings, (gpointer)name, (gpointer)rest_param_get_content (param)); } return strings; } /** * rest_params_iter_init: * @iter: an uninitialized #RestParamsIter * @params: a valid #RestParams * * Initialize a parameter iterator over @params. Modifying @params after calling * this function invalidates the returned iterator. * |[ * RestParamsIter iter; * const char *name; * RestParam *param; * * rest_params_iter_init (&iter, params); * while (rest_params_iter_next (&iter, &name, ¶m)) { * /* do something with name and param */ * } * ]| **/ void rest_params_iter_init (RestParamsIter *iter, RestParams *params) { g_return_if_fail (iter); g_return_if_fail (params); g_hash_table_iter_init ((GHashTableIter *)iter, (GHashTable *)params); } /** * rest_params_iter_next: * @iter: an initialized #RestParamsIter * @name: a location to store the name, or %NULL * @param: a location to store the #RestParam, or %NULL * * Advances @iter and retrieves the name and/or parameter that are now pointed * at as a result of this advancement. If FALSE is returned, @name and @param * are not set and the iterator becomes invalid. * * Returns: %FALSE if the end of the #RestParams has been reached, %TRUE otherwise. **/ gboolean rest_params_iter_next (RestParamsIter *iter, const char **name, RestParam **param) { g_return_val_if_fail (iter, FALSE); return g_hash_table_iter_next ((GHashTableIter *)iter, (gpointer)name, (gpointer)param); } librest/docs/0000775000175000017500000000000012014274314011540 5ustar bobboblibrest/docs/Makefile.am0000664000175000017500000000002412014274314013570 0ustar bobbobSUBDIRS = reference librest/docs/reference/0000775000175000017500000000000012014274314013476 5ustar bobboblibrest/docs/reference/Makefile.am0000664000175000017500000000001712014274314015530 0ustar bobbobSUBDIRS = rest librest/docs/reference/rest/0000775000175000017500000000000012014274314014453 5ustar bobboblibrest/docs/reference/rest/Makefile.am0000664000175000017500000000663012014274314016514 0ustar bobbob## Process this file with automake to produce Makefile.in # We require automake 1.6 at least. AUTOMAKE_OPTIONS = 1.6 # This is a blank Makefile.am for using gtk-doc. # Copy this to your project's API docs directory and modify the variables to # suit your project. See the GTK+ Makefiles in gtk+/docs/reference for examples # of using the various options. # The name of the module, e.g. 'glib'. DOC_MODULE=rest DOC_MODULE_VERSION=@API_VERSION@ # The top-level SGML file. You can change this if you want to. DOC_MAIN_SGML_FILE=$(DOC_MODULE)-docs.sgml # The directory containing the source code. Relative to $(srcdir). # gtk-doc will search all .c & .h files beneath here for inline comments # documenting the functions and macros. # e.g. DOC_SOURCE_DIR=../../../gtk DOC_SOURCE_DIR=../../../rest ../../../rest-extras # Extra options to pass to gtkdoc-scangobj. Not normally needed. SCANGOBJ_OPTIONS= # Extra options to supply to gtkdoc-scan. # e.g. SCAN_OPTIONS=--deprecated-guards="GTK_DISABLE_DEPRECATED" SCAN_OPTIONS= # Extra options to supply to gtkdoc-mkdb. # e.g. MKDB_OPTIONS=--sgml-mode --output-format=xml MKDB_OPTIONS=--sgml-mode --output-format=xml # Extra options to supply to gtkdoc-mktmpl # e.g. MKTMPL_OPTIONS=--only-section-tmpl MKTMPL_OPTIONS= # Extra options to supply to gtkdoc-mkhtml MKHTML_OPTIONS= # Extra options to supply to gtkdoc-fixref. Not normally needed. # e.g. FIXXREF_OPTIONS=--extra-dir=../gdk-pixbuf/html --extra-dir=../gdk/html FIXXREF_OPTIONS= # Used for dependencies. The docs will be rebuilt if any of these change. # e.g. HFILE_GLOB=$(top_srcdir)/gtk/*.h # e.g. CFILE_GLOB=$(top_srcdir)/gtk/*.c HFILE_GLOB=$(top_srcdir)/rest/*.h $(top_srcdir)/rest-extras/*.h CFILE_GLOB=$(top_srcdir)/rest/*.c $(top_srcdir)/rest-extras/*.c # Header files to ignore when scanning. # e.g. IGNORE_HFILES=gtkdebug.h gtkintl.h IGNORE_HFILES=sha1.h rest-private.h rest-proxy-call-private.h oauth-proxy-private.h oauth2-proxy-private.h flickr-proxy-private.h lastfm-proxy-private.h # Images to copy into HTML directory. # e.g. HTML_IMAGES=$(top_srcdir)/gtk/stock-icons/stock_about_24.png HTML_IMAGES= # Extra SGML files that are included by $(DOC_MAIN_SGML_FILE). # e.g. content_files=running.sgml building.sgml changes-2.0.sgml content_files= # SGML files where gtk-doc abbrevations (#GtkWidget) are expanded # These files must be listed here *and* in content_files # e.g. expand_content_files=running.sgml expand_content_files= # CFLAGS and LDFLAGS for compiling gtkdoc-scangobj with your library. # Only needed if you are using gtkdoc-scangobj to dynamically query widget # signals and properties. # e.g. INCLUDES=-I$(top_srcdir) -I$(top_builddir) $(GTK_DEBUG_FLAGS) # e.g. GTKDOC_LIBS=$(top_builddir)/gtk/$(gtktargetlib) INCLUDES=-I$(top_srcdir) -I$(top_builddir) $(GLIB_CFLAGS) $(SOUP_CFLAGS) $(XML_CFLAGS) GTKDOC_LIBS=$(top_builddir)/rest/librest-@API_VERSION@.la $(top_builddir)/rest-extras/librest-extras-@API_VERSION@.la \ $(GLIB_LIBS) $(SOUP_LIBS) $(XML_LIBS) # This includes the standard gtk-doc make rules, copied by gtkdocize. include $(top_srcdir)/gtk-doc.make # Other files to distribute # e.g. EXTRA_DIST += version.xml.in EXTRA_DIST += # Files not to distribute # for --rebuild-types in $(SCAN_OPTIONS), e.g. $(DOC_MODULE).types # for --rebuild-sections in $(SCAN_OPTIONS) e.g. $(DOC_MODULE)-sections.txt #DISTCLEANFILES += # Comment this out if you want your docs-status tested during 'make check' #TESTS = $(GTKDOC_CHECK) librest/docs/reference/rest/rest-docs.sgml0000664000175000017500000000221012014274314017235 0ustar bobbob librest Reference Manual Generic Proxies OAuth Proxies Service-specific Proxies XML Parsing librest/docs/reference/rest/rest-overrides.txt0000664000175000017500000000000012014274314020157 0ustar bobboblibrest/docs/reference/rest/rest.types0000664000175000017500000000043712014274314016522 0ustar bobbobflickr_proxy_call_get_type flickr_proxy_get_type lastfm_proxy_call_get_type lastfm_proxy_get_type oauth2_proxy_call_get_type oauth2_proxy_get_type oauth_proxy_call_get_type oauth_proxy_get_type rest_proxy_call_get_type rest_proxy_get_type rest_xml_node_get_type rest_xml_parser_get_type librest/docs/reference/rest/rest-sections.txt0000664000175000017500000001416112014274314020021 0ustar bobbob
rest-xml-parser RestXmlParser RestXmlParser RestXmlNode rest_xml_parser_new rest_xml_parser_parse_from_data rest_xml_node_ref rest_xml_node_unref rest_xml_node_get_attr rest_xml_node_find REST_XML_PARSER REST_IS_XML_PARSER REST_TYPE_XML_PARSER rest_xml_parser_get_type REST_XML_PARSER_CLASS REST_IS_XML_PARSER_CLASS REST_XML_PARSER_GET_CLASS REST_TYPE_XML_NODE rest_xml_node_get_type
rest-proxy-call RestProxyCall RestProxyCall REST_PROXY_CALL_ERROR RestProxyCallError rest_proxy_call_set_method rest_proxy_call_get_method rest_proxy_call_set_function rest_proxy_call_add_header rest_proxy_call_add_headers rest_proxy_call_add_headers_from_valist rest_proxy_call_lookup_header rest_proxy_call_remove_header rest_proxy_call_add_param rest_proxy_call_add_param_full rest_proxy_call_add_params rest_proxy_call_add_params_from_valist rest_proxy_call_lookup_param rest_proxy_call_remove_param rest_proxy_call_get_params rest_proxy_call_run RestProxyCallAsyncCallback rest_proxy_call_async rest_proxy_call_cancel rest_proxy_call_sync rest_proxy_call_lookup_response_header rest_proxy_call_get_response_headers rest_proxy_call_get_payload_length rest_proxy_call_get_payload rest_proxy_call_get_status_code rest_proxy_call_get_status_message RestProxyCallPrivate REST_PROXY_CALL REST_IS_PROXY_CALL REST_TYPE_PROXY_CALL rest_proxy_call_get_type REST_PROXY_CALL_CLASS REST_IS_PROXY_CALL_CLASS REST_PROXY_CALL_GET_CLASS rest_proxy_call_error_quark
oauth2-proxy OAuth2Proxy OAuth2Proxy oauth2_proxy_new oauth2_proxy_new_with_token oauth2_proxy_build_login_url_full oauth2_proxy_build_login_url oauth2_proxy_get_access_token oauth2_proxy_set_access_token oauth2_proxy_extract_access_token OAuth2ProxyClass OAuth2ProxyPrivate OAUTH2_PROXY OAUTH2_IS_PROXY OAUTH2_TYPE_PROXY oauth2_proxy_get_type OAUTH2_PROXY_CLASS OAUTH2_IS_PROXY_CLASS OAUTH2_PROXY_GET_CLASS
oauth2-proxy-call OAuth2ProxyCall OAuth2ProxyCall OAuth2ProxyCallClass OAUTH2_PROXY_CALL OAUTH2_IS_PROXY_CALL OAUTH2_TYPE_PROXY_CALL oauth2_proxy_call_get_type OAUTH2_PROXY_CALL_CLASS OAUTH2_IS_PROXY_CALL_CLASS OAUTH2_PROXY_CALL_GET_CLASS
rest-proxy RestProxy RestProxy RestProxyClass REST_PROXY_ERROR RestProxyError rest_proxy_new rest_proxy_bind rest_proxy_bind_valist rest_proxy_set_user_agent rest_proxy_get_user_agent rest_proxy_new_call rest_proxy_simple_run rest_proxy_simple_run_valist REST_PROXY REST_IS_PROXY REST_TYPE_PROXY rest_proxy_get_type REST_PROXY_CLASS REST_IS_PROXY_CLASS REST_PROXY_GET_CLASS rest_proxy_error_quark
oauth-proxy-call OAuthProxyCall OAuthProxyCall oauth_proxy_call_parse_token_reponse OAuthProxyCallClass OAUTH_PROXY_CALL OAUTH_IS_PROXY_CALL OAUTH_TYPE_PROXY_CALL oauth_proxy_call_get_type OAUTH_PROXY_CALL_CLASS OAUTH_IS_PROXY_CALL_CLASS OAUTH_PROXY_CALL_GET_CLASS
oauth-proxy OAuthProxy OAuthProxy OAuthSignatureMethod oauth_proxy_new oauth_proxy_new_echo_proxy oauth_proxy_new_with_token OAuthProxyAuthCallback oauth_proxy_auth_step oauth_proxy_auth_step_async oauth_proxy_request_token oauth_proxy_request_token_async oauth_proxy_is_oauth10a oauth_proxy_access_token oauth_proxy_access_token_async oauth_proxy_get_token oauth_proxy_set_token oauth_proxy_get_token_secret oauth_proxy_set_token_secret oauth_proxy_get_signature_host oauth_proxy_set_signature_host OAuthProxyPrivate OAuthProxyClass OAUTH_PROXY OAUTH_IS_PROXY OAUTH_TYPE_PROXY oauth_proxy_get_type OAUTH_PROXY_CLASS OAUTH_IS_PROXY_CLASS OAUTH_PROXY_GET_CLASS
rest-params RestParams RestParams RestParamsIter rest_params_new rest_params_free rest_params_add rest_params_get rest_params_remove rest_params_are_strings rest_params_as_string_hash_table rest_params_iter_init rest_params_iter_next
rest-param RestParam RestMemoryUse RestParam rest_param_new_string rest_param_new_full rest_param_new_with_owner rest_param_is_string rest_param_get_name rest_param_get_content_type rest_param_get_file_name rest_param_get_content rest_param_get_content_length rest_param_ref rest_param_unref
flickr-proxy-call FlickrProxyCall FlickrProxyCall FlickrProxyCallClass FLICKR_PROXY_CALL FLICKR_IS_PROXY_CALL FLICKR_TYPE_PROXY_CALL flickr_proxy_call_get_type FLICKR_PROXY_CALL_CLASS FLICKR_IS_PROXY_CALL_CLASS FLICKR_PROXY_CALL_GET_CLASS
flickr-proxy FlickrProxy FlickrProxy FLICKR_PROXY_ERROR flickr_proxy_new flickr_proxy_new_with_token flickr_proxy_get_api_key flickr_proxy_get_shared_secret flickr_proxy_get_token flickr_proxy_set_token flickr_proxy_sign flickr_proxy_build_login_url flickr_proxy_is_successful flickr_proxy_new_upload flickr_proxy_new_upload_for_file FlickrProxyClass FlickrProxyPrivate FLICKR_PROXY FLICKR_IS_PROXY FLICKR_TYPE_PROXY flickr_proxy_get_type FLICKR_PROXY_CLASS FLICKR_IS_PROXY_CLASS FLICKR_PROXY_GET_CLASS
lastfm-proxy-call LastfmProxyCall LastfmProxyCall LastfmProxyCallClass LASTFM_PROXY_CALL LASTFM_IS_PROXY_CALL LASTFM_TYPE_PROXY_CALL lastfm_proxy_call_get_type LASTFM_PROXY_CALL_CLASS LASTFM_IS_PROXY_CALL_CLASS LASTFM_PROXY_CALL_GET_CLASS
lastfm-proxy LastfmProxy LastfmProxy LASTFM_PROXY_ERROR lastfm_proxy_new lastfm_proxy_new_with_session lastfm_proxy_get_api_key lastfm_proxy_get_secret lastfm_proxy_get_session_key lastfm_proxy_set_session_key lastfm_proxy_sign lastfm_proxy_build_login_url lastfm_proxy_is_successful LastfmProxyClass LastfmProxyPrivate LASTFM_PROXY LASTFM_IS_PROXY LASTFM_TYPE_PROXY lastfm_proxy_get_type LASTFM_PROXY_CLASS LASTFM_IS_PROXY_CLASS LASTFM_PROXY_GET_CLASS
librest/rest-extras.pc.in0000664000175000017500000000047012014274314014023 0ustar bobbobprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ apiversion=@API_VERSION@ Name: rest Description: RESTful web api query library Version: @VERSION@ Libs: -L${libdir} -lrest-extras-${apiversion} Cflags: -I${includedir}/rest-${apiversion} Requires: glib-2.0 libsoup-2.4 libxml-2.0 librest/build/0000775000175000017500000000000012014274314011707 5ustar bobboblibrest/build/Makefile.am0000664000175000017500000000003612014274314013742 0ustar bobbobEXTRA_DIST = introspection.m4 librest/build/introspection.m40000664000175000017500000000661412014274314015060 0ustar bobbobdnl -*- mode: autoconf -*- dnl Copyright 2009 Johan Dahlin dnl dnl This file is free software; the author(s) gives unlimited dnl permission to copy and/or distribute it, with or without dnl modifications, as long as this notice is preserved. dnl # serial 1 m4_define([_GOBJECT_INTROSPECTION_CHECK_INTERNAL], [ AC_BEFORE([AC_PROG_LIBTOOL],[$0])dnl setup libtool first AC_BEFORE([AM_PROG_LIBTOOL],[$0])dnl setup libtool first AC_BEFORE([LT_INIT],[$0])dnl setup libtool first dnl enable/disable introspection m4_if([$2], [require], [dnl enable_introspection=yes ],[dnl AC_ARG_ENABLE(introspection, AS_HELP_STRING([--enable-introspection[=@<:@no/auto/yes@:>@]], [Enable introspection for this build]),, [enable_introspection=auto]) ])dnl AC_MSG_CHECKING([for gobject-introspection]) dnl presence/version checking AS_CASE([$enable_introspection], [no], [dnl found_introspection="no (disabled, use --enable-introspection to enable)" ],dnl [yes],[dnl PKG_CHECK_EXISTS([gobject-introspection-1.0],, AC_MSG_ERROR([gobject-introspection-1.0 is not installed])) PKG_CHECK_EXISTS([gobject-introspection-1.0 >= $1], found_introspection=yes, AC_MSG_ERROR([You need to have gobject-introspection >= $1 installed to build AC_PACKAGE_NAME])) ],dnl [auto],[dnl PKG_CHECK_EXISTS([gobject-introspection-1.0 >= $1], found_introspection=yes, found_introspection=no) ],dnl [dnl AC_MSG_ERROR([invalid argument passed to --enable-introspection, should be one of @<:@no/auto/yes@:>@]) ])dnl AC_MSG_RESULT([$found_introspection]) INTROSPECTION_SCANNER= INTROSPECTION_COMPILER= INTROSPECTION_GENERATE= INTROSPECTION_GIRDIR= INTROSPECTION_TYPELIBDIR= if test "x$found_introspection" = "xyes"; then INTROSPECTION_SCANNER=`$PKG_CONFIG --variable=g_ir_scanner gobject-introspection-1.0` INTROSPECTION_COMPILER=`$PKG_CONFIG --variable=g_ir_compiler gobject-introspection-1.0` INTROSPECTION_GENERATE=`$PKG_CONFIG --variable=g_ir_generate gobject-introspection-1.0` INTROSPECTION_GIRDIR=`$PKG_CONFIG --variable=girdir gobject-introspection-1.0` INTROSPECTION_TYPELIBDIR="$($PKG_CONFIG --variable=typelibdir gobject-introspection-1.0)" INTROSPECTION_CFLAGS=`$PKG_CONFIG --cflags gobject-introspection-1.0` INTROSPECTION_LIBS=`$PKG_CONFIG --libs gobject-introspection-1.0` INTROSPECTION_MAKEFILE=`$PKG_CONFIG --variable=datadir gobject-introspection-1.0`/gobject-introspection-1.0/Makefile.introspection fi AC_SUBST(INTROSPECTION_SCANNER) AC_SUBST(INTROSPECTION_COMPILER) AC_SUBST(INTROSPECTION_GENERATE) AC_SUBST(INTROSPECTION_GIRDIR) AC_SUBST(INTROSPECTION_TYPELIBDIR) AC_SUBST(INTROSPECTION_CFLAGS) AC_SUBST(INTROSPECTION_LIBS) AC_SUBST(INTROSPECTION_MAKEFILE) AM_CONDITIONAL(HAVE_INTROSPECTION, test "x$found_introspection" = "xyes") ]) dnl Usage: dnl GOBJECT_INTROSPECTION_CHECK([minimum-g-i-version]) AC_DEFUN([GOBJECT_INTROSPECTION_CHECK], [ _GOBJECT_INTROSPECTION_CHECK_INTERNAL([$1]) ]) dnl Usage: dnl GOBJECT_INTROSPECTION_REQUIRE([minimum-g-i-version]) AC_DEFUN([GOBJECT_INTROSPECTION_REQUIRE], [ _GOBJECT_INTROSPECTION_CHECK_INTERNAL([$1], [require]) ]) librest/tests/0000775000175000017500000000000012014274315011753 5ustar bobboblibrest/tests/threaded.c0000664000175000017500000000567012014274315013707 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2009 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include static volatile int errors = 0; static const gboolean verbose = FALSE; static void server_callback (SoupServer *server, SoupMessage *msg, const char *path, GHashTable *query, SoupClientContext *client, gpointer user_data) { if (g_str_equal (path, "/ping")) { soup_message_set_status (msg, SOUP_STATUS_OK); } else { soup_message_set_status (msg, SOUP_STATUS_NOT_IMPLEMENTED); } } static gpointer func (gpointer data) { RestProxy *proxy; RestProxyCall *call; const char *url = data; GError *error = NULL; proxy = rest_proxy_new (url, FALSE); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "ping"); if (!rest_proxy_call_sync (call, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); g_atomic_int_add (&errors, 1); goto done; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("Wrong response code, got %d\n", rest_proxy_call_get_status_code (call)); g_atomic_int_add (&errors, 1); goto done; } if (verbose) g_print ("Thread %p done\n", g_thread_self ()); done: g_object_unref (call); g_object_unref (proxy); return NULL; } int main (int argc, char **argv) { SoupSession *session; SoupServer *server; GThread *threads[10]; char *url; int i; g_type_init (); session = soup_session_sync_new (); server = soup_server_new (NULL); soup_server_add_handler (server, NULL, server_callback, NULL, NULL); g_thread_create ((GThreadFunc)soup_server_run, server, FALSE, NULL); url = g_strdup_printf ("http://127.0.0.1:%d/", soup_server_get_port (server)); for (i = 0; i < G_N_ELEMENTS (threads); i++) { threads[i] = g_thread_create (func, url, TRUE, NULL); if (verbose) g_print ("Starting thread %p\n", threads[i]); } for (i = 0; i < G_N_ELEMENTS (threads); i++) { g_thread_join (threads[i]); } soup_server_quit (server); g_free (url); return errors != 0; } librest/tests/oauth2.c0000664000175000017500000000342512014274315013325 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Jonathon Jongsma * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include void test_extract_token () { char *token; /* test a url without a fragment */ token = oauth2_proxy_extract_access_token ("http://example.com/"); g_assert (token == NULL); /* test a url with a fragment but without an access_token parameter */ token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#bar"); g_assert (token == NULL); /* test simple access_token */ token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#access_token=1234567890_12.34561abcdefg&bar"); g_assert (strcmp(token, "1234567890_12.34561abcdefg") == 0); /* test access_token with url encoding */ token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#access_token=1234567890%5F12%2E34561abcdefg&bar"); g_assert (strcmp(token, "1234567890_12.34561abcdefg") == 0); } int main (int argc, char **argv) { g_type_init (); test_extract_token (); return 0; } librest/tests/oauth-async.c0000664000175000017500000001027112014274315014353 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include static GMainLoop *loop; static void make_calls (OAuthProxy *oproxy) { RestProxy *proxy = REST_PROXY (oproxy); RestProxyCall *call; GError *error = NULL; /* Make some test calls */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "foo", "bar"); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "foo=bar"); g_object_unref (call); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "numbers", "1234567890"); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "numbers=1234567890"); g_object_unref (call); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "escape", "!£$%^&*()"); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "escape=%21%C2%A3%24%25%5E%26%2A%28%29"); g_object_unref (call); g_main_loop_quit (loop); } static void access_token_cb (OAuthProxy *proxy, const GError *error, GObject *weak_object, gpointer user_data) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (proxy); g_assert_no_error ((GError *)error); g_assert_cmpstr (priv->token, ==, "accesskey"); g_assert_cmpstr (priv->token_secret, ==, "accesssecret"); make_calls (proxy); } static void request_token_cb (OAuthProxy *proxy, const GError *error, GObject *weak_object, gpointer user_data) { OAuthProxyPrivate *priv = PROXY_GET_PRIVATE (proxy); GError *err = NULL; g_assert_no_error ((GError *)error); g_assert_cmpstr (priv->token, ==, "requestkey"); g_assert_cmpstr (priv->token_secret, ==, "requestsecret"); /* Second stage authentication, this gets an access token */ oauth_proxy_access_token_async (proxy, "access_token.php", NULL, access_token_cb, NULL, NULL, &err); g_assert_no_error (err); } static gboolean on_timeout (gpointer data) { g_message ("timed out!"); exit (1); return FALSE; } int main (int argc, char **argv) { RestProxy *proxy; OAuthProxy *oproxy; GError *error = NULL; g_type_init (); /* Install a timeout so that we don't hang or infinite loop */ g_timeout_add_seconds (10, on_timeout, NULL); loop = g_main_loop_new (NULL, TRUE); /* Create the proxy */ proxy = oauth_proxy_new ("key", "secret", "http://term.ie/oauth/example/", FALSE); oproxy = OAUTH_PROXY (proxy); g_assert (oproxy); /* First stage authentication, this gets a request token */ oauth_proxy_request_token_async (oproxy, "request_token.php", NULL, request_token_cb, NULL, NULL, &error); g_assert_no_error (error); g_main_loop_run (loop); g_main_loop_unref (loop); g_object_unref (proxy); return 0; } librest/tests/Makefile.am0000664000175000017500000000123412014274315014007 0ustar bobbobTESTS = proxy proxy-continuous threaded oauth oauth-async oauth2 flickr lastfm xml custom-serialize # TODO: fix this test case XFAIL_TESTS = xml AM_CPPFLAGS = $(SOUP_CFLAGS) -I$(top_srcdir) $(GCOV_CFLAGS) AM_LDFLAGS = $(SOUP_LIBS) $(GCOV_LDFLAGS) \ ../rest/librest-@API_VERSION@.la ../rest-extras/librest-extras-@API_VERSION@.la check_PROGRAMS = $(TESTS) proxy_SOURCES = proxy.c proxy_continuous_SOURCES = proxy-continuous.c threaded_SOURCES = threaded.c oauth_SOURCES = oauth.c oauth_async_SOURCES = oauth-async.c oauth2_SOURCES = oauth2.c flickr_SOURCES = flickr.c lastfm_SOURCES = lastfm.c xml_SOURCES = xml.c custom_serialize_SOURCES = custom-serialize.c librest/tests/proxy-continuous.c0000664000175000017500000001076012014274315015510 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include static int errors = 0; static GMainLoop *loop = NULL; #define NUM_CHUNKS 20 static int server_count = 0; static gint client_count = 0; static SoupServer *server; static gboolean send_chunks (gpointer user_data) { SoupMessage *msg = SOUP_MESSAGE (user_data); char *s; SoupBuffer *buf; s = g_strdup_printf ("%d %d %d %d\n", server_count, server_count, server_count, server_count); buf = soup_buffer_new (SOUP_MEMORY_TAKE, s, strlen (s)); soup_message_body_append_buffer (msg->response_body, buf); soup_server_unpause_message (server, msg); if (++server_count == NUM_CHUNKS) { soup_message_body_complete (msg->response_body); return FALSE; } else { return TRUE; } } static void server_callback (SoupServer *server, SoupMessage *msg, const char *path, GHashTable *query, SoupClientContext *client, gpointer user_data) { if (g_str_equal (path, "/stream")) { soup_message_set_status (msg, SOUP_STATUS_OK); soup_message_headers_set_encoding (msg->response_headers, SOUP_ENCODING_CHUNKED); soup_server_pause_message (server, msg); server_count = 1; g_idle_add (send_chunks, msg); } } static void _call_continuous_cb (RestProxyCall *call, const gchar *buf, gsize len, const GError *error, GObject *weak_object, gpointer userdata) { gint a = 0, b = 0, c = 0, d = 0; if (error) { g_printerr ("Error: %s\n", error->message); errors++; goto out; } if (!REST_IS_PROXY (weak_object)) { g_printerr ("weak object not as expected\n"); errors++; goto out; } if (buf == NULL && len == 0) { if (client_count != NUM_CHUNKS) { g_printerr ("stream ended prematurely\n"); errors++; } goto out; } if (sscanf (buf, "%d %d %d %d\n", &a, &b, &c, &d) != 4) { g_printerr ("stream data not formatted as expected\n"); errors++; goto out; } if (a != client_count || b != client_count || c != client_count || d != client_count) { g_printerr ("stream data not as expected (got %d %d %d %d, expected %d)\n", a, b, c, d, client_count); errors++; goto out; } client_count++; return; out: g_main_loop_quit (loop); return; } static void stream_test (RestProxy *proxy) { RestProxyCall *call; GError *error; client_count = 1; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "stream"); if (!rest_proxy_call_continuous (call, _call_continuous_cb, (GObject *)proxy, NULL, &error)) { g_printerr ("Making stream failed: %s", error->message); g_error_free (error); errors++; return; } g_object_unref (call); } int main (int argc, char **argv) { SoupSession *session; char *url; RestProxy *proxy; g_type_init (); loop = g_main_loop_new (NULL, FALSE); session = soup_session_async_new (); server = soup_server_new (NULL); soup_server_add_handler (server, NULL, server_callback, NULL, NULL); soup_server_run_async (server); url = g_strdup_printf ("http://127.0.0.1:%d/", soup_server_get_port (server)); proxy = rest_proxy_new (url, FALSE); g_free (url); stream_test (proxy); g_main_loop_run (loop); return errors != 0; } librest/tests/proxy.c0000664000175000017500000002017412014274315013304 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2009 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* * TODO: * - port to gtest * - decide if status 3xx is success or failure * - test query params * - test request headers * - test response headers */ #include #include #include #include #include static int errors = 0; static void server_callback (SoupServer *server, SoupMessage *msg, const char *path, GHashTable *query, SoupClientContext *client, gpointer user_data) { if (g_str_equal (path, "/ping")) { soup_message_set_status (msg, SOUP_STATUS_OK); } else if (g_str_equal (path, "/echo")) { const char *value; value = g_hash_table_lookup (query, "value"); soup_message_set_response (msg, "text/plain", SOUP_MEMORY_COPY, value, strlen (value)); soup_message_set_status (msg, SOUP_STATUS_OK); } else if (g_str_equal (path, "/reverse")) { char *value; value = g_strdup (g_hash_table_lookup (query, "value")); g_strreverse (value); soup_message_set_response (msg, "text/plain", SOUP_MEMORY_TAKE, value, strlen (value)); soup_message_set_status (msg, SOUP_STATUS_OK); } else if (g_str_equal (path, "/status")) { const char *value; int status; value = g_hash_table_lookup (query, "status"); if (value) { status = atoi (value); soup_message_set_status (msg, status ?: SOUP_STATUS_INTERNAL_SERVER_ERROR); } else { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); } } else if (g_str_equal (path, "/useragent/none")) { if (soup_message_headers_get (msg->request_headers, "User-Agent") == NULL) { soup_message_set_status (msg, SOUP_STATUS_OK); } else { soup_message_set_status (msg, SOUP_STATUS_EXPECTATION_FAILED); } } else if (g_str_equal (path, "/useragent/testsuite")) { const char *value; value = soup_message_headers_get (msg->request_headers, "User-Agent"); if (g_strcmp0 (value, "TestSuite-1.0") == 0) { soup_message_set_status (msg, SOUP_STATUS_OK); } else { soup_message_set_status (msg, SOUP_STATUS_EXPECTATION_FAILED); } } } static void ping_test (RestProxy *proxy) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "ping"); if (!rest_proxy_call_run (call, NULL, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("wrong response code\n"); errors++; return; } if (rest_proxy_call_get_payload_length (call) != 0) { g_printerr ("wrong length returned\n"); errors++; return; } g_object_unref (call); } static void echo_test (RestProxy *proxy) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo"); rest_proxy_call_add_param (call, "value", "echome"); if (!rest_proxy_call_run (call, NULL, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("wrong response code\n"); errors++; return; } if (rest_proxy_call_get_payload_length (call) != 6) { g_printerr ("wrong length returned\n"); errors++; return; } if (g_strcmp0 ("echome", rest_proxy_call_get_payload (call)) != 0) { g_printerr ("wrong string returned\n"); errors++; return; } } static void reverse_test (RestProxy *proxy) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "reverse"); rest_proxy_call_add_param (call, "value", "reverseme"); if (!rest_proxy_call_run (call, NULL, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("wrong response code\n"); errors++; return; } if (rest_proxy_call_get_payload_length (call) != 9) { g_printerr ("wrong length returned\n"); errors++; return; } if (g_strcmp0 ("emesrever", rest_proxy_call_get_payload (call)) != 0) { g_printerr ("wrong string returned\n"); errors++; return; } } static void status_ok_test (RestProxy *proxy, int status) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "status"); rest_proxy_call_add_param (call, "status", g_strdup_printf ("%d", status)); if (!rest_proxy_call_run (call, NULL, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != status) { g_printerr ("wrong response code, got %d\n", rest_proxy_call_get_status_code (call)); errors++; return; } g_object_unref (call); } static void status_error_test (RestProxy *proxy, int status) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "status"); rest_proxy_call_add_param (call, "status", g_strdup_printf ("%d", status)); if (rest_proxy_call_run (call, NULL, &error)) { g_printerr ("Call succeeded should have failed"); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != status) { g_printerr ("wrong response code, got %d\n", rest_proxy_call_get_status_code (call)); errors++; return; } g_object_unref (call); } static void test_status_ok (RestProxy *proxy, const char *function) { RestProxyCall *call; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, function); if (!rest_proxy_call_run (call, NULL, &error)) { g_printerr ("%s call failed: %s\n", function, error->message); g_error_free (error); errors++; g_object_unref (call); return; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("wrong response code, got %d\n", rest_proxy_call_get_status_code (call)); errors++; return; } g_object_unref (call); } int main (int argc, char **argv) { SoupSession *session; SoupServer *server; char *url; RestProxy *proxy; g_type_init (); session = soup_session_async_new (); server = soup_server_new (NULL); soup_server_add_handler (server, NULL, server_callback, NULL, NULL); soup_server_run_async (server); url = g_strdup_printf ("http://127.0.0.1:%d/", soup_server_get_port (server)); proxy = rest_proxy_new (url, FALSE); g_free (url); ping_test (proxy); echo_test (proxy); reverse_test (proxy); status_ok_test (proxy, SOUP_STATUS_OK); status_ok_test (proxy, SOUP_STATUS_NO_CONTENT); /* status_ok_test (proxy, SOUP_STATUS_MULTIPLE_CHOICES); */ status_error_test (proxy, SOUP_STATUS_BAD_REQUEST); status_error_test (proxy, SOUP_STATUS_NOT_IMPLEMENTED); test_status_ok (proxy, "useragent/none"); rest_proxy_set_user_agent (proxy, "TestSuite-1.0"); test_status_ok (proxy, "useragent/testsuite"); return errors != 0; } librest/tests/flickr.c0000664000175000017500000000663012014274315013376 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #define API_KEY "cf4e02fc57240a9b07346ad26e291080" #define SHARED_SECRET "cdfa2329cb206e50" #define ROSS_ID "35468147630@N01" int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; GError *error = NULL; RestXmlParser *parser; RestXmlNode *root, *node; g_type_init (); /* Create the proxy */ proxy = flickr_proxy_new (API_KEY, SHARED_SECRET); g_assert_cmpstr (flickr_proxy_get_api_key (FLICKR_PROXY (proxy)), ==, API_KEY); g_assert_cmpstr (flickr_proxy_get_shared_secret (FLICKR_PROXY (proxy)), ==, SHARED_SECRET); /* * Sadly can't unit test authentication. */ /* * Test a call which just requires an API key but no signature. */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.people.getInfo"); rest_proxy_call_add_param (call, "user_id", ROSS_ID); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); g_assert (root); g_assert_cmpstr (root->name, ==, "rsp"); g_assert_cmpstr (rest_xml_node_get_attr (root, "stat"), ==, "ok"); node = rest_xml_node_find (root, "person"); g_assert (node); g_assert_cmpstr (rest_xml_node_get_attr (node, "nsid"), ==, ROSS_ID); node = rest_xml_node_find (node, "username"); g_assert (node); g_assert_cmpstr (node->content, ==, "Ross Burton"); rest_xml_node_unref (root); g_object_unref (call); /* * Test a call which requires a signature. */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.auth.getFrob"); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); g_assert (root); g_assert_cmpstr (root->name, ==, "rsp"); g_assert_cmpstr (rest_xml_node_get_attr (root, "stat"), ==, "ok"); node = rest_xml_node_find (root, "frob"); g_assert (node); g_assert (node->content); g_assert_cmpstr (node->content, !=, ""); g_object_unref (proxy); return 0; } librest/tests/custom-serialize.c0000664000175000017500000001101012014274315015407 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2009 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include static volatile int errors = 0; static const gboolean verbose = FALSE; #define REST_TYPE_CUSTOM_PROXY_CALL custom_proxy_call_get_type() #define REST_CUSTOM_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), REST_TYPE_CUSTOM_PROXY_CALL, CustomProxyCall)) #define REST_CUSTOM_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), REST_TYPE_CUSTOM_PROXY_CALL, CustomProxyCallClass)) #define REST_IS_CUSTOM_PROXY_CALL(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), REST_TYPE_CUSTOM_PROXY_CALL)) #define REST_IS_CUSTOM_PROXY_CALL_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), REST_TYPE_CUSTOM_PROXY_CALL)) #define REST_CUSTOM_PROXY_CALL_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), REST_TYPE_CUSTOM_PROXY_CALL, CustomProxyCallClass)) typedef struct { RestProxyCall parent; } CustomProxyCall; typedef struct { RestProxyCallClass parent_class; } CustomProxyCallClass; GType custom_proxy_call_get_type (void); G_DEFINE_TYPE (CustomProxyCall, custom_proxy_call, REST_TYPE_PROXY_CALL) static gboolean custom_proxy_call_serialize (RestProxyCall *self, gchar **content_type, gchar **content, gsize *content_len, GError **error) { g_return_val_if_fail (REST_IS_CUSTOM_PROXY_CALL (self), FALSE); *content_type = g_strdup ("application/json"); *content = g_strdup ("{}"); *content_len = strlen (*content); return TRUE; } static void custom_proxy_call_class_init (CustomProxyCallClass *klass) { RestProxyCallClass *parent_klass = (RestProxyCallClass*) klass; parent_klass->serialize_params = custom_proxy_call_serialize; } static void custom_proxy_call_init (CustomProxyCall *self) { } static void server_callback (SoupServer *server, SoupMessage *msg, const char *path, GHashTable *query, SoupClientContext *client, gpointer user_data) { if (g_str_equal (path, "/ping")) { const char *content_type = NULL; SoupMessageHeaders *headers = msg->request_headers; SoupMessageBody *body = msg->request_body; content_type = soup_message_headers_get_content_type (headers, NULL); g_assert_cmpstr (content_type, ==, "application/json"); g_assert_cmpstr (body->data, ==, "{}"); soup_message_set_status (msg, SOUP_STATUS_OK); } else { soup_message_set_status (msg, SOUP_STATUS_NOT_IMPLEMENTED); } } static gpointer func (gpointer data) { return NULL; } int main (int argc, char **argv) { SoupSession *session; SoupServer *server; RestProxy *proxy; RestProxyCall *call; char *url; int i; GError *error; g_type_init (); session = soup_session_sync_new (); server = soup_server_new (NULL); soup_server_add_handler (server, NULL, server_callback, NULL, NULL); g_thread_create ((GThreadFunc)soup_server_run, server, FALSE, NULL); url = g_strdup_printf ("http://127.0.0.1:%d/", soup_server_get_port (server)); proxy = rest_proxy_new (url, FALSE); call = g_object_new (REST_TYPE_CUSTOM_PROXY_CALL, "proxy", proxy, NULL); rest_proxy_call_set_function (call, "ping"); if (!rest_proxy_call_sync (call, &error)) { g_printerr ("Call failed: %s\n", error->message); g_error_free (error); g_atomic_int_add (&errors, 1); goto done; } if (rest_proxy_call_get_status_code (call) != SOUP_STATUS_OK) { g_printerr ("Wrong response code, got %d\n", rest_proxy_call_get_status_code (call)); g_atomic_int_add (&errors, 1); goto done; } done: g_object_unref (call); g_object_unref (proxy); soup_server_quit (server); g_free (url); return errors != 0; } librest/tests/lastfm.c0000664000175000017500000000515312014274315013411 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #define API_KEY "aa581f6505fd3ea79073ddcc2215cbc7" #define SECRET "7db227a36b3154e3a3306a23754de1d7" #define USERNAME "rossburton" int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; GError *error = NULL; RestXmlParser *parser; RestXmlNode *root, *u_node, *node; g_type_init (); /* Create the proxy */ proxy = lastfm_proxy_new (API_KEY, SECRET); g_assert_cmpstr (lastfm_proxy_get_api_key (LASTFM_PROXY (proxy)), ==, API_KEY); g_assert_cmpstr (lastfm_proxy_get_secret (LASTFM_PROXY (proxy)), ==, SECRET); /* * Sadly can't unit test authentication. Need an interactive mode. */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "user.getInfo"); rest_proxy_call_add_param (call, "user", USERNAME); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot make call: %s", error->message); parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); g_assert (root); g_assert_cmpstr (root->name, ==, "lfm"); g_assert_cmpstr (rest_xml_node_get_attr (root, "status"), ==, "ok"); u_node = rest_xml_node_find (root, "user"); g_assert (u_node); node = rest_xml_node_find (u_node, "id"); g_assert (node); g_assert_cmpstr (node->content, ==, "17038"); node = rest_xml_node_find (u_node, "name"); g_assert (node); g_assert_cmpstr (node->content, ==, USERNAME); rest_xml_node_unref (root); g_object_unref (call); g_object_unref (proxy); return 0; } librest/tests/xml.c0000664000175000017500000000432312014274315012721 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2011, Intel Corporation. * * Author: Tomas Frydrych * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #define TEST_XML "Cont0" int main (int argc, char **argv) { GError *error = NULL; RestXmlParser *parser; RestXmlNode *root, *node; char *xml; g_type_init (); parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, TEST_XML, strlen (TEST_XML)); g_assert (root); xml = rest_xml_node_print (root); g_assert (xml); if (strcmp (TEST_XML, xml)) { g_error ("Generated output for parsed XML does not match:\n" "in: %s\n" "out: %s\n", TEST_XML, xml); } rest_xml_node_unref (root); root = rest_xml_node_add_child (NULL, "node0"); rest_xml_node_add_attr (root, "a00", "v00"); rest_xml_node_add_attr (root, "a01", "v01"); node = rest_xml_node_add_child (root, "node1"); rest_xml_node_add_attr (node, "a10", "v10"); node = rest_xml_node_add_child (root, "node1"); rest_xml_node_add_attr (node, "a10", "v10"); rest_xml_node_set_content (root, "Cont0"); xml = rest_xml_node_print (root); g_assert (xml); if (strcmp (TEST_XML, xml)) { g_error ("Generated output for constructed XML does not match:\n" "in: %s\n" "out: %s\n", TEST_XML, xml); } rest_xml_node_unref (root); return 0; } librest/tests/oauth.c0000664000175000017500000000605212014274315013242 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include int main (int argc, char **argv) { RestProxy *proxy; OAuthProxy *oproxy; OAuthProxyPrivate *priv; RestProxyCall *call; GError *error = NULL; g_type_init (); /* Create the proxy */ proxy = oauth_proxy_new ("key", "secret", "http://term.ie/oauth/example/", FALSE); oproxy = OAUTH_PROXY (proxy); g_assert (oproxy); priv = PROXY_GET_PRIVATE (oproxy); /* First stage authentication, this gets a request token */ oauth_proxy_request_token (oproxy, "request_token.php", NULL, &error); g_assert_no_error (error); g_assert_cmpstr (priv->token, ==, "requestkey"); g_assert_cmpstr (priv->token_secret, ==, "requestsecret"); /* Second stage authentication, this gets an access token */ oauth_proxy_access_token (OAUTH_PROXY (proxy), "access_token.php", NULL, &error); g_assert_no_error (error); g_assert_cmpstr (priv->token, ==, "accesskey"); g_assert_cmpstr (priv->token_secret, ==, "accesssecret"); /* Make some test calls */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "foo", "bar"); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "foo=bar"); g_object_unref (call); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "numbers", "1234567890"); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "numbers=1234567890"); g_object_unref (call); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "echo_api.php"); rest_proxy_call_add_param (call, "escape", "!+£$%^&*()"); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot make call: %s", error->message); g_assert_cmpstr (rest_proxy_call_get_payload (call), ==, "escape=%21%2B%C2%A3%24%25%5E%26%2A%28%29"); g_object_unref (call); g_object_unref (proxy); return 0; } librest/INSTALL0000664000175000017500000002245012014274314011644 0ustar bobbobInstallation Instructions ************************* Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package. 4. Type `make install' to install the programs and any data files and documentation. 5. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 6. Often, you can also type `make uninstall' to remove the installed files again. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX'. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Optional Features ================= Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of the options to `configure', and exit. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. librest/configure.ac0000664000175000017500000001004712014274314013100 0ustar bobbobm4_define([api_major], [0]) m4_define([api_minor], [7]) m4_define([api_micro], [90]) m4_define([rest_version], [api_major.api_minor.api_micro]) AC_PREREQ([2.63]) AC_INIT([rest], [rest_version], [], [rest], [http://git.gnome.org/browse/librest/]) AC_CONFIG_SRCDIR([rest/rest-proxy.h]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_AUX_DIR([build]) AC_CONFIG_MACRO_DIR([build]) AM_INIT_AUTOMAKE([1.11 foreign -Wno-portability no-define]) AM_SILENT_RULES([yes]) API_MAJOR=api_major API_MINOR=api_minor AC_SUBST([API_VERSION],[$API_MAJOR.$API_MINOR]) AC_SUBST([API_VERSION_AM],[$API_MAJOR\_$API_MINOR]) AC_DEFINE_UNQUOTED(API_VERSION, [$API_VERSION], [API version]) AC_CANONICAL_HOST AC_PROG_CC AC_PROG_CC_STDC AC_PROG_INSTALL AC_ISC_POSIX AC_HEADER_STDC AM_PROG_CC_C_O # require libtool >= 2.2 LT_PREREQ([2.2.6]) LT_INIT([disable-static]) PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.24) PKG_CHECK_MODULES(SOUP, libsoup-2.4) PKG_CHECK_MODULES(XML, libxml-2.0) PKG_CHECK_MODULES(GTHREAD, gthread-2.0) AC_MSG_CHECKING([whether to use the GNOME environment]) AC_ARG_WITH([gnome],[AS_HELP_STRING([--without-gnome], [disable support for GNOME environment])], [], [with_gnome=yes]) AS_IF( [test "$with_gnome" = yes], [ AC_MSG_RESULT([yes]) AC_DEFINE([WITH_GNOME], 1, [Use GNOME]) PKG_CHECK_MODULES(SOUP_GNOME, libsoup-gnome-2.4 >= 2.25.1) ], AC_MSG_RESULT([no]) ) # gtkdocize greps for ^GTK_DOC_CHECK and parses it, so you need to have # it on it's own line. m4_ifdef([GTK_DOC_CHECK], [ GTK_DOC_CHECK([1.13], [--flavour no-tmpl]) ]) GOBJECT_INTROSPECTION_CHECK([0.6.7]) AC_PATH_PROG([GLIB_MKENUMS],[glib-mkenums]) localedir=${datadir}/locale AC_SUBST(localedir) dnl === Coverage report ======================================================= AC_PATH_PROG([GCOV], [lcov], [enable_gcov=no]) AC_MSG_CHECKING([whether to build with gcov testing]) AC_ARG_ENABLE([gcov], [AS_HELP_STRING([--enable-gcov], [Whether to enable coverage testing (requires gcc and lcov)])], [], [enable_gcov=no]) AS_IF([test "x$enable_gcov" = "xyes" && test "x$GCC" = "xyes"], [ AS_IF([test "x$enable_gtk_doc" = "xyes"], [AC_MSG_WARN([gtk-doc is enabled, this may go horribly wrong])], [AC_MSG_RESULT([yes])] ) GCOV_CFLAGS="-g -O0 -fprofile-arcs -ftest-coverage" GCOV_LDFLAGS="-lgcov" ], [AC_MSG_RESULT([no])] ) AM_CONDITIONAL([GCOV_ENABLED], [test "x$enable_gcov" = "xyes"]) AC_SUBST([GCOV_CFLAGS]) AC_SUBST([GCOV_LDFLAGS]) dnl Stolen from glib-networking - those guys rock AC_MSG_CHECKING([location of system Certificate Authority list]) AC_ARG_WITH(ca-certificates, [AC_HELP_STRING([--with-ca-certificates=@<:@path@:>@], [path to system Certificate Authority list])]) if test "$with_ca_certificates" = "no"; then AC_MSG_RESULT([disabled]) else if test -z "$with_ca_certificates"; then for f in /etc/pki/tls/certs/ca-bundle.crt \ /etc/ssl/certs/ca-certificates.crt; do if test -f "$f"; then with_ca_certificates="$f" fi done if test -z "$with_ca_certificates"; then AC_MSG_ERROR([could not find. Use --with-ca-certificates=path to set, or --without-ca-certificates to disable]) fi fi AC_MSG_RESULT($with_ca_certificates) AC_DEFINE_UNQUOTED(REST_SYSTEM_CA_FILE, ["$with_ca_certificates"], [The system TLS CA list]) fi AC_OUTPUT([ Makefile rest/Makefile rest-extras/Makefile examples/Makefile docs/Makefile docs/reference/Makefile docs/reference/rest/Makefile tests/Makefile rest.pc rest-extras.pc ]) echo "" echo " LibRest $VERSION" echo " ================" echo "" echo " prefix: ${prefix}" echo "" echo " Documentation: ${enable_gtk_doc}" echo " Introspection data: ${enable_introspection}" echo "" librest/examples/0000775000175000017500000000000012014274314012426 5ustar bobboblibrest/examples/get-flickr-favorites.c0000664000175000017500000001021612014274314016621 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008,2009 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include /* * Parse the payload and either return a RestXmlNode, or error. As a side-effect * the call is unreffed. */ static RestXmlNode * get_xml (RestProxyCall *call) { RestXmlParser *parser; RestXmlNode *root; GError *error = NULL; parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); if (!flickr_proxy_is_successful (root, &error)) g_error ("%s", error->message); g_object_unref (call); g_object_unref (parser); return root; } static void print_user_name (RestProxy *proxy) { RestProxyCall *call; RestXmlNode *root, *node; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.auth.checkToken"); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot check token"); root = get_xml (call); node = rest_xml_node_find (root, "user"); g_print ("Logged in as %s\n", rest_xml_node_get_attr (node, "fullname") ?: rest_xml_node_get_attr (node, "username")); rest_xml_node_unref (root); } static void print_favourites (RestProxy *proxy) { RestProxyCall *call; RestXmlNode *root, *node; call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.favorites.getList"); rest_proxy_call_add_param (call, "extras", "owner_name"); rest_proxy_call_add_param (call, "per_page", "10"); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot get favourites"); root = get_xml (call); for (node = rest_xml_node_find (root, "photo"); node; node = node->next) { g_print ("%s by %s\n", rest_xml_node_get_attr (node, "title"), rest_xml_node_get_attr (node, "ownername")); } rest_xml_node_unref (root); } int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; RestXmlNode *root; char *frob, *url; const char *token; g_type_init (); proxy = flickr_proxy_new ("cf4e02fc57240a9b07346ad26e291080", "cdfa2329cb206e50"); if (argc > 1) { flickr_proxy_set_token (FLICKR_PROXY (proxy), argv[1]); } else { call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.auth.getFrob"); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot get frob"); root = get_xml (call); frob = g_strdup (rest_xml_node_find (root, "frob")->content); rest_xml_node_unref (root); url = flickr_proxy_build_login_url (FLICKR_PROXY (proxy), frob, "read"); g_print ("Go to %s to authorise me and then press any key.\n", url); getchar (); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "flickr.auth.getToken"); rest_proxy_call_add_param (call, "frob", frob); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot get token"); root = get_xml (call); token = rest_xml_node_find (root, "token")->content; g_print ("Got token %s\n", token); flickr_proxy_set_token (FLICKR_PROXY (proxy), token); rest_xml_node_unref (root); } print_user_name (proxy); print_favourites (proxy); g_object_unref (proxy); return 0; } librest/examples/dump-xml.c0000664000175000017500000000555212014274314014344 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include /* These debugging functions *leak* */ static gchar * _generate_attrs_output (GHashTable *attrs) { char *res; char *res_old = NULL; GList *keys, *values, *l, *ll; res = g_strdup ("{ "); keys = g_hash_table_get_keys (attrs); values = g_hash_table_get_values (attrs); for (l = keys, ll = values; l; l = l->next, ll = ll->next) { res_old = res; res = g_strconcat (res, l->data, ":", ll->data, " ", NULL); g_free (res_old); } g_list_free (keys); g_list_free (values); res_old = res; res = g_strconcat (res, "}", NULL); g_free (res_old); return res; } static void _rest_xml_node_output (RestXmlNode *node, gint depth) { RestXmlNode *child; GList *values; GList *l; char *attrs_output = NULL; do { attrs_output = _generate_attrs_output (node->attrs); g_print ("%*s[%s, %s, %s]\n", depth, "", node->name, node->content ? node->content : "NULL", attrs_output); g_free (attrs_output); values = g_hash_table_get_values (node->children); for (l = values; l; l = l->next) { child = (RestXmlNode *)l->data; g_print ("%*s%s - >\n", depth, "", child->name); _rest_xml_node_output (child, depth + 4); } g_list_free (values); } while ((node = node->next) != NULL); } int main (int argc, char **argv) { RestXmlParser *parser; RestXmlNode *node; GError *error = NULL; char *data = NULL; gsize length; if (argc != 2) { g_printerr ("$ dump-xml \n"); return 1; } g_type_init (); if (!g_file_get_contents (argv[1], &data, &length, &error)) { g_printerr ("%s\n", error->message); g_error_free (error); return 1; } parser = rest_xml_parser_new (); node = rest_xml_parser_parse_from_data (parser, data, length); if (node) { _rest_xml_node_output (node, 0); rest_xml_node_unref (node); } else { g_print ("Cannot parse document\n"); } g_object_unref (parser); return 0; } librest/examples/lastfm-shout.c0000664000175000017500000001061612014274314015224 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2010 Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include /* * Parse the payload and either return a RestXmlNode, or error. As a side-effect * the call is unreffed. */ static RestXmlNode * get_xml (RestProxyCall *call) { RestXmlParser *parser; RestXmlNode *root; GError *error = NULL; parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); if (!lastfm_proxy_is_successful (root, &error)) g_error ("%s", error->message); g_object_unref (call); g_object_unref (parser); return root; } static void shout (RestProxy *proxy, const char *username, const char *message) { RestProxyCall *call; RestXmlNode *root, *node; GError *error = NULL; call = rest_proxy_new_call (proxy); rest_proxy_call_set_method (call, "POST"); rest_proxy_call_set_function (call, "user.shout"); rest_proxy_call_add_param (call, "user", username); rest_proxy_call_add_param (call, "message", message); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot shout: %s", error->message); rest_xml_node_unref (get_xml (call)); } int main (int argc, char **argv) { GError *error = NULL; GOptionContext *context; RestProxy *proxy; RestProxyCall *call; RestXmlNode *root; char *token, *url, *userid = NULL, *session = NULL;; GOptionEntry entries[] = { { "session", 's', 0, G_OPTION_ARG_STRING, &session, "Session key (optional)", "KEY" }, { "user", 'u', 0, G_OPTION_ARG_STRING, &userid, "User to send a message to", "USERNAME" }, { NULL } }; g_type_init (); context = g_option_context_new ("- send a shout to a Last.fm user"); 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); return 1; } if (userid == NULL) { g_print ("Need a user ID to send a shout out to\n\n"); g_print ("%s", g_option_context_get_help (context, TRUE, NULL)); return 1; } proxy = lastfm_proxy_new ("aa581f6505fd3ea79073ddcc2215cbc7", "7db227a36b3154e3a3306a23754de1d7"); if (session) { lastfm_proxy_set_session_key (LASTFM_PROXY (proxy), argv[1]); } else { call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "auth.getToken"); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot get token"); root = get_xml (call); token = g_strdup (rest_xml_node_find (root, "token")->content); g_debug ("got token %s", token); rest_xml_node_unref (root); url = lastfm_proxy_build_login_url (LASTFM_PROXY (proxy), token); g_print ("Go to %s to authorise me and then press any key.\n", url); getchar (); call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "auth.getSession"); rest_proxy_call_add_param (call, "token", token); if (!rest_proxy_call_sync (call, NULL)) g_error ("Cannot get session"); root = get_xml (call); session = rest_xml_node_find (root, "key")->content; g_print ("Got session key %s\n", session); g_print ("Got username %s\n", rest_xml_node_find (root, "name")->content); lastfm_proxy_set_session_key (LASTFM_PROXY (proxy), session); rest_xml_node_unref (root); } shout (proxy, userid, "Hello from librest!"); g_object_unref (proxy); return 0; } librest/examples/Makefile.am0000664000175000017500000000124312014274314014462 0ustar bobbobnoinst_PROGRAMS = test-raw test-xml dump-xml get-fireeagle-location post-twitter get-flickr-favorites lastfm-shout continuous-twitter AM_CFLAGS = $(GLIB_CFLAGS) $(GTHREAD_CFLAGS) $(SOUP_CFLAGS) -I$(top_srcdir) AM_LDFLAGS = $(GLIB_LIBS) $(GTHREAD_LIBS) $(SOUP_LIBS) ../rest/librest-@API_VERSION@.la ../rest-extras/librest-extras-@API_VERSION@.la test_raw_SOURCES = test-raw.c test_xml_SOURCES = test-xml.c get_fireeagle_location_SOURCES = get-fireeagle-location.c dump_xml_SOURCES = dump-xml.c post_twitter_SOURCES = post-twitter.c get_flickr_favorites_SOURCES = get-flickr-favorites.c lastfm_shout_SOURCES = lastfm-shout.c continuous_twitter_SOURCES = continuous-twitter.c librest/examples/test-xml.c0000664000175000017500000001046712014274314014357 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include /* These debugging functions *leak* */ static gchar * _generate_attrs_output (GHashTable *attrs) { gchar *res; gchar *res_old = NULL; GList *keys, *values, *l, *ll; res = g_strdup ("{ "); keys = g_hash_table_get_keys (attrs); values = g_hash_table_get_values (attrs); for (l = keys, ll = values; l; l = l->next, ll = ll->next) { res_old = res; res = g_strconcat (res, l->data, ":", ll->data, " ", NULL); g_free (res_old); } g_list_free (keys); g_list_free (values); res_old = res; res = g_strconcat (res, "}", NULL); g_free (res_old); return res; } static void _rest_xml_node_output (RestXmlNode *node, gint depth) { RestXmlNode *child; GList *values; GList *l; gchar *attrs_output = NULL; do { attrs_output = _generate_attrs_output (node->attrs); g_print ("%*s[%s, %s, %s]\n", depth, "", node->name, node->content, attrs_output); g_free (attrs_output); values = g_hash_table_get_values (node->children); for (l = values; l; l = l->next) { child = (RestXmlNode *)l->data; g_print ("%*s%s - >\n", depth, "", child->name); _rest_xml_node_output (child, depth + 4); } g_list_free (values); } while ((node = node->next) != NULL); } static void proxy_call_raw_async_cb (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer userdata) { RestXmlParser *parser; RestXmlNode *node; const gchar *payload; goffset len; parser = rest_xml_parser_new (); payload = rest_proxy_call_get_payload (call); len = rest_proxy_call_get_payload_length (call); write (1, payload, len); node = rest_xml_parser_parse_from_data (parser, payload, len); _rest_xml_node_output (node, 0); rest_xml_node_unref (node); g_object_unref (parser); g_main_loop_quit ((GMainLoop *)userdata); } gint main (gint argc, gchar **argv) { RestProxy *proxy; RestProxyCall *call; GMainLoop *loop; g_type_init (); loop = g_main_loop_new (NULL, FALSE); proxy = rest_proxy_new ("http://www.flickr.com/services/rest/", FALSE); call = rest_proxy_new_call (proxy); rest_proxy_call_set_method (call, "GET"); rest_proxy_call_add_params (call, "method", "flickr.photos.getInfo", "api_key", "314691be2e63a4d58994b2be01faacfb", "photo_id", "2658808091", NULL); rest_proxy_call_async (call, proxy_call_raw_async_cb, NULL, loop, NULL); g_main_loop_run (loop); g_object_unref (call); call = rest_proxy_new_call (proxy); rest_proxy_call_set_method (call, "GET"); rest_proxy_call_add_params (call, "method", "flickr.people.getPublicPhotos", "api_key", "314691be2e63a4d58994b2be01faacfb", "user_id","66598853@N00", NULL); rest_proxy_call_async (call, proxy_call_raw_async_cb, NULL, loop, NULL); g_main_loop_run (loop); g_object_unref (call); g_object_unref (proxy); g_main_loop_unref (loop); } librest/examples/test-raw.c0000664000175000017500000000443612014274314014347 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include static void proxy_call_async_cb (RestProxyCall *call, const GError *error, GObject *weak_object, gpointer userdata) { const gchar *payload; goffset len; payload = rest_proxy_call_get_payload (call); len = rest_proxy_call_get_payload_length (call); write (1, payload, len); g_main_loop_quit ((GMainLoop *)userdata); } gint main (gint argc, gchar **argv) { RestProxy *proxy; RestProxyCall *call; GMainLoop *loop; const gchar *payload; gssize len; g_type_init (); loop = g_main_loop_new (NULL, FALSE); proxy = rest_proxy_new ("http://www.flickr.com/services/rest/", FALSE); call = rest_proxy_new_call (proxy); rest_proxy_call_add_params (call, "method", "flickr.test.echo", "api_key", "314691be2e63a4d58994b2be01faacfb", "format", "json", NULL); rest_proxy_call_async (call, proxy_call_async_cb, NULL, loop, NULL); g_main_loop_run (loop); rest_proxy_call_run (call, NULL, NULL); payload = rest_proxy_call_get_payload (call); len = rest_proxy_call_get_payload_length (call); write (1, payload, len); g_object_unref (call); g_object_unref (proxy); } librest/examples/get-fireeagle-location.c0000664000175000017500000000612712014274314017106 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; GError *error = NULL; char pin[256]; RestXmlParser *parser; RestXmlNode *root, *node; g_type_init (); /* Create the proxy */ proxy = oauth_proxy_new (/* Consumer Key */ "NmUm6hxQ9a4u", /* Consumer Secret */ "t4FM7LiUeD4RBwKSPa6ichKPDh5Jx4kt", /* FireEagle endpoint */ "https://fireeagle.yahooapis.com/", FALSE); /* First stage authentication, this gets a request token. */ if (!oauth_proxy_request_token (OAUTH_PROXY (proxy), "oauth/request_token", "oob", &error)) g_error ("Cannot request token: %s", error->message); /* From the token construct a URL for the user to visit */ g_print ("Go to https://fireeagle.yahoo.net/oauth/authorize?oauth_token=%s then enter the verification code\n", oauth_proxy_get_token (OAUTH_PROXY (proxy))); /* Read the PIN */ fgets (pin, sizeof (pin), stdin); g_strchomp (pin); /* Second stage authentication, this gets an access token. */ if (!oauth_proxy_access_token (OAUTH_PROXY (proxy), "oauth/access_token", pin, &error)) g_error ("Cannot request token: %s", error->message); /* Get the user's current location */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "api/0.1/user"); if (!rest_proxy_call_run (call, NULL, &error)) g_error ("Cannot make call: %s", error->message); parser = rest_xml_parser_new (); root = rest_xml_parser_parse_from_data (parser, rest_proxy_call_get_payload (call), rest_proxy_call_get_payload_length (call)); g_object_unref (parser); g_object_unref (call); g_object_unref (proxy); node = rest_xml_node_find (root, "location"); node = rest_xml_node_find (node, "name"); g_print ("%s\n", node->content); return 0; } librest/examples/continuous-twitter.c0000664000175000017500000000573612014274314016513 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include static void _call_continous_cb (RestProxyCall *call, const gchar *buf, gsize len, const GError *error, GObject *weak_object, gpointer userdata) { g_message ("%s", buf); } int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; GError *error = NULL; char pin[256]; GMainLoop *loop; g_type_init (); loop = g_main_loop_new (NULL, FALSE); /* Create the proxy */ proxy = oauth_proxy_new ("UfXFxDbUjk41scg0kmkFwA", "pYQlfI2ZQ1zVK0f01dnfhFTWzizBGDnhNJIw6xwto", "https://api.twitter.com/", FALSE); /* First stage authentication, this gets a request token */ if (!oauth_proxy_request_token (OAUTH_PROXY (proxy), "oauth/request_token", "oob", &error)) g_error ("Cannot get request token: %s", error->message); /* From the token construct a URL for the user to visit */ g_print ("Go to http://twitter.com/oauth/authorize?oauth_token=%s then enter the PIN\n", oauth_proxy_get_token (OAUTH_PROXY (proxy))); fgets (pin, sizeof (pin), stdin); g_strchomp (pin); /* Second stage authentication, this gets an access token */ if (!oauth_proxy_access_token (OAUTH_PROXY (proxy), "oauth/access_token", pin, &error)) g_error ("Cannot get access token: %s", error->message); /* We're now authenticated */ /* Post the status message */ call = rest_proxy_new_call (proxy); g_object_set (proxy, "url-format", "http://stream.twitter.com/", NULL); rest_proxy_call_set_function (call, "1/statuses/filter.json"); rest_proxy_call_set_method (call, "GET"); rest_proxy_call_add_param (call, "track", "Cameron"); rest_proxy_call_add_param (call, "delimited", "length"); rest_proxy_call_continuous (call, _call_continous_cb, NULL, NULL, NULL); g_main_loop_run (loop); g_object_unref (call); g_object_unref (proxy); return 0; } librest/examples/post-twitter.c0000664000175000017500000000507512014274314015266 0ustar bobbob/* * librest - RESTful web services access * Copyright (c) 2008, 2009, Intel Corporation. * * Authors: Rob Bradford * Ross Burton * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include int main (int argc, char **argv) { RestProxy *proxy; RestProxyCall *call; GError *error = NULL; char pin[256]; g_type_init (); if (argc != 2) { g_printerr ("$ post-twitter \"message\"\n"); return 1; } /* Create the proxy */ proxy = oauth_proxy_new ("UfXFxDbUjk41scg0kmkFwA", "pYQlfI2ZQ1zVK0f01dnfhFTWzizBGDnhNJIw6xwto", "https://api.twitter.com/", FALSE); /* First stage authentication, this gets a request token */ if (!oauth_proxy_request_token (OAUTH_PROXY (proxy), "oauth/request_token", "oob", &error)) g_error ("Cannot get request token: %s", error->message); /* From the token construct a URL for the user to visit */ g_print ("Go to http://twitter.com/oauth/authorize?oauth_token=%s then enter the PIN\n", oauth_proxy_get_token (OAUTH_PROXY (proxy))); fgets (pin, sizeof (pin), stdin); g_strchomp (pin); /* Second stage authentication, this gets an access token */ if (!oauth_proxy_access_token (OAUTH_PROXY (proxy), "oauth/access_token", pin, &error)) g_error ("Cannot get access token: %s", error->message); /* We're now authenticated */ /* Post the status message */ call = rest_proxy_new_call (proxy); rest_proxy_call_set_function (call, "1/statuses/update.xml"); rest_proxy_call_set_method (call, "POST"); rest_proxy_call_add_param (call, "status", argv[1]); if (!rest_proxy_call_sync (call, &error)) g_error ("Cannot make call: %s", error->message); /* TODO: parse the XML and print something useful */ g_print ("%s\n", rest_proxy_call_get_payload (call)); g_object_unref (call); g_object_unref (proxy); return 0; } librest/AUTHORS0000664000175000017500000000010612014274314011655 0ustar bobbobRob Bradford Ross Burton librest/ChangeLog0000664000175000017500000000000012014274314012350 0ustar bobboblibrest/COPYING0000664000175000017500000006363712014274314011662 0ustar bobbob GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it!