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-auth-basic.h"
18 #include "soup-auth-digest.h"
19 #include "soup-auth-manager-ntlm.h"
20 #include "soup-connection.h"
21 #include "soup-marshal.h"
22 #include "soup-message-private.h"
23 #include "soup-message-queue.h"
24 #include "soup-session.h"
25 #include "soup-session-feature.h"
26 #include "soup-session-private.h"
27 #include "soup-socket.h"
32 * SECTION:soup-session
33 * @short_description: Soup session state object
35 * #SoupSession is the object that controls client-side HTTP. A
36 * #SoupSession encapsulates all of the state that libsoup is keeping
37 * on behalf of your program; cached HTTP connections, authentication
40 * Most applications will only need a single #SoupSession; the primary
41 * reason you might need multiple sessions is if you need to have
42 * multiple independent authentication contexts. (Eg, you are
43 * connecting to a server and authenticating as two different users at
44 * different times; the easiest way to ensure that each #SoupMessage
45 * is sent with the authentication information you intended is to use
46 * one session for the first user, and a second session for the other
49 * #SoupSession itself is an abstract class, with two subclasses. If
50 * you are using the glib main loop, you will generally want to use
51 * #SoupSessionAsync, which uses non-blocking I/O and callbacks. On
52 * the other hand, if your application is threaded and you want to do
53 * synchronous I/O in a separate thread from the UI, use
60 GSList *connections; /* CONTAINS: SoupConnection */
63 GHashTable *auth_realms; /* path -> scheme:realm */
64 GHashTable *auths; /* scheme:realm -> SoupAuth */
72 SoupSSLCredentials *ssl_creds;
74 SoupMessageQueue *queue;
79 SoupAuthManager *auth_manager;
81 GHashTable *hosts; /* SoupURI -> SoupSessionHost */
82 GHashTable *conns; /* SoupConnection -> SoupSessionHost */
84 guint max_conns, max_conns_per_host;
85 guint io_timeout, idle_timeout;
87 /* Must hold the host_lock before potentially creating a
88 * new SoupSessionHost, or adding/removing a connection.
89 * Must not emit signals or destroy objects while holding it.
93 GMainContext *async_context;
95 #define SOUP_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SESSION, SoupSessionPrivate))
97 static void free_host (SoupSessionHost *host);
99 static void queue_message (SoupSession *session, SoupMessage *msg,
100 SoupSessionCallback callback, gpointer user_data);
101 static void requeue_message (SoupSession *session, SoupMessage *msg);
102 static void cancel_message (SoupSession *session, SoupMessage *msg,
105 static void auth_manager_authenticate (SoupAuthManager *manager,
106 SoupMessage *msg, SoupAuth *auth,
107 gboolean retrying, gpointer user_data);
109 /* temporary until we fix this to index hosts by SoupAddress */
110 extern guint soup_uri_host_hash (gconstpointer key);
111 extern gboolean soup_uri_host_equal (gconstpointer v1,
113 extern SoupURI *soup_uri_copy_root (SoupURI *uri);
115 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
116 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 2
118 #define SOUP_SESSION_USER_AGENT_BASE "libsoup/" PACKAGE_VERSION
120 G_DEFINE_TYPE (SoupSession, soup_session, G_TYPE_OBJECT)
130 static guint signals[LAST_SIGNAL] = { 0 };
137 PROP_MAX_CONNS_PER_HOST,
145 PROP_ADD_FEATURE_BY_TYPE,
146 PROP_REMOVE_FEATURE_BY_TYPE,
151 static void set_property (GObject *object, guint prop_id,
152 const GValue *value, GParamSpec *pspec);
153 static void get_property (GObject *object, guint prop_id,
154 GValue *value, GParamSpec *pspec);
157 soup_session_init (SoupSession *session)
159 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
161 priv->queue = soup_message_queue_new ();
163 priv->host_lock = g_mutex_new ();
164 priv->hosts = g_hash_table_new (soup_uri_host_hash,
165 soup_uri_host_equal);
166 priv->conns = g_hash_table_new (NULL, NULL);
168 priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
169 priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
171 priv->auth_manager = g_object_new (SOUP_TYPE_AUTH_MANAGER_NTLM,
172 SOUP_AUTH_MANAGER_NTLM_USE_NTLM, FALSE,
174 g_signal_connect (priv->auth_manager, "authenticate",
175 G_CALLBACK (auth_manager_authenticate), session);
176 soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_BASIC);
177 soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_DIGEST);
178 soup_session_add_feature (session, SOUP_SESSION_FEATURE (priv->auth_manager));
182 foreach_free_host (gpointer key, gpointer host, gpointer data)
189 cleanup_hosts (SoupSessionPrivate *priv)
191 GHashTable *old_hosts;
193 g_mutex_lock (priv->host_lock);
194 old_hosts = priv->hosts;
195 priv->hosts = g_hash_table_new (soup_uri_host_hash,
196 soup_uri_host_equal);
197 g_mutex_unlock (priv->host_lock);
199 g_hash_table_foreach_remove (old_hosts, foreach_free_host, NULL);
200 g_hash_table_destroy (old_hosts);
204 dispose (GObject *object)
206 SoupSession *session = SOUP_SESSION (object);
207 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
209 soup_session_abort (session);
210 cleanup_hosts (priv);
212 while (priv->features)
213 soup_session_remove_feature (session, priv->features->data);
215 G_OBJECT_CLASS (soup_session_parent_class)->dispose (object);
219 finalize (GObject *object)
221 SoupSession *session = SOUP_SESSION (object);
222 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
224 soup_message_queue_destroy (priv->queue);
226 g_mutex_free (priv->host_lock);
227 g_hash_table_destroy (priv->hosts);
228 g_hash_table_destroy (priv->conns);
230 g_free (priv->user_agent);
232 if (priv->auth_manager)
233 g_object_unref (priv->auth_manager);
236 soup_uri_free (priv->proxy_uri);
239 soup_ssl_free_client_credentials (priv->ssl_creds);
241 if (priv->async_context)
242 g_main_context_unref (priv->async_context);
244 G_OBJECT_CLASS (soup_session_parent_class)->finalize (object);
248 soup_session_class_init (SoupSessionClass *session_class)
250 GObjectClass *object_class = G_OBJECT_CLASS (session_class);
252 g_type_class_add_private (session_class, sizeof (SoupSessionPrivate));
254 /* virtual method definition */
255 session_class->queue_message = queue_message;
256 session_class->requeue_message = requeue_message;
257 session_class->cancel_message = cancel_message;
259 /* virtual method override */
260 object_class->dispose = dispose;
261 object_class->finalize = finalize;
262 object_class->set_property = set_property;
263 object_class->get_property = get_property;
268 * SoupSession::request-queued:
269 * @session: the session
270 * @msg: the request that was queued
272 * Emitted when a request is queued on @session. (Note that
273 * "queued" doesn't just mean soup_session_queue_message();
274 * soup_session_send_message() implicitly queues the message
277 * When sending a request, first #SoupSession::request_queued
278 * is emitted, indicating that the session has become aware of
281 * Once a connection is available to send the request on, the
282 * session emits #SoupSession::request_started. Then, various
283 * #SoupMessage signals are emitted as the message is
284 * processed. If the message is requeued, it will emit
285 * #SoupMessage::restarted, which will then be followed by
286 * another #SoupSession::request_started and another set of
287 * #SoupMessage signals when the message is re-sent.
289 * Eventually, the message will emit #SoupMessage::finished.
290 * Normally, this signals the completion of message
291 * processing. However, it is possible that the application
292 * will requeue the message from the "finished" handler (or
293 * equivalently, from the soup_session_queue_message()
294 * callback). In that case, the process will loop back to
295 * #SoupSession::request_started.
297 * Eventually, a message will reach "finished" and not be
298 * requeued. At that point, the session will emit
299 * #SoupSession::request_unqueued to indicate that it is done
302 * To sum up: #SoupSession::request_queued and
303 * #SoupSession::request_unqueued are guaranteed to be emitted
304 * exactly once, but #SoupSession::request_started and
305 * #SoupMessage::finished (and all of the other #SoupMessage
306 * signals) may be invoked multiple times for a given message.
308 signals[REQUEST_QUEUED] =
309 g_signal_new ("request-queued",
310 G_OBJECT_CLASS_TYPE (object_class),
314 soup_marshal_NONE__OBJECT,
319 * SoupSession::request-started:
320 * @session: the session
321 * @msg: the request being sent
322 * @socket: the socket the request is being sent on
324 * Emitted just before a request is sent. See
325 * #SoupSession::request_queued for a detailed description of
326 * the message lifecycle within a session.
328 signals[REQUEST_STARTED] =
329 g_signal_new ("request-started",
330 G_OBJECT_CLASS_TYPE (object_class),
332 G_STRUCT_OFFSET (SoupSessionClass, request_started),
334 soup_marshal_NONE__OBJECT_OBJECT,
340 * SoupSession::request-unqueued:
341 * @session: the session
342 * @msg: the request that was unqueued
344 * Emitted when a request is removed from @session's queue,
345 * indicating that @session is done with it. See
346 * #SoupSession::request_queued for a detailed description of the
347 * message lifecycle within a session.
349 signals[REQUEST_UNQUEUED] =
350 g_signal_new ("request-unqueued",
351 G_OBJECT_CLASS_TYPE (object_class),
355 soup_marshal_NONE__OBJECT,
360 * SoupSession::authenticate:
361 * @session: the session
362 * @msg: the #SoupMessage being sent
363 * @auth: the #SoupAuth to authenticate
364 * @retrying: %TRUE if this is the second (or later) attempt
366 * Emitted when the session requires authentication. If
367 * credentials are available call soup_auth_authenticate() on
368 * @auth. If these credentials fail, the signal will be
369 * emitted again, with @retrying set to %TRUE, which will
370 * continue until you return without calling
371 * soup_auth_authenticate() on @auth.
373 * Note that this may be emitted before @msg's body has been
376 * If you call soup_session_pause_message() on @msg before
377 * returning, then you can authenticate @auth asynchronously
378 * (as long as you g_object_ref() it to make sure it doesn't
379 * get destroyed), and then unpause @msg when you are ready
380 * for it to continue.
382 signals[AUTHENTICATE] =
383 g_signal_new ("authenticate",
384 G_OBJECT_CLASS_TYPE (object_class),
386 G_STRUCT_OFFSET (SoupSessionClass, authenticate),
388 soup_marshal_NONE__OBJECT_OBJECT_BOOLEAN,
395 g_object_class_install_property (
396 object_class, PROP_PROXY_URI,
397 g_param_spec_boxed (SOUP_SESSION_PROXY_URI,
399 "The HTTP Proxy to use for this session",
402 g_object_class_install_property (
403 object_class, PROP_MAX_CONNS,
404 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
405 "Max Connection Count",
406 "The maximum number of connections that the session can open at once",
409 SOUP_SESSION_MAX_CONNS_DEFAULT,
411 g_object_class_install_property (
412 object_class, PROP_MAX_CONNS_PER_HOST,
413 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
414 "Max Per-Host Connection Count",
415 "The maximum number of connections that the session can open at once to a given host",
418 SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT,
420 g_object_class_install_property (
421 object_class, PROP_IDLE_TIMEOUT,
422 g_param_spec_uint (SOUP_SESSION_IDLE_TIMEOUT,
424 "Connection lifetime when idle",
427 g_object_class_install_property (
428 object_class, PROP_USE_NTLM,
429 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
431 "Whether or not to use NTLM authentication",
434 g_object_class_install_property (
435 object_class, PROP_SSL_CA_FILE,
436 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
438 "File containing SSL CA certificates",
441 g_object_class_install_property (
442 object_class, PROP_ASYNC_CONTEXT,
443 g_param_spec_pointer (SOUP_SESSION_ASYNC_CONTEXT,
444 "Async GMainContext",
445 "The GMainContext to dispatch async I/O in",
446 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
447 g_object_class_install_property (
448 object_class, PROP_TIMEOUT,
449 g_param_spec_uint (SOUP_SESSION_TIMEOUT,
451 "Value in seconds to timeout a blocking I/O",
456 * SoupSession:user-agent:
458 * If non-%NULL, the value to use for the "User-Agent" header
459 * on #SoupMessage<!-- -->s sent from this session.
461 * RFC 2616 says: "The User-Agent request-header field
462 * contains information about the user agent originating the
463 * request. This is for statistical purposes, the tracing of
464 * protocol violations, and automated recognition of user
465 * agents for the sake of tailoring responses to avoid
466 * particular user agent limitations. User agents SHOULD
467 * include this field with requests."
469 * The User-Agent header contains a list of one or more
470 * product tokens, separated by whitespace, with the most
471 * significant product token coming first. The tokens must be
472 * brief, ASCII, and mostly alphanumeric (although "-", "_",
473 * and "." are also allowed), and may optionally include a "/"
474 * followed by a version string. You may also put comments,
475 * enclosed in parentheses, between or after the tokens.
477 * If you set a %user_agent property that has trailing
478 * whitespace, #SoupSession will append its own product token
479 * (eg, "<literal>libsoup/2.3.2</literal>") to the end of the
482 g_object_class_install_property (
483 object_class, PROP_USER_AGENT,
484 g_param_spec_string (SOUP_SESSION_USER_AGENT,
490 g_object_class_install_property (
491 object_class, PROP_ADD_FEATURE,
492 g_param_spec_object (SOUP_SESSION_ADD_FEATURE,
494 "Add a feature object to the session",
495 SOUP_TYPE_SESSION_FEATURE,
497 g_object_class_install_property (
498 object_class, PROP_ADD_FEATURE_BY_TYPE,
499 g_param_spec_gtype (SOUP_SESSION_ADD_FEATURE_BY_TYPE,
500 "Add Feature By Type",
501 "Add a feature object of the given type to the session",
502 SOUP_TYPE_SESSION_FEATURE,
504 g_object_class_install_property (
505 object_class, PROP_REMOVE_FEATURE_BY_TYPE,
506 g_param_spec_gtype (SOUP_SESSION_REMOVE_FEATURE_BY_TYPE,
507 "Remove Feature By Type",
508 "Remove features of the given type from the session",
509 SOUP_TYPE_SESSION_FEATURE,
514 safe_uri_equal (SoupURI *a, SoupURI *b)
519 if ((a && !b) || (b && !a))
522 return soup_uri_equal (a, b);
526 safe_str_equal (const char *a, const char *b)
531 if ((a && !b) || (b && !a))
534 return strcmp (a, b) == 0;
538 set_property (GObject *object, guint prop_id,
539 const GValue *value, GParamSpec *pspec)
541 SoupSession *session = SOUP_SESSION (object);
542 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
544 gboolean need_abort = FALSE;
545 gboolean ca_file_changed = FALSE;
546 const char *new_ca_file, *user_agent;
550 uri = g_value_get_boxed (value);
552 if (!safe_uri_equal (priv->proxy_uri, uri))
556 soup_uri_free (priv->proxy_uri);
558 priv->proxy_uri = uri ? soup_uri_copy (uri) : NULL;
561 soup_session_abort (session);
562 cleanup_hosts (priv);
567 priv->max_conns = g_value_get_int (value);
569 case PROP_MAX_CONNS_PER_HOST:
570 priv->max_conns_per_host = g_value_get_int (value);
573 g_object_set_property (G_OBJECT (priv->auth_manager),
574 SOUP_AUTH_MANAGER_NTLM_USE_NTLM,
577 case PROP_SSL_CA_FILE:
578 new_ca_file = g_value_get_string (value);
580 if (!safe_str_equal (priv->ssl_ca_file, new_ca_file))
581 ca_file_changed = TRUE;
583 g_free (priv->ssl_ca_file);
584 priv->ssl_ca_file = g_strdup (new_ca_file);
586 if (ca_file_changed) {
587 if (priv->ssl_creds) {
588 soup_ssl_free_client_credentials (priv->ssl_creds);
589 priv->ssl_creds = NULL;
592 cleanup_hosts (priv);
596 case PROP_ASYNC_CONTEXT:
597 priv->async_context = g_value_get_pointer (value);
598 if (priv->async_context)
599 g_main_context_ref (priv->async_context);
602 priv->io_timeout = g_value_get_uint (value);
604 case PROP_USER_AGENT:
605 g_free (priv->user_agent);
606 user_agent = g_value_get_string (value);
608 priv->user_agent = NULL;
609 else if (!*user_agent) {
611 g_strdup (SOUP_SESSION_USER_AGENT_BASE);
612 } else if (g_str_has_suffix (user_agent, " ")) {
614 g_strdup_printf ("%s%s", user_agent,
615 SOUP_SESSION_USER_AGENT_BASE);
617 priv->user_agent = g_strdup (user_agent);
619 case PROP_IDLE_TIMEOUT:
620 priv->idle_timeout = g_value_get_uint (value);
622 case PROP_ADD_FEATURE:
623 soup_session_add_feature (session, g_value_get_object (value));
625 case PROP_ADD_FEATURE_BY_TYPE:
626 soup_session_add_feature_by_type (session, g_value_get_gtype (value));
628 case PROP_REMOVE_FEATURE_BY_TYPE:
629 soup_session_remove_feature_by_type (session, g_value_get_gtype (value));
632 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
638 get_property (GObject *object, guint prop_id,
639 GValue *value, GParamSpec *pspec)
641 SoupSession *session = SOUP_SESSION (object);
642 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
646 g_value_set_boxed (value, priv->proxy_uri);
649 g_value_set_int (value, priv->max_conns);
651 case PROP_MAX_CONNS_PER_HOST:
652 g_value_set_int (value, priv->max_conns_per_host);
655 g_object_get_property (G_OBJECT (priv->auth_manager),
656 SOUP_AUTH_MANAGER_NTLM_USE_NTLM,
659 case PROP_SSL_CA_FILE:
660 g_value_set_string (value, priv->ssl_ca_file);
662 case PROP_ASYNC_CONTEXT:
663 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
666 g_value_set_uint (value, priv->io_timeout);
668 case PROP_USER_AGENT:
669 g_value_set_string (value, priv->user_agent);
671 case PROP_IDLE_TIMEOUT:
672 g_value_set_uint (value, priv->idle_timeout);
675 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
682 * soup_session_get_async_context:
683 * @session: a #SoupSession
685 * Gets @session's async_context. This does not add a ref to the
686 * context, so you will need to ref it yourself if you want it to
687 * outlive its session.
689 * Return value: @session's #GMainContext, which may be %NULL
692 soup_session_get_async_context (SoupSession *session)
694 SoupSessionPrivate *priv;
696 g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
697 priv = SOUP_SESSION_GET_PRIVATE (session);
699 return priv->async_context;
704 static SoupSessionHost *
705 soup_session_host_new (SoupSession *session, SoupURI *source_uri)
707 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
708 SoupSessionHost *host;
710 host = g_slice_new0 (SoupSessionHost);
711 host->root_uri = soup_uri_copy_root (source_uri);
713 if (host->root_uri->scheme == SOUP_URI_SCHEME_HTTPS &&
716 soup_ssl_get_client_credentials (priv->ssl_ca_file);
722 /* Note: get_host_for_message doesn't lock the host_lock. The caller
723 * must do it itself if there's a chance the host doesn't already
726 static SoupSessionHost *
727 get_host_for_message (SoupSession *session, SoupMessage *msg)
729 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
730 SoupSessionHost *host;
731 SoupURI *source = soup_message_get_uri (msg);
733 host = g_hash_table_lookup (priv->hosts, source);
737 host = soup_session_host_new (session, source);
738 g_hash_table_insert (priv->hosts, host->root_uri, host);
744 free_host (SoupSessionHost *host)
746 while (host->connections) {
747 SoupConnection *conn = host->connections->data;
749 host->connections = g_slist_remove (host->connections, conn);
750 soup_connection_disconnect (conn);
753 soup_uri_free (host->root_uri);
754 g_slice_free (SoupSessionHost, host);
758 auth_manager_authenticate (SoupAuthManager *manager, SoupMessage *msg,
759 SoupAuth *auth, gboolean retrying,
762 g_signal_emit (session, signals[AUTHENTICATE], 0, msg, auth, retrying);
766 redirect_handler (SoupMessage *msg, gpointer user_data)
768 SoupSession *session = user_data;
772 new_loc = soup_message_headers_get (msg->response_headers, "Location");
773 g_return_if_fail (new_loc != NULL);
775 if (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY ||
776 msg->status_code == SOUP_STATUS_TEMPORARY_REDIRECT) {
777 /* Don't redirect non-safe methods */
778 if (msg->method != SOUP_METHOD_GET &&
779 msg->method != SOUP_METHOD_HEAD &&
780 msg->method != SOUP_METHOD_OPTIONS &&
781 msg->method != SOUP_METHOD_PROPFIND)
783 } else if (msg->status_code == SOUP_STATUS_SEE_OTHER ||
784 msg->status_code == SOUP_STATUS_FOUND) {
785 /* Redirect using a GET */
787 SOUP_MESSAGE_METHOD, SOUP_METHOD_GET,
789 soup_message_set_request (msg, NULL,
790 SOUP_MEMORY_STATIC, NULL, 0);
791 soup_message_headers_set_encoding (msg->request_headers,
794 /* Three possibilities:
796 * 1) This was a non-3xx response that happened to
797 * have a "Location" header
798 * 2) It's a non-redirecty 3xx response (300, 304,
800 * 3) It's some newly-defined 3xx response (308+)
802 * We ignore all of these cases. In the first two,
803 * redirecting would be explicitly wrong, and in the
804 * last case, we have no clue if the 3xx response is
805 * supposed to be redirecty or non-redirecty. Plus,
806 * 2616 says unrecognized status codes should be
807 * treated as the equivalent to the x00 code, and we
808 * don't redirect on 300, so therefore we shouldn't
809 * redirect on 308+ either.
814 /* Location is supposed to be an absolute URI, but some sites
815 * are lame, so we use soup_uri_new_with_base().
817 new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
818 if (!SOUP_URI_VALID_FOR_HTTP (new_uri)) {
820 soup_uri_free (new_uri);
821 soup_message_set_status_full (msg,
822 SOUP_STATUS_MALFORMED,
823 "Invalid Redirect URL");
827 soup_message_set_uri (msg, new_uri);
828 soup_uri_free (new_uri);
830 soup_session_requeue_message (session, msg);
834 connection_started_request (SoupConnection *conn, SoupMessage *msg,
837 SoupSession *session = data;
838 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
840 if (priv->user_agent) {
841 soup_message_headers_replace (msg->request_headers,
842 "User-Agent", priv->user_agent);
845 /* Kludge to deal with the fact that CONNECT msgs come from the
846 * SoupConnection rather than being queued normally.
848 if (msg->method == SOUP_METHOD_CONNECT)
849 g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
851 g_signal_emit (session, signals[REQUEST_STARTED], 0,
852 msg, soup_connection_get_socket (conn));
856 soup_session_try_prune_connection (SoupSession *session)
858 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
864 conns = g_ptr_array_new ();
866 g_mutex_lock (priv->host_lock);
867 g_hash_table_iter_init (&iter, priv->conns);
868 while (g_hash_table_iter_next (&iter, &conn, &host)) {
869 /* Don't prune a connection that is currently in use,
870 * or hasn't been used yet.
872 if (!soup_connection_is_in_use (conn) &&
873 soup_connection_last_used (conn) > 0)
874 g_ptr_array_add (conns, g_object_ref (conn));
876 g_mutex_unlock (priv->host_lock);
879 g_ptr_array_free (conns, TRUE);
883 for (i = 0; i < conns->len; i++) {
884 soup_connection_disconnect (conns->pdata[i]);
885 g_object_unref (conns->pdata[i]);
887 g_ptr_array_free (conns, TRUE);
893 connection_disconnected (SoupConnection *conn, gpointer user_data)
895 SoupSession *session = user_data;
896 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
897 SoupSessionHost *host;
899 g_mutex_lock (priv->host_lock);
901 host = g_hash_table_lookup (priv->conns, conn);
903 g_hash_table_remove (priv->conns, conn);
904 host->connections = g_slist_remove (host->connections, conn);
908 g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
911 g_mutex_unlock (priv->host_lock);
912 g_object_unref (conn);
916 connect_result (SoupConnection *conn, guint status, gpointer user_data)
918 SoupSession *session = user_data;
919 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
920 SoupSessionHost *host;
921 SoupMessageQueueIter iter;
924 g_mutex_lock (priv->host_lock);
926 host = g_hash_table_lookup (priv->conns, conn);
928 g_mutex_unlock (priv->host_lock);
932 if (status == SOUP_STATUS_OK) {
933 soup_connection_reserve (conn);
934 host->connections = g_slist_prepend (host->connections, conn);
935 g_mutex_unlock (priv->host_lock);
939 /* The connection failed. */
940 g_mutex_unlock (priv->host_lock);
941 connection_disconnected (conn, session);
943 if (host->connections) {
944 /* Something went wrong this time, but we have at
945 * least one open connection to this host. So just
946 * leave the message in the queue so it can use that
947 * connection once it's free.
952 /* There are two possibilities: either status is
953 * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
954 * will create a new connection (and all we need to do here
955 * is downgrade the message from CONNECTING to QUEUED); or
956 * status is something else, probably CANT_CONNECT or
957 * CANT_RESOLVE or the like, in which case we need to cancel
958 * any messages waiting for this host, since they're out
961 for (msg = soup_message_queue_first (priv->queue, &iter); msg; msg = soup_message_queue_next (priv->queue, &iter)) {
962 if (get_host_for_message (session, msg) == host) {
963 if (status == SOUP_STATUS_TRY_AGAIN) {
964 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING)
965 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
967 soup_session_cancel_message (session, msg,
975 * soup_session_get_connection:
976 * @session: a #SoupSession
977 * @msg: a #SoupMessage
978 * @try_pruning: on return, whether or not to try pruning a connection
979 * @is_new: on return, %TRUE if the returned connection is new and not
982 * Tries to find or create a connection for @msg; this is an internal
983 * method for #SoupSession subclasses.
985 * If there is an idle connection to the relevant host available, then
986 * that connection will be returned (with *@is_new set to %FALSE). The
987 * connection will be marked "reserved", so the caller must call
988 * soup_connection_release() if it ends up not using the connection
991 * If there is no idle connection available, but it is possible to
992 * create a new connection, then one will be created and returned,
993 * with *@is_new set to %TRUE. The caller MUST then call
994 * soup_connection_connect_sync() or soup_connection_connect_async()
995 * to connect it. If the connection attempt succeeds, the connection
996 * will be marked "reserved" and added to @session's connection pool
997 * once it connects. If the connection attempt fails, the connection
1000 * If no connection is available and a new connection cannot be made,
1001 * soup_session_get_connection() will return %NULL. If @session has
1002 * the maximum number of open connections open, but does not have the
1003 * maximum number of per-host connections open to the relevant host,
1004 * then *@try_pruning will be set to %TRUE. In this case, the caller
1005 * can call soup_session_try_prune_connection() to close an idle
1006 * connection, and then try soup_session_get_connection() again. (If
1007 * calling soup_session_try_prune_connection() wouldn't help, then
1008 * *@try_pruning is left untouched; it is NOT set to %FALSE.)
1010 * Return value: a #SoupConnection, or %NULL
1013 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
1014 gboolean *try_pruning, gboolean *is_new)
1016 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1017 SoupConnection *conn;
1018 SoupSessionHost *host;
1021 g_mutex_lock (priv->host_lock);
1023 host = get_host_for_message (session, msg);
1024 for (conns = host->connections; conns; conns = conns->next) {
1025 if (!soup_connection_is_in_use (conns->data)) {
1026 soup_connection_reserve (conns->data);
1027 g_mutex_unlock (priv->host_lock);
1033 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING) {
1034 /* We already started a connection for this
1035 * message, so don't start another one.
1037 g_mutex_unlock (priv->host_lock);
1041 if (host->num_conns >= priv->max_conns_per_host) {
1042 g_mutex_unlock (priv->host_lock);
1046 if (priv->num_conns >= priv->max_conns) {
1047 *try_pruning = TRUE;
1048 g_mutex_unlock (priv->host_lock);
1052 conn = soup_connection_new (
1053 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
1054 SOUP_CONNECTION_PROXY_URI, priv->proxy_uri,
1055 SOUP_CONNECTION_SSL_CREDENTIALS, priv->ssl_creds,
1056 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
1057 SOUP_CONNECTION_TIMEOUT, priv->io_timeout,
1058 SOUP_CONNECTION_IDLE_TIMEOUT, priv->idle_timeout,
1060 g_signal_connect (conn, "connect_result",
1061 G_CALLBACK (connect_result),
1063 g_signal_connect (conn, "disconnected",
1064 G_CALLBACK (connection_disconnected),
1066 g_signal_connect (conn, "request_started",
1067 G_CALLBACK (connection_started_request),
1070 g_hash_table_insert (priv->conns, conn, host);
1072 /* We increment the connection counts so it counts against the
1073 * totals, but we don't add it to the host's connection list
1074 * yet, since it's not ready for use.
1079 /* Mark the request as connecting, so we don't try to open
1080 * another new connection for it while waiting for this one.
1082 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_CONNECTING);
1084 g_mutex_unlock (priv->host_lock);
1090 soup_session_get_queue (SoupSession *session)
1092 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1098 message_finished (SoupMessage *msg, gpointer user_data)
1100 SoupSession *session = user_data;
1101 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1103 if (!SOUP_MESSAGE_IS_STARTING (msg)) {
1104 soup_message_queue_remove_message (priv->queue, msg);
1105 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
1106 g_signal_handlers_disconnect_by_func (msg, redirect_handler, session);
1107 g_signal_emit (session, signals[REQUEST_UNQUEUED], 0, msg);
1112 queue_message (SoupSession *session, SoupMessage *msg,
1113 SoupSessionCallback callback, gpointer user_data)
1115 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1117 g_signal_connect_after (msg, "finished",
1118 G_CALLBACK (message_finished), session);
1120 if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
1121 soup_message_add_header_handler (
1122 msg, "got_body", "Location",
1123 G_CALLBACK (redirect_handler), session);
1126 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1127 soup_message_queue_append (priv->queue, msg);
1129 g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
1133 * SoupSessionCallback:
1134 * @session: the session
1135 * @msg: the message that has finished
1136 * @user_data: the data passed to soup_session_queue_message
1138 * Prototype for the callback passed to soup_session_queue_message(),
1143 * soup_session_queue_message:
1144 * @session: a #SoupSession
1145 * @msg: the message to queue
1146 * @callback: a #SoupSessionCallback which will be called after the
1147 * message completes or when an unrecoverable error occurs.
1148 * @user_data: a pointer passed to @callback.
1150 * Queues the message @msg for sending. All messages are processed
1151 * while the glib main loop runs. If @msg has been processed before,
1152 * any resources related to the time it was last sent are freed.
1154 * Upon message completion, the callback specified in @callback will
1155 * be invoked (in the thread associated with @session's async
1156 * context). If after returning from this callback the message has not
1157 * been requeued, @msg will be unreffed.
1160 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1161 SoupSessionCallback callback, gpointer user_data)
1163 g_return_if_fail (SOUP_IS_SESSION (session));
1164 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1166 SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1167 callback, user_data);
1171 requeue_message (SoupSession *session, SoupMessage *msg)
1173 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1177 * soup_session_requeue_message:
1178 * @session: a #SoupSession
1179 * @msg: the message to requeue
1181 * This causes @msg to be placed back on the queue to be attempted
1185 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
1187 g_return_if_fail (SOUP_IS_SESSION (session));
1188 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1190 SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
1195 * soup_session_send_message:
1196 * @session: a #SoupSession
1197 * @msg: the message to send
1199 * Synchronously send @msg. This call will not return until the
1200 * transfer is finished successfully or there is an unrecoverable
1203 * @msg is not freed upon return.
1205 * Return value: the HTTP status code of the response
1208 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1210 g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1211 g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1213 return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1218 * soup_session_pause_message:
1219 * @session: a #SoupSession
1220 * @msg: a #SoupMessage currently running on @session
1222 * Pauses HTTP I/O on @msg. Call soup_session_unpause_message() to
1226 soup_session_pause_message (SoupSession *session,
1229 g_return_if_fail (SOUP_IS_SESSION (session));
1230 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1232 soup_message_io_pause (msg);
1236 * soup_session_unpause_message:
1237 * @session: a #SoupSession
1238 * @msg: a #SoupMessage currently running on @session
1240 * Resumes HTTP I/O on @msg. Use this to resume after calling
1241 * soup_sessino_pause_message().
1243 * If @msg is being sent via blocking I/O, this will resume reading or
1244 * writing immediately. If @msg is using non-blocking I/O, then
1245 * reading or writing won't resume until you return to the main loop.
1248 soup_session_unpause_message (SoupSession *session,
1251 g_return_if_fail (SOUP_IS_SESSION (session));
1252 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1254 soup_message_io_unpause (msg);
1259 cancel_message (SoupSession *session, SoupMessage *msg, guint status_code)
1261 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1263 soup_message_queue_remove_message (priv->queue, msg);
1264 soup_message_io_stop (msg);
1265 soup_message_set_status (msg, status_code);
1266 soup_message_finished (msg);
1270 * soup_session_cancel_message:
1271 * @session: a #SoupSession
1272 * @msg: the message to cancel
1273 * @status_code: status code to set on @msg (generally
1274 * %SOUP_STATUS_CANCELLED)
1276 * Causes @session to immediately finish processing @msg, with a final
1277 * status_code of @status_code. Depending on when you cancel it, the
1278 * response state may be incomplete or inconsistent.
1281 soup_session_cancel_message (SoupSession *session, SoupMessage *msg,
1284 g_return_if_fail (SOUP_IS_SESSION (session));
1285 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1287 SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg, status_code);
1291 gather_conns (gpointer key, gpointer host, gpointer data)
1293 SoupConnection *conn = key;
1294 GSList **conns = data;
1296 *conns = g_slist_prepend (*conns, conn);
1300 * soup_session_abort:
1301 * @session: the session
1303 * Cancels all pending requests in @session.
1306 soup_session_abort (SoupSession *session)
1308 SoupSessionPrivate *priv;
1309 SoupMessageQueueIter iter;
1313 g_return_if_fail (SOUP_IS_SESSION (session));
1314 priv = SOUP_SESSION_GET_PRIVATE (session);
1316 for (msg = soup_message_queue_first (priv->queue, &iter);
1318 msg = soup_message_queue_next (priv->queue, &iter)) {
1319 soup_session_cancel_message (session, msg,
1320 SOUP_STATUS_CANCELLED);
1323 /* Close all connections */
1324 g_mutex_lock (priv->host_lock);
1326 g_hash_table_foreach (priv->conns, gather_conns, &conns);
1328 for (c = conns; c; c = c->next)
1329 g_object_ref (c->data);
1330 g_mutex_unlock (priv->host_lock);
1331 for (c = conns; c; c = c->next) {
1332 soup_connection_disconnect (c->data);
1333 g_object_unref (c->data);
1336 g_slist_free (conns);
1340 soup_session_add_feature (SoupSession *session, SoupSessionFeature *feature)
1342 SoupSessionPrivate *priv;
1344 g_return_if_fail (SOUP_IS_SESSION (session));
1345 g_return_if_fail (SOUP_IS_SESSION_FEATURE (feature));
1347 priv = SOUP_SESSION_GET_PRIVATE (session);
1348 priv->features = g_slist_prepend (priv->features, g_object_ref (feature));
1349 soup_session_feature_attach (feature, session);
1353 soup_session_add_feature_by_type (SoupSession *session, GType feature_type)
1355 SoupSessionFeature *feature;
1357 g_return_if_fail (SOUP_IS_SESSION (session));
1358 g_return_if_fail (g_type_is_a (feature_type, SOUP_TYPE_SESSION_FEATURE));
1360 feature = g_object_new (feature_type, NULL);
1361 soup_session_add_feature (session, feature);
1362 g_object_unref (feature);
1366 soup_session_remove_feature (SoupSession *session, SoupSessionFeature *feature)
1368 SoupSessionPrivate *priv;
1370 g_return_if_fail (SOUP_IS_SESSION (session));
1372 priv = SOUP_SESSION_GET_PRIVATE (session);
1373 if (g_slist_find (priv->features, feature)) {
1374 priv->features = g_slist_remove (priv->features, feature);
1375 soup_session_feature_detach (feature, session);
1376 g_object_unref (feature);
1381 soup_session_remove_feature_by_type (SoupSession *session, GType feature_type)
1383 SoupSessionPrivate *priv;
1386 g_return_if_fail (SOUP_IS_SESSION (session));
1388 priv = SOUP_SESSION_GET_PRIVATE (session);
1390 for (f = priv->features; f; f = f->next) {
1391 if (G_TYPE_CHECK_INSTANCE_TYPE (f->data, feature_type)) {
1392 soup_session_remove_feature (session, f->data);