1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
5 * Copyright (C) 2000-2003, Ximian, Inc.
16 #include "soup-auth.h"
17 #include "soup-session.h"
18 #include "soup-connection.h"
19 #include "soup-connection-ntlm.h"
20 #include "soup-marshal.h"
21 #include "soup-message-filter.h"
22 #include "soup-message-queue.h"
29 GSList *connections; /* CONTAINS: SoupConnection */
32 GHashTable *auth_realms; /* path -> scheme:realm */
33 GHashTable *auths; /* scheme:realm -> SoupAuth */
38 guint max_conns, max_conns_per_host;
46 GHashTable *hosts; /* SoupUri -> SoupSessionHost */
47 GHashTable *conns; /* SoupConnection -> SoupSessionHost */
50 SoupSessionHost *proxy_host;
52 /* Must hold the host_lock before potentially creating a
53 * new SoupSessionHost, or adding/removing a connection.
54 * Must not emit signals or destroy objects while holding it.
58 GMainContext *async_context;
60 /* Holds the timeout value for the connection, when
61 no response is received.
65 #define SOUP_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SESSION, SoupSessionPrivate))
67 static guint host_uri_hash (gconstpointer key);
68 static gboolean host_uri_equal (gconstpointer v1, gconstpointer v2);
69 static void free_host (SoupSessionHost *host);
71 static void setup_message (SoupMessageFilter *filter, SoupMessage *msg);
73 static void queue_message (SoupSession *session, SoupMessage *msg,
74 SoupMessageCallbackFn callback,
76 static void requeue_message (SoupSession *session, SoupMessage *msg);
77 static void cancel_message (SoupSession *session, SoupMessage *msg);
79 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
80 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 4
82 static void filter_iface_init (SoupMessageFilterClass *filter_class);
84 G_DEFINE_TYPE_EXTENDED (SoupSession, soup_session, G_TYPE_OBJECT, 0,
85 G_IMPLEMENT_INTERFACE (SOUP_TYPE_MESSAGE_FILTER,
94 static guint signals[LAST_SIGNAL] = { 0 };
101 PROP_MAX_CONNS_PER_HOST,
110 static void set_property (GObject *object, guint prop_id,
111 const GValue *value, GParamSpec *pspec);
112 static void get_property (GObject *object, guint prop_id,
113 GValue *value, GParamSpec *pspec);
116 soup_session_init (SoupSession *session)
118 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
120 session->queue = soup_message_queue_new ();
122 priv->host_lock = g_mutex_new ();
123 priv->hosts = g_hash_table_new (host_uri_hash, host_uri_equal);
124 priv->conns = g_hash_table_new (NULL, NULL);
126 priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
127 priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
133 foreach_free_host (gpointer key, gpointer host, gpointer data)
140 cleanup_hosts (SoupSessionPrivate *priv)
142 GHashTable *old_hosts;
144 g_mutex_lock (priv->host_lock);
145 old_hosts = priv->hosts;
146 priv->hosts = g_hash_table_new (host_uri_hash, host_uri_equal);
147 g_mutex_unlock (priv->host_lock);
149 g_hash_table_foreach_remove (old_hosts, foreach_free_host, NULL);
150 g_hash_table_destroy (old_hosts);
154 dispose (GObject *object)
156 SoupSession *session = SOUP_SESSION (object);
157 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
160 soup_session_abort (session);
161 cleanup_hosts (priv);
164 for (f = priv->filters; f; f = f->next)
165 g_object_unref (f->data);
166 g_slist_free (priv->filters);
167 priv->filters = NULL;
170 G_OBJECT_CLASS (soup_session_parent_class)->dispose (object);
174 finalize (GObject *object)
176 SoupSession *session = SOUP_SESSION (object);
177 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
179 soup_message_queue_destroy (session->queue);
181 g_mutex_free (priv->host_lock);
182 g_hash_table_destroy (priv->hosts);
183 g_hash_table_destroy (priv->conns);
185 if (priv->async_context)
186 g_main_context_unref (priv->async_context);
188 G_OBJECT_CLASS (soup_session_parent_class)->finalize (object);
192 soup_session_class_init (SoupSessionClass *session_class)
194 GObjectClass *object_class = G_OBJECT_CLASS (session_class);
196 g_type_class_add_private (session_class, sizeof (SoupSessionPrivate));
198 /* virtual method definition */
199 session_class->queue_message = queue_message;
200 session_class->requeue_message = requeue_message;
201 session_class->cancel_message = cancel_message;
203 /* virtual method override */
204 object_class->dispose = dispose;
205 object_class->finalize = finalize;
206 object_class->set_property = set_property;
207 object_class->get_property = get_property;
212 * SoupSession::authenticate:
213 * @session: the session
214 * @msg: the #SoupMessage being sent
215 * @auth_type: the authentication type
216 * @auth_realm: the realm being authenticated to
217 * @username: the signal handler should set this to point to
218 * the provided username
219 * @password: the signal handler should set this to point to
220 * the provided password
222 * Emitted when the session requires authentication. The
223 * credentials may come from the user, or from cached
224 * information. If no credentials are available, leave
225 * @username and @password unchanged.
227 * If the provided credentials fail, the #reauthenticate
228 * signal will be emitted.
230 signals[AUTHENTICATE] =
231 g_signal_new ("authenticate",
232 G_OBJECT_CLASS_TYPE (object_class),
234 G_STRUCT_OFFSET (SoupSessionClass, authenticate),
236 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
245 * SoupSession::reauthenticate:
246 * @session: the session
247 * @msg: the #SoupMessage being sent
248 * @auth_type: the authentication type
249 * @auth_realm: the realm being authenticated to
250 * @username: the signal handler should set this to point to
251 * the provided username
252 * @password: the signal handler should set this to point to
253 * the provided password
255 * Emitted when the credentials provided by the application to
256 * the #authenticate signal have failed. This gives the
257 * application a second chance to provide authentication
258 * credentials. If the new credentials also fail, #SoupSession
259 * will emit #reauthenticate again, and will continue doing so
260 * until the provided credentials work, or a #reauthenticate
261 * signal emission "fails" (because the handler left @username
262 * and @password unchanged). At that point, the 401 or 407
263 * error status will be returned to the caller.
265 * If your application only uses cached passwords, it should
266 * only connect to #authenticate, and not #reauthenticate.
268 * If your application always prompts the user for a password,
269 * and never uses cached information, then you can connect the
270 * same handler to #authenticate and #reauthenticate.
272 * To get standard web-browser behavior, return either cached
273 * information or a user-provided password (whichever is
274 * available) from the #authenticate handler, but return only
275 * user-provided information from the #reauthenticate handler.
277 signals[REAUTHENTICATE] =
278 g_signal_new ("reauthenticate",
279 G_OBJECT_CLASS_TYPE (object_class),
281 G_STRUCT_OFFSET (SoupSessionClass, reauthenticate),
283 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
292 g_object_class_install_property (
293 object_class, PROP_PROXY_URI,
294 g_param_spec_pointer (SOUP_SESSION_PROXY_URI,
296 "The HTTP Proxy to use for this session",
298 g_object_class_install_property (
299 object_class, PROP_MAX_CONNS,
300 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
301 "Max Connection Count",
302 "The maximum number of connections that the session can open at once",
307 g_object_class_install_property (
308 object_class, PROP_MAX_CONNS_PER_HOST,
309 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
310 "Max Per-Host Connection Count",
311 "The maximum number of connections that the session can open at once to a given host",
316 g_object_class_install_property (
317 object_class, PROP_USE_NTLM,
318 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
320 "Whether or not to use NTLM authentication",
323 g_object_class_install_property (
324 object_class, PROP_SSL_CA_FILE,
325 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
327 "File containing SSL CA certificates",
330 g_object_class_install_property (
331 object_class, PROP_ASYNC_CONTEXT,
332 g_param_spec_pointer (SOUP_SESSION_ASYNC_CONTEXT,
333 "Async GMainContext",
334 "The GMainContext to dispatch async I/O in",
335 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
336 g_object_class_install_property (
337 object_class, PROP_TIMEOUT,
338 g_param_spec_uint (SOUP_SESSION_TIMEOUT,
340 "Value in seconds to timeout a blocking I/O",
346 filter_iface_init (SoupMessageFilterClass *filter_class)
348 /* interface implementation */
349 filter_class->setup_message = setup_message;
354 safe_uri_equal (const SoupUri *a, const SoupUri *b)
359 if ((a && !b) || (b && !a))
362 return soup_uri_equal (a, b);
366 safe_str_equal (const char *a, const char *b)
371 if ((a && !b) || (b && !a))
374 return strcmp (a, b) == 0;
378 set_property (GObject *object, guint prop_id,
379 const GValue *value, GParamSpec *pspec)
381 SoupSession *session = SOUP_SESSION (object);
382 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
384 gboolean need_abort = FALSE;
385 gboolean ca_file_changed = FALSE;
386 const char *new_ca_file;
390 pval = g_value_get_pointer (value);
392 if (!safe_uri_equal (priv->proxy_uri, pval))
396 soup_uri_free (priv->proxy_uri);
398 priv->proxy_uri = pval ? soup_uri_copy (pval) : NULL;
401 soup_session_abort (session);
402 cleanup_hosts (priv);
407 priv->max_conns = g_value_get_int (value);
409 case PROP_MAX_CONNS_PER_HOST:
410 priv->max_conns_per_host = g_value_get_int (value);
413 priv->use_ntlm = g_value_get_boolean (value);
415 case PROP_SSL_CA_FILE:
416 new_ca_file = g_value_get_string (value);
418 if (!safe_str_equal (priv->ssl_ca_file, new_ca_file))
419 ca_file_changed = TRUE;
421 g_free (priv->ssl_ca_file);
422 priv->ssl_ca_file = g_strdup (new_ca_file);
424 if (ca_file_changed) {
425 if (priv->ssl_creds) {
426 soup_ssl_free_client_credentials (priv->ssl_creds);
427 priv->ssl_creds = NULL;
430 cleanup_hosts (priv);
434 case PROP_ASYNC_CONTEXT:
435 priv->async_context = g_value_get_pointer (value);
436 if (priv->async_context)
437 g_main_context_ref (priv->async_context);
440 priv->timeout = g_value_get_uint (value);
448 get_property (GObject *object, guint prop_id,
449 GValue *value, GParamSpec *pspec)
451 SoupSession *session = SOUP_SESSION (object);
452 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
456 g_value_set_pointer (value, priv->proxy_uri ?
457 soup_uri_copy (priv->proxy_uri) :
461 g_value_set_int (value, priv->max_conns);
463 case PROP_MAX_CONNS_PER_HOST:
464 g_value_set_int (value, priv->max_conns_per_host);
467 g_value_set_boolean (value, priv->use_ntlm);
469 case PROP_SSL_CA_FILE:
470 g_value_set_string (value, priv->ssl_ca_file);
472 case PROP_ASYNC_CONTEXT:
473 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
476 g_value_set_uint (value, priv->timeout);
485 * soup_session_add_filter:
486 * @session: a #SoupSession
487 * @filter: an object implementing the #SoupMessageFilter interface
489 * Adds @filter to @session's list of message filters to be applied to
493 soup_session_add_filter (SoupSession *session, SoupMessageFilter *filter)
495 SoupSessionPrivate *priv;
497 g_return_if_fail (SOUP_IS_SESSION (session));
498 g_return_if_fail (SOUP_IS_MESSAGE_FILTER (filter));
499 priv = SOUP_SESSION_GET_PRIVATE (session);
501 g_object_ref (filter);
502 priv->filters = g_slist_prepend (priv->filters, filter);
506 * soup_session_remove_filter:
507 * @session: a #SoupSession
508 * @filter: an object implementing the #SoupMessageFilter interface
510 * Removes @filter from @session's list of message filters
513 soup_session_remove_filter (SoupSession *session, SoupMessageFilter *filter)
515 SoupSessionPrivate *priv;
517 g_return_if_fail (SOUP_IS_SESSION (session));
518 g_return_if_fail (SOUP_IS_MESSAGE_FILTER (filter));
519 priv = SOUP_SESSION_GET_PRIVATE (session);
521 priv->filters = g_slist_remove (priv->filters, filter);
522 g_object_unref (filter);
528 host_uri_hash (gconstpointer key)
530 const SoupUri *uri = key;
532 return (uri->protocol << 16) + uri->port + g_str_hash (uri->host);
536 host_uri_equal (gconstpointer v1, gconstpointer v2)
538 const SoupUri *one = v1;
539 const SoupUri *two = v2;
541 if (one->protocol != two->protocol)
543 if (one->port != two->port)
546 return strcmp (one->host, two->host) == 0;
549 static SoupSessionHost *
550 soup_session_host_new (SoupSession *session, const SoupUri *source_uri)
552 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
553 SoupSessionHost *host;
555 host = g_new0 (SoupSessionHost, 1);
556 host->root_uri = soup_uri_copy_root (source_uri);
558 if (host->root_uri->protocol == SOUP_PROTOCOL_HTTPS &&
561 soup_ssl_get_client_credentials (priv->ssl_ca_file);
567 /* Note: get_host_for_message doesn't lock the host_lock. The caller
568 * must do it itself if there's a chance the host doesn't already
571 static SoupSessionHost *
572 get_host_for_message (SoupSession *session, SoupMessage *msg)
574 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
575 SoupSessionHost *host;
576 const SoupUri *source = soup_message_get_uri (msg);
578 host = g_hash_table_lookup (priv->hosts, source);
582 host = soup_session_host_new (session, source);
583 g_hash_table_insert (priv->hosts, host->root_uri, host);
588 /* Note: get_proxy_host doesn't lock the host_lock. The caller must do
589 * it itself if there's a chance the host doesn't already exist.
591 static SoupSessionHost *
592 get_proxy_host (SoupSession *session)
594 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
596 if (priv->proxy_host || !priv->proxy_uri)
597 return priv->proxy_host;
600 soup_session_host_new (session, priv->proxy_uri);
601 return priv->proxy_host;
605 free_realm (gpointer path, gpointer scheme_realm, gpointer data)
608 g_free (scheme_realm);
612 free_auth (gpointer scheme_realm, gpointer auth, gpointer data)
614 g_free (scheme_realm);
615 g_object_unref (auth);
619 free_host (SoupSessionHost *host)
621 while (host->connections) {
622 SoupConnection *conn = host->connections->data;
624 host->connections = g_slist_remove (host->connections, conn);
625 soup_connection_disconnect (conn);
628 if (host->auth_realms) {
629 g_hash_table_foreach (host->auth_realms, free_realm, NULL);
630 g_hash_table_destroy (host->auth_realms);
633 g_hash_table_foreach (host->auths, free_auth, NULL);
634 g_hash_table_destroy (host->auths);
637 soup_uri_free (host->root_uri);
644 lookup_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
646 SoupSessionHost *host;
648 const char *realm, *const_path;
651 host = get_proxy_host (session);
654 host = get_host_for_message (session, msg);
655 const_path = soup_message_get_uri (msg)->path;
660 g_return_val_if_fail (host != NULL, NULL);
662 if (!host->auth_realms)
665 path = g_strdup (const_path);
668 realm = g_hash_table_lookup (host->auth_realms, path);
672 dir = strrchr (path, '/');
683 return g_hash_table_lookup (host->auths, realm);
689 invalidate_auth (SoupSessionHost *host, SoupAuth *auth)
694 realm = g_strdup_printf ("%s:%s",
695 soup_auth_get_scheme_name (auth),
696 soup_auth_get_realm (auth));
698 if (g_hash_table_lookup_extended (host->auths, realm, &key, &value) &&
699 auth == (SoupAuth *)value) {
700 g_hash_table_remove (host->auths, realm);
702 g_object_unref (auth);
708 authenticate_auth (SoupSession *session, SoupAuth *auth,
709 SoupMessage *msg, gboolean prior_auth_failed,
712 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
714 char *username = NULL, *password = NULL;
717 uri = priv->proxy_uri;
719 uri = soup_message_get_uri (msg);
721 if (uri->passwd && !prior_auth_failed) {
722 soup_auth_authenticate (auth, uri->user, uri->passwd);
726 g_signal_emit (session, signals[prior_auth_failed ? REAUTHENTICATE : AUTHENTICATE], 0,
727 msg, soup_auth_get_scheme_name (auth),
728 soup_auth_get_realm (auth),
729 &username, &password);
730 if (username || password)
731 soup_auth_authenticate (auth, username, password);
735 memset (password, 0, strlen (password));
739 return soup_auth_is_authenticated (auth);
743 update_auth_internal (SoupSession *session, SoupMessage *msg,
744 const GSList *headers, gboolean proxy,
745 gboolean got_unauthorized)
747 SoupSessionHost *host;
748 SoupAuth *new_auth, *prior_auth, *old_auth;
749 gpointer old_path, old_realm;
750 const SoupUri *msg_uri;
754 gboolean prior_auth_failed = FALSE;
757 host = get_proxy_host (session);
759 host = get_host_for_message (session, msg);
761 g_return_val_if_fail (host != NULL, FALSE);
763 /* Try to construct a new auth from the headers; if we can't,
764 * there's no way we'll be able to authenticate.
766 msg_uri = soup_message_get_uri (msg);
767 new_auth = soup_auth_new_from_header_list (headers);
771 /* See if this auth is the same auth we used last time */
772 prior_auth = lookup_auth (session, msg, proxy);
774 G_OBJECT_TYPE (prior_auth) == G_OBJECT_TYPE (new_auth) &&
775 !strcmp (soup_auth_get_realm (prior_auth),
776 soup_auth_get_realm (new_auth))) {
777 if (!got_unauthorized) {
778 /* The user is just trying to preauthenticate
779 * using information we already have, so
780 * there's nothing more that needs to be done.
782 g_object_unref (new_auth);
786 /* The server didn't like the username/password we
787 * provided before. Invalidate it and note this fact.
789 invalidate_auth (host, prior_auth);
790 prior_auth_failed = TRUE;
793 if (!host->auth_realms) {
794 host->auth_realms = g_hash_table_new (g_str_hash, g_str_equal);
795 host->auths = g_hash_table_new (g_str_hash, g_str_equal);
798 /* Record where this auth realm is used */
799 realm = g_strdup_printf ("%s:%s",
800 soup_auth_get_scheme_name (new_auth),
801 soup_auth_get_realm (new_auth));
804 * RFC 2617 is somewhat unclear about the scope of protection
805 * spaces with regard to proxies. The only mention of it is
806 * as an aside in section 3.2.1, where it is defining the fields
807 * of a Digest challenge and says that the protection space is
808 * always the entire proxy. Is this the case for all authentication
809 * schemes or just Digest? Who knows, but we're assuming all.
812 pspace = g_slist_prepend (NULL, g_strdup (""));
814 pspace = soup_auth_get_protection_space (new_auth, msg_uri);
816 for (p = pspace; p; p = p->next) {
818 if (g_hash_table_lookup_extended (host->auth_realms, path,
819 &old_path, &old_realm)) {
820 g_hash_table_remove (host->auth_realms, old_path);
825 g_hash_table_insert (host->auth_realms,
826 g_strdup (path), g_strdup (realm));
828 soup_auth_free_protection_space (new_auth, pspace);
830 /* Now, make sure the auth is recorded. (If there's a
831 * pre-existing auth, we keep that rather than the new one,
832 * since the old one might already be authenticated.)
834 old_auth = g_hash_table_lookup (host->auths, realm);
837 g_object_unref (new_auth);
840 g_hash_table_insert (host->auths, realm, new_auth);
842 /* If we need to authenticate, try to do it. */
843 if (!soup_auth_is_authenticated (new_auth)) {
844 return authenticate_auth (session, new_auth,
845 msg, prior_auth_failed, proxy);
848 /* Otherwise we're good. */
853 connection_authenticate (SoupConnection *conn, SoupMessage *msg,
854 const char *auth_type, const char *auth_realm,
855 char **username, char **password, gpointer session)
857 g_signal_emit (session, signals[AUTHENTICATE], 0,
858 msg, auth_type, auth_realm, username, password);
862 connection_reauthenticate (SoupConnection *conn, SoupMessage *msg,
863 const char *auth_type, const char *auth_realm,
864 char **username, char **password,
867 g_signal_emit (conn, signals[REAUTHENTICATE], 0,
868 msg, auth_type, auth_realm, username, password);
873 authorize_handler (SoupMessage *msg, gpointer user_data)
875 SoupSession *session = user_data;
876 const GSList *headers;
879 if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
880 headers = soup_message_get_header_list (msg->response_headers,
881 "Proxy-Authenticate");
884 headers = soup_message_get_header_list (msg->response_headers,
891 if (update_auth_internal (session, msg, headers, proxy, TRUE))
892 soup_session_requeue_message (session, msg);
896 redirect_handler (SoupMessage *msg, gpointer user_data)
898 SoupSession *session = user_data;
902 new_loc = soup_message_get_header (msg->response_headers, "Location");
906 /* Location is supposed to be an absolute URI, but some sites
907 * are lame, so we use soup_uri_new_with_base().
909 new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
911 soup_message_set_status_full (msg,
912 SOUP_STATUS_MALFORMED,
913 "Invalid Redirect URL");
917 soup_message_set_uri (msg, new_uri);
918 soup_uri_free (new_uri);
920 soup_session_requeue_message (session, msg);
924 add_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
926 const char *header = proxy ? "Proxy-Authorization" : "Authorization";
930 auth = lookup_auth (session, msg, proxy);
933 if (!soup_auth_is_authenticated (auth) &&
934 !authenticate_auth (session, auth, msg, FALSE, proxy))
937 token = soup_auth_get_authorization (auth, msg);
939 soup_message_remove_header (msg->request_headers, header);
940 soup_message_add_header (msg->request_headers, header, token);
946 setup_message (SoupMessageFilter *filter, SoupMessage *msg)
948 SoupSession *session = SOUP_SESSION (filter);
949 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
952 for (f = priv->filters; f; f = f->next) {
954 soup_message_filter_setup_message (filter, msg);
957 add_auth (session, msg, FALSE);
958 soup_message_add_status_code_handler (
959 msg, SOUP_STATUS_UNAUTHORIZED,
960 SOUP_HANDLER_POST_BODY,
961 authorize_handler, session);
963 if (priv->proxy_uri) {
964 add_auth (session, msg, TRUE);
965 soup_message_add_status_code_handler (
966 msg, SOUP_STATUS_PROXY_UNAUTHORIZED,
967 SOUP_HANDLER_POST_BODY,
968 authorize_handler, session);
973 find_oldest_connection (gpointer key, gpointer host, gpointer data)
975 SoupConnection *conn = key, **oldest = data;
977 /* Don't prune a connection that is currently in use, or
978 * hasn't been used yet.
980 if (soup_connection_is_in_use (conn) ||
981 soup_connection_last_used (conn) == 0)
984 if (!*oldest || (soup_connection_last_used (conn) <
985 soup_connection_last_used (*oldest)))
990 * soup_session_try_prune_connection:
991 * @session: a #SoupSession
993 * Finds the least-recently-used idle connection in @session and closes
996 * Return value: %TRUE if a connection was closed, %FALSE if there are
997 * no idle connections.
1000 soup_session_try_prune_connection (SoupSession *session)
1002 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1003 SoupConnection *oldest = NULL;
1005 g_mutex_lock (priv->host_lock);
1006 g_hash_table_foreach (priv->conns, find_oldest_connection,
1009 /* Ref the connection before unlocking the mutex in
1010 * case someone else tries to prune it too.
1012 g_object_ref (oldest);
1013 g_mutex_unlock (priv->host_lock);
1014 soup_connection_disconnect (oldest);
1015 g_object_unref (oldest);
1018 g_mutex_unlock (priv->host_lock);
1024 connection_disconnected (SoupConnection *conn, gpointer user_data)
1026 SoupSession *session = user_data;
1027 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1028 SoupSessionHost *host;
1030 g_mutex_lock (priv->host_lock);
1032 host = g_hash_table_lookup (priv->conns, conn);
1034 g_hash_table_remove (priv->conns, conn);
1035 host->connections = g_slist_remove (host->connections, conn);
1039 g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
1042 g_mutex_unlock (priv->host_lock);
1043 g_object_unref (conn);
1047 connect_result (SoupConnection *conn, guint status, gpointer user_data)
1049 SoupSession *session = user_data;
1050 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1051 SoupSessionHost *host;
1052 SoupMessageQueueIter iter;
1055 g_mutex_lock (priv->host_lock);
1057 host = g_hash_table_lookup (priv->conns, conn);
1059 g_mutex_unlock (priv->host_lock);
1063 if (status == SOUP_STATUS_OK) {
1064 soup_connection_reserve (conn);
1065 host->connections = g_slist_prepend (host->connections, conn);
1066 g_mutex_unlock (priv->host_lock);
1070 /* The connection failed. */
1071 g_mutex_unlock (priv->host_lock);
1072 connection_disconnected (conn, session);
1074 if (host->connections) {
1075 /* Something went wrong this time, but we have at
1076 * least one open connection to this host. So just
1077 * leave the message in the queue so it can use that
1078 * connection once it's free.
1083 /* There are two possibilities: either status is
1084 * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
1085 * will create a new connection (and all we need to do here
1086 * is downgrade the message from CONNECTING to QUEUED); or
1087 * status is something else, probably CANT_CONNECT or
1088 * CANT_RESOLVE or the like, in which case we need to cancel
1089 * any messages waiting for this host, since they're out
1092 for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
1093 if (get_host_for_message (session, msg) == host) {
1094 if (status == SOUP_STATUS_TRY_AGAIN) {
1095 if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING)
1096 msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1098 soup_message_set_status (msg, status);
1099 soup_session_cancel_message (session, msg);
1106 * soup_session_get_connection:
1107 * @session: a #SoupSession
1108 * @msg: a #SoupMessage
1109 * @try_pruning: on return, whether or not to try pruning a connection
1110 * @is_new: on return, %TRUE if the returned connection is new and not
1113 * Tries to find or create a connection for @msg; this is an internal
1114 * method for #SoupSession subclasses.
1116 * If there is an idle connection to the relevant host available, then
1117 * that connection will be returned (with *@is_new set to %FALSE). The
1118 * connection will be marked "reserved", so the caller must call
1119 * soup_connection_release() if it ends up not using the connection
1122 * If there is no idle connection available, but it is possible to
1123 * create a new connection, then one will be created and returned,
1124 * with *@is_new set to %TRUE. The caller MUST then call
1125 * soup_connection_connect_sync() or soup_connection_connect_async()
1126 * to connect it. If the connection attempt succeeds, the connection
1127 * will be marked "reserved" and added to @session's connection pool
1128 * once it connects. If the connection attempt fails, the connection
1131 * If no connection is available and a new connection cannot be made,
1132 * soup_session_get_connection() will return %NULL. If @session has
1133 * the maximum number of open connections open, but does not have the
1134 * maximum number of per-host connections open to the relevant host,
1135 * then *@try_pruning will be set to %TRUE. In this case, the caller
1136 * can call soup_session_try_prune_connection() to close an idle
1137 * connection, and then try soup_session_get_connection() again. (If
1138 * calling soup_session_try_prune_connection() wouldn't help, then
1139 * *@try_pruning is left untouched; it is NOT set to %FALSE.)
1141 * Return value: a #SoupConnection, or %NULL
1144 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
1145 gboolean *try_pruning, gboolean *is_new)
1147 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1148 SoupConnection *conn;
1149 SoupSessionHost *host;
1152 g_mutex_lock (priv->host_lock);
1154 host = get_host_for_message (session, msg);
1155 for (conns = host->connections; conns; conns = conns->next) {
1156 if (!soup_connection_is_in_use (conns->data)) {
1157 soup_connection_reserve (conns->data);
1158 g_mutex_unlock (priv->host_lock);
1164 if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING) {
1165 /* We already started a connection for this
1166 * message, so don't start another one.
1168 g_mutex_unlock (priv->host_lock);
1172 if (host->num_conns >= priv->max_conns_per_host) {
1173 g_mutex_unlock (priv->host_lock);
1177 if (priv->num_conns >= priv->max_conns) {
1178 *try_pruning = TRUE;
1179 g_mutex_unlock (priv->host_lock);
1183 /* Make sure priv->proxy_host gets set now while
1184 * we have the host_lock.
1186 if (priv->proxy_uri)
1187 get_proxy_host (session);
1189 conn = g_object_new (
1191 SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
1192 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
1193 SOUP_CONNECTION_PROXY_URI, priv->proxy_uri,
1194 SOUP_CONNECTION_SSL_CREDENTIALS, priv->ssl_creds,
1195 SOUP_CONNECTION_MESSAGE_FILTER, session,
1196 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
1197 SOUP_CONNECTION_TIMEOUT, priv->timeout,
1199 g_signal_connect (conn, "connect_result",
1200 G_CALLBACK (connect_result),
1202 g_signal_connect (conn, "disconnected",
1203 G_CALLBACK (connection_disconnected),
1205 g_signal_connect (conn, "authenticate",
1206 G_CALLBACK (connection_authenticate),
1208 g_signal_connect (conn, "reauthenticate",
1209 G_CALLBACK (connection_reauthenticate),
1212 g_hash_table_insert (priv->conns, conn, host);
1214 /* We increment the connection counts so it counts against the
1215 * totals, but we don't add it to the host's connection list
1216 * yet, since it's not ready for use.
1221 /* Mark the request as connecting, so we don't try to open
1222 * another new connection for it while waiting for this one.
1224 msg->status = SOUP_MESSAGE_STATUS_CONNECTING;
1226 g_mutex_unlock (priv->host_lock);
1232 message_finished (SoupMessage *msg, gpointer user_data)
1234 SoupSession *session = user_data;
1236 if (!SOUP_MESSAGE_IS_STARTING (msg)) {
1237 soup_message_queue_remove_message (session->queue, msg);
1238 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
1243 queue_message (SoupSession *session, SoupMessage *msg,
1244 SoupMessageCallbackFn callback, gpointer user_data)
1246 g_signal_connect_after (msg, "finished",
1247 G_CALLBACK (message_finished), session);
1249 if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
1250 soup_message_add_status_class_handler (
1251 msg, SOUP_STATUS_CLASS_REDIRECT,
1252 SOUP_HANDLER_POST_BODY,
1253 redirect_handler, session);
1256 msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1257 soup_message_queue_append (session->queue, msg);
1261 * soup_session_queue_message:
1262 * @session: a #SoupSession
1263 * @msg: the message to queue
1264 * @callback: a #SoupMessageCallbackFn which will be called after the
1265 * message completes or when an unrecoverable error occurs.
1266 * @user_data: a pointer passed to @callback.
1268 * Queues the message @msg for sending. All messages are processed
1269 * while the glib main loop runs. If @msg has been processed before,
1270 * any resources related to the time it was last sent are freed.
1272 * Upon message completion, the callback specified in @callback will
1273 * be invoked. If after returning from this callback the message has
1274 * not been requeued, @msg will be unreffed.
1277 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1278 SoupMessageCallbackFn callback, gpointer user_data)
1280 g_return_if_fail (SOUP_IS_SESSION (session));
1281 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1283 SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1284 callback, user_data);
1288 requeue_message (SoupSession *session, SoupMessage *msg)
1290 msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1294 * soup_session_requeue_message:
1295 * @session: a #SoupSession
1296 * @msg: the message to requeue
1298 * This causes @msg to be placed back on the queue to be attempted
1302 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
1304 g_return_if_fail (SOUP_IS_SESSION (session));
1305 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1307 SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
1312 * soup_session_send_message:
1313 * @session: a #SoupSession
1314 * @msg: the message to send
1316 * Synchronously send @msg. This call will not return until the
1317 * transfer is finished successfully or there is an unrecoverable
1320 * @msg is not freed upon return.
1322 * Return value: the HTTP status code of the response
1325 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1327 g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1328 g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1330 return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1335 cancel_message (SoupSession *session, SoupMessage *msg)
1337 soup_message_queue_remove_message (session->queue, msg);
1338 soup_message_finished (msg);
1342 * soup_session_cancel_message:
1343 * @session: a #SoupSession
1344 * @msg: the message to cancel
1346 * Causes @session to immediately finish processing @msg. You should
1347 * set a status code on @msg with soup_message_set_status() before
1348 * calling this function.
1351 soup_session_cancel_message (SoupSession *session, SoupMessage *msg)
1353 g_return_if_fail (SOUP_IS_SESSION (session));
1354 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1356 SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg);
1360 * soup_session_abort:
1361 * @session: the session
1363 * Cancels all pending requests in @session.
1366 soup_session_abort (SoupSession *session)
1368 SoupMessageQueueIter iter;
1371 g_return_if_fail (SOUP_IS_SESSION (session));
1373 for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
1374 soup_message_set_status (msg, SOUP_STATUS_CANCELLED);
1375 soup_session_cancel_message (session, msg);