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.h"
20 #include "soup-auth-manager-ntlm.h"
21 #include "soup-connection.h"
22 #include "soup-marshal.h"
23 #include "soup-message-private.h"
24 #include "soup-message-queue.h"
25 #include "soup-session.h"
26 #include "soup-session-feature.h"
27 #include "soup-session-private.h"
28 #include "soup-socket.h"
33 * SECTION:soup-session
34 * @short_description: Soup session state object
36 * #SoupSession is the object that controls client-side HTTP. A
37 * #SoupSession encapsulates all of the state that libsoup is keeping
38 * on behalf of your program; cached HTTP connections, authentication
41 * Most applications will only need a single #SoupSession; the primary
42 * reason you might need multiple sessions is if you need to have
43 * multiple independent authentication contexts. (Eg, you are
44 * connecting to a server and authenticating as two different users at
45 * different times; the easiest way to ensure that each #SoupMessage
46 * is sent with the authentication information you intended is to use
47 * one session for the first user, and a second session for the other
50 * #SoupSession itself is an abstract class, with two subclasses. If
51 * you are using the glib main loop, you will generally want to use
52 * #SoupSessionAsync, which uses non-blocking I/O and callbacks. On
53 * the other hand, if your application is threaded and you want to do
54 * synchronous I/O in a separate thread from the UI, use
61 GSList *connections; /* CONTAINS: SoupConnection */
64 GHashTable *auth_realms; /* path -> scheme:realm */
65 GHashTable *auths; /* scheme:realm -> SoupAuth */
73 SoupSSLCredentials *ssl_creds;
75 SoupMessageQueue *queue;
80 SoupAuthManager *auth_manager;
81 SoupAuthManagerNTLM *ntlm_manager;
83 GHashTable *hosts; /* SoupURI -> SoupSessionHost */
84 GHashTable *conns; /* SoupConnection -> SoupSessionHost */
86 guint max_conns, max_conns_per_host;
87 guint io_timeout, idle_timeout;
89 /* Must hold the host_lock before potentially creating a
90 * new SoupSessionHost, or adding/removing a connection.
91 * Must not emit signals or destroy objects while holding it.
95 GMainContext *async_context;
97 #define SOUP_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SESSION, SoupSessionPrivate))
99 static void free_host (SoupSessionHost *host);
101 static void queue_message (SoupSession *session, SoupMessage *msg,
102 SoupSessionCallback callback, gpointer user_data);
103 static void requeue_message (SoupSession *session, SoupMessage *msg);
104 static void cancel_message (SoupSession *session, SoupMessage *msg,
107 /* temporary until we fix this to index hosts by SoupAddress */
108 extern guint soup_uri_host_hash (gconstpointer key);
109 extern gboolean soup_uri_host_equal (gconstpointer v1,
111 extern SoupURI *soup_uri_copy_root (SoupURI *uri);
113 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
114 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 2
116 #define SOUP_SESSION_USER_AGENT_BASE "libsoup/" PACKAGE_VERSION
118 G_DEFINE_TYPE (SoupSession, soup_session, G_TYPE_OBJECT)
128 static guint signals[LAST_SIGNAL] = { 0 };
135 PROP_MAX_CONNS_PER_HOST,
143 PROP_ADD_FEATURE_BY_TYPE,
144 PROP_REMOVE_FEATURE_BY_TYPE,
149 static void set_property (GObject *object, guint prop_id,
150 const GValue *value, GParamSpec *pspec);
151 static void get_property (GObject *object, guint prop_id,
152 GValue *value, GParamSpec *pspec);
155 soup_session_init (SoupSession *session)
157 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
159 priv->queue = soup_message_queue_new ();
161 priv->host_lock = g_mutex_new ();
162 priv->hosts = g_hash_table_new (soup_uri_host_hash,
163 soup_uri_host_equal);
164 priv->conns = g_hash_table_new (NULL, NULL);
166 priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
167 priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
169 priv->auth_manager = soup_auth_manager_new (session);
170 soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_BASIC);
171 soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_DIGEST);
175 foreach_free_host (gpointer key, gpointer host, gpointer data)
182 cleanup_hosts (SoupSessionPrivate *priv)
184 GHashTable *old_hosts;
186 g_mutex_lock (priv->host_lock);
187 old_hosts = priv->hosts;
188 priv->hosts = g_hash_table_new (soup_uri_host_hash,
189 soup_uri_host_equal);
190 g_mutex_unlock (priv->host_lock);
192 g_hash_table_foreach_remove (old_hosts, foreach_free_host, NULL);
193 g_hash_table_destroy (old_hosts);
197 dispose (GObject *object)
199 SoupSession *session = SOUP_SESSION (object);
200 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
202 soup_session_abort (session);
203 cleanup_hosts (priv);
205 while (priv->features)
206 soup_session_remove_feature (session, priv->features->data);
208 G_OBJECT_CLASS (soup_session_parent_class)->dispose (object);
212 finalize (GObject *object)
214 SoupSession *session = SOUP_SESSION (object);
215 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
217 soup_message_queue_destroy (priv->queue);
219 g_mutex_free (priv->host_lock);
220 g_hash_table_destroy (priv->hosts);
221 g_hash_table_destroy (priv->conns);
223 g_free (priv->user_agent);
225 soup_auth_manager_free (priv->auth_manager);
226 if (priv->ntlm_manager)
227 soup_auth_manager_ntlm_free (priv->ntlm_manager);
230 soup_uri_free (priv->proxy_uri);
233 soup_ssl_free_client_credentials (priv->ssl_creds);
235 if (priv->async_context)
236 g_main_context_unref (priv->async_context);
238 G_OBJECT_CLASS (soup_session_parent_class)->finalize (object);
242 soup_session_class_init (SoupSessionClass *session_class)
244 GObjectClass *object_class = G_OBJECT_CLASS (session_class);
246 g_type_class_add_private (session_class, sizeof (SoupSessionPrivate));
248 /* virtual method definition */
249 session_class->queue_message = queue_message;
250 session_class->requeue_message = requeue_message;
251 session_class->cancel_message = cancel_message;
253 /* virtual method override */
254 object_class->dispose = dispose;
255 object_class->finalize = finalize;
256 object_class->set_property = set_property;
257 object_class->get_property = get_property;
262 * SoupSession::request-queued:
263 * @session: the session
264 * @msg: the request that was queued
266 * Emitted when a request is queued on @session. (Note that
267 * "queued" doesn't just mean soup_session_queue_message();
268 * soup_session_send_message() implicitly queues the message
271 * When sending a request, first #SoupSession::request_queued
272 * is emitted, indicating that the session has become aware of
275 * Once a connection is available to send the request on, the
276 * session emits #SoupSession::request_started. Then, various
277 * #SoupMessage signals are emitted as the message is
278 * processed. If the message is requeued, it will emit
279 * #SoupMessage::restarted, which will then be followed by
280 * another #SoupSession::request_started and another set of
281 * #SoupMessage signals when the message is re-sent.
283 * Eventually, the message will emit #SoupMessage::finished.
284 * Normally, this signals the completion of message
285 * processing. However, it is possible that the application
286 * will requeue the message from the "finished" handler (or
287 * equivalently, from the soup_session_queue_message()
288 * callback). In that case, the process will loop back to
289 * #SoupSession::request_started.
291 * Eventually, a message will reach "finished" and not be
292 * requeued. At that point, the session will emit
293 * #SoupSession::request_unqueued to indicate that it is done
296 * To sum up: #SoupSession::request_queued and
297 * #SoupSession::request_unqueued are guaranteed to be emitted
298 * exactly once, but #SoupSession::request_started and
299 * #SoupMessage::finished (and all of the other #SoupMessage
300 * signals) may be invoked multiple times for a given message.
302 signals[REQUEST_QUEUED] =
303 g_signal_new ("request-queued",
304 G_OBJECT_CLASS_TYPE (object_class),
308 soup_marshal_NONE__OBJECT,
313 * SoupSession::request-started:
314 * @session: the session
315 * @msg: the request being sent
316 * @socket: the socket the request is being sent on
318 * Emitted just before a request is sent. See
319 * #SoupSession::request_queued for a detailed description of
320 * the message lifecycle within a session.
322 signals[REQUEST_STARTED] =
323 g_signal_new ("request-started",
324 G_OBJECT_CLASS_TYPE (object_class),
326 G_STRUCT_OFFSET (SoupSessionClass, request_started),
328 soup_marshal_NONE__OBJECT_OBJECT,
334 * SoupSession::request-unqueued:
335 * @session: the session
336 * @msg: the request that was unqueued
338 * Emitted when a request is removed from @session's queue,
339 * indicating that @session is done with it. See
340 * #SoupSession::request_queued for a detailed description of the
341 * message lifecycle within a session.
343 signals[REQUEST_UNQUEUED] =
344 g_signal_new ("request-unqueued",
345 G_OBJECT_CLASS_TYPE (object_class),
349 soup_marshal_NONE__OBJECT,
354 * SoupSession::authenticate:
355 * @session: the session
356 * @msg: the #SoupMessage being sent
357 * @auth: the #SoupAuth to authenticate
358 * @retrying: %TRUE if this is the second (or later) attempt
360 * Emitted when the session requires authentication. If
361 * credentials are available call soup_auth_authenticate() on
362 * @auth. If these credentials fail, the signal will be
363 * emitted again, with @retrying set to %TRUE, which will
364 * continue until you return without calling
365 * soup_auth_authenticate() on @auth.
367 * Note that this may be emitted before @msg's body has been
370 * If you call soup_session_pause_message() on @msg before
371 * returning, then you can authenticate @auth asynchronously
372 * (as long as you g_object_ref() it to make sure it doesn't
373 * get destroyed), and then unpause @msg when you are ready
374 * for it to continue.
376 signals[AUTHENTICATE] =
377 g_signal_new ("authenticate",
378 G_OBJECT_CLASS_TYPE (object_class),
380 G_STRUCT_OFFSET (SoupSessionClass, authenticate),
382 soup_marshal_NONE__OBJECT_OBJECT_BOOLEAN,
389 g_object_class_install_property (
390 object_class, PROP_PROXY_URI,
391 g_param_spec_boxed (SOUP_SESSION_PROXY_URI,
393 "The HTTP Proxy to use for this session",
396 g_object_class_install_property (
397 object_class, PROP_MAX_CONNS,
398 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
399 "Max Connection Count",
400 "The maximum number of connections that the session can open at once",
403 SOUP_SESSION_MAX_CONNS_DEFAULT,
405 g_object_class_install_property (
406 object_class, PROP_MAX_CONNS_PER_HOST,
407 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
408 "Max Per-Host Connection Count",
409 "The maximum number of connections that the session can open at once to a given host",
412 SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT,
414 g_object_class_install_property (
415 object_class, PROP_IDLE_TIMEOUT,
416 g_param_spec_uint (SOUP_SESSION_IDLE_TIMEOUT,
418 "Connection lifetime when idle",
421 g_object_class_install_property (
422 object_class, PROP_USE_NTLM,
423 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
425 "Whether or not to use NTLM authentication",
428 g_object_class_install_property (
429 object_class, PROP_SSL_CA_FILE,
430 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
432 "File containing SSL CA certificates",
435 g_object_class_install_property (
436 object_class, PROP_ASYNC_CONTEXT,
437 g_param_spec_pointer (SOUP_SESSION_ASYNC_CONTEXT,
438 "Async GMainContext",
439 "The GMainContext to dispatch async I/O in",
440 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
441 g_object_class_install_property (
442 object_class, PROP_TIMEOUT,
443 g_param_spec_uint (SOUP_SESSION_TIMEOUT,
445 "Value in seconds to timeout a blocking I/O",
450 * SoupSession:user-agent:
452 * If non-%NULL, the value to use for the "User-Agent" header
453 * on #SoupMessage<!-- -->s sent from this session.
455 * RFC 2616 says: "The User-Agent request-header field
456 * contains information about the user agent originating the
457 * request. This is for statistical purposes, the tracing of
458 * protocol violations, and automated recognition of user
459 * agents for the sake of tailoring responses to avoid
460 * particular user agent limitations. User agents SHOULD
461 * include this field with requests."
463 * The User-Agent header contains a list of one or more
464 * product tokens, separated by whitespace, with the most
465 * significant product token coming first. The tokens must be
466 * brief, ASCII, and mostly alphanumeric (although "-", "_",
467 * and "." are also allowed), and may optionally include a "/"
468 * followed by a version string. You may also put comments,
469 * enclosed in parentheses, between or after the tokens.
471 * If you set a %user_agent property that has trailing
472 * whitespace, #SoupSession will append its own product token
473 * (eg, "<literal>libsoup/2.3.2</literal>") to the end of the
476 g_object_class_install_property (
477 object_class, PROP_USER_AGENT,
478 g_param_spec_string (SOUP_SESSION_USER_AGENT,
484 g_object_class_install_property (
485 object_class, PROP_ADD_FEATURE,
486 g_param_spec_object (SOUP_SESSION_ADD_FEATURE,
488 "Add a feature object to the session",
489 SOUP_TYPE_SESSION_FEATURE,
491 g_object_class_install_property (
492 object_class, PROP_ADD_FEATURE_BY_TYPE,
493 g_param_spec_gtype (SOUP_SESSION_ADD_FEATURE_BY_TYPE,
494 "Add Feature By Type",
495 "Add a feature object of the given type to the session",
496 SOUP_TYPE_SESSION_FEATURE,
498 g_object_class_install_property (
499 object_class, PROP_REMOVE_FEATURE_BY_TYPE,
500 g_param_spec_gtype (SOUP_SESSION_REMOVE_FEATURE_BY_TYPE,
501 "Remove Feature By Type",
502 "Remove features of the given type from the session",
503 SOUP_TYPE_SESSION_FEATURE,
508 safe_uri_equal (SoupURI *a, SoupURI *b)
513 if ((a && !b) || (b && !a))
516 return soup_uri_equal (a, b);
520 safe_str_equal (const char *a, const char *b)
525 if ((a && !b) || (b && !a))
528 return strcmp (a, b) == 0;
532 set_property (GObject *object, guint prop_id,
533 const GValue *value, GParamSpec *pspec)
535 SoupSession *session = SOUP_SESSION (object);
536 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
538 gboolean need_abort = FALSE;
539 gboolean ca_file_changed = FALSE;
540 const char *new_ca_file, *user_agent;
544 uri = g_value_get_boxed (value);
546 if (!safe_uri_equal (priv->proxy_uri, uri))
550 soup_uri_free (priv->proxy_uri);
552 priv->proxy_uri = uri ? soup_uri_copy (uri) : NULL;
555 soup_session_abort (session);
556 cleanup_hosts (priv);
561 priv->max_conns = g_value_get_int (value);
563 case PROP_MAX_CONNS_PER_HOST:
564 priv->max_conns_per_host = g_value_get_int (value);
567 if (g_value_get_boolean (value)) {
568 if (!priv->ntlm_manager)
569 priv->ntlm_manager = soup_auth_manager_ntlm_new (session);
571 if (priv->ntlm_manager) {
572 soup_auth_manager_ntlm_free (priv->ntlm_manager);
573 priv->ntlm_manager = NULL;
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_value_set_boolean (value, priv->ntlm_manager != NULL);
657 case PROP_SSL_CA_FILE:
658 g_value_set_string (value, priv->ssl_ca_file);
660 case PROP_ASYNC_CONTEXT:
661 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
664 g_value_set_uint (value, priv->io_timeout);
666 case PROP_USER_AGENT:
667 g_value_set_string (value, priv->user_agent);
669 case PROP_IDLE_TIMEOUT:
670 g_value_set_uint (value, priv->idle_timeout);
673 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
680 * soup_session_get_async_context:
681 * @session: a #SoupSession
683 * Gets @session's async_context. This does not add a ref to the
684 * context, so you will need to ref it yourself if you want it to
685 * outlive its session.
687 * Return value: @session's #GMainContext, which may be %NULL
690 soup_session_get_async_context (SoupSession *session)
692 SoupSessionPrivate *priv;
694 g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
695 priv = SOUP_SESSION_GET_PRIVATE (session);
697 return priv->async_context;
702 static SoupSessionHost *
703 soup_session_host_new (SoupSession *session, SoupURI *source_uri)
705 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
706 SoupSessionHost *host;
708 host = g_slice_new0 (SoupSessionHost);
709 host->root_uri = soup_uri_copy_root (source_uri);
711 if (host->root_uri->scheme == SOUP_URI_SCHEME_HTTPS &&
714 soup_ssl_get_client_credentials (priv->ssl_ca_file);
720 /* Note: get_host_for_message doesn't lock the host_lock. The caller
721 * must do it itself if there's a chance the host doesn't already
724 static SoupSessionHost *
725 get_host_for_message (SoupSession *session, SoupMessage *msg)
727 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
728 SoupSessionHost *host;
729 SoupURI *source = soup_message_get_uri (msg);
731 host = g_hash_table_lookup (priv->hosts, source);
735 host = soup_session_host_new (session, source);
736 g_hash_table_insert (priv->hosts, host->root_uri, host);
742 free_host (SoupSessionHost *host)
744 while (host->connections) {
745 SoupConnection *conn = host->connections->data;
747 host->connections = g_slist_remove (host->connections, conn);
748 soup_connection_disconnect (conn);
751 soup_uri_free (host->root_uri);
752 g_slice_free (SoupSessionHost, host);
756 soup_session_emit_authenticate (SoupSession *session, SoupMessage *msg,
757 SoupAuth *auth, gboolean retrying)
759 g_signal_emit (session, signals[AUTHENTICATE], 0, msg, auth, retrying);
763 redirect_handler (SoupMessage *msg, gpointer user_data)
765 SoupSession *session = user_data;
769 new_loc = soup_message_headers_get (msg->response_headers, "Location");
770 g_return_if_fail (new_loc != NULL);
772 if (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY ||
773 msg->status_code == SOUP_STATUS_TEMPORARY_REDIRECT) {
774 /* Don't redirect non-safe methods */
775 if (msg->method != SOUP_METHOD_GET &&
776 msg->method != SOUP_METHOD_HEAD &&
777 msg->method != SOUP_METHOD_OPTIONS &&
778 msg->method != SOUP_METHOD_PROPFIND)
780 } else if (msg->status_code == SOUP_STATUS_SEE_OTHER ||
781 msg->status_code == SOUP_STATUS_FOUND) {
782 /* Redirect using a GET */
784 SOUP_MESSAGE_METHOD, SOUP_METHOD_GET,
786 soup_message_set_request (msg, NULL,
787 SOUP_MEMORY_STATIC, NULL, 0);
788 soup_message_headers_set_encoding (msg->request_headers,
791 /* Three possibilities:
793 * 1) This was a non-3xx response that happened to
794 * have a "Location" header
795 * 2) It's a non-redirecty 3xx response (300, 304,
797 * 3) It's some newly-defined 3xx response (308+)
799 * We ignore all of these cases. In the first two,
800 * redirecting would be explicitly wrong, and in the
801 * last case, we have no clue if the 3xx response is
802 * supposed to be redirecty or non-redirecty. Plus,
803 * 2616 says unrecognized status codes should be
804 * treated as the equivalent to the x00 code, and we
805 * don't redirect on 300, so therefore we shouldn't
806 * redirect on 308+ either.
811 /* Location is supposed to be an absolute URI, but some sites
812 * are lame, so we use soup_uri_new_with_base().
814 new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
816 soup_message_set_status_full (msg,
817 SOUP_STATUS_MALFORMED,
818 "Invalid Redirect URL");
822 soup_message_set_uri (msg, new_uri);
823 soup_uri_free (new_uri);
825 soup_session_requeue_message (session, msg);
829 connection_started_request (SoupConnection *conn, SoupMessage *msg,
832 SoupSession *session = data;
833 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
835 if (priv->user_agent) {
836 soup_message_headers_replace (msg->request_headers,
837 "User-Agent", priv->user_agent);
840 /* Kludge to deal with the fact that CONNECT msgs come from the
841 * SoupConnection rather than being queued normally.
843 if (msg->method == SOUP_METHOD_CONNECT)
844 g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
846 g_signal_emit (session, signals[REQUEST_STARTED], 0,
847 msg, soup_connection_get_socket (conn));
851 soup_session_try_prune_connection (SoupSession *session)
853 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
859 conns = g_ptr_array_new ();
861 g_mutex_lock (priv->host_lock);
862 g_hash_table_iter_init (&iter, priv->conns);
863 while (g_hash_table_iter_next (&iter, &conn, &host)) {
864 /* Don't prune a connection that is currently in use,
865 * or hasn't been used yet.
867 if (!soup_connection_is_in_use (conn) &&
868 soup_connection_last_used (conn) > 0)
869 g_ptr_array_add (conns, g_object_ref (conn));
871 g_mutex_unlock (priv->host_lock);
874 g_ptr_array_free (conns, TRUE);
878 for (i = 0; i < conns->len; i++) {
879 soup_connection_disconnect (conns->pdata[i]);
880 g_object_unref (conns->pdata[i]);
882 g_ptr_array_free (conns, TRUE);
888 connection_disconnected (SoupConnection *conn, gpointer user_data)
890 SoupSession *session = user_data;
891 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
892 SoupSessionHost *host;
894 g_mutex_lock (priv->host_lock);
896 host = g_hash_table_lookup (priv->conns, conn);
898 g_hash_table_remove (priv->conns, conn);
899 host->connections = g_slist_remove (host->connections, conn);
903 g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
906 g_mutex_unlock (priv->host_lock);
907 g_object_unref (conn);
911 connect_result (SoupConnection *conn, guint status, gpointer user_data)
913 SoupSession *session = user_data;
914 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
915 SoupSessionHost *host;
916 SoupMessageQueueIter iter;
919 g_mutex_lock (priv->host_lock);
921 host = g_hash_table_lookup (priv->conns, conn);
923 g_mutex_unlock (priv->host_lock);
927 if (status == SOUP_STATUS_OK) {
928 soup_connection_reserve (conn);
929 host->connections = g_slist_prepend (host->connections, conn);
930 g_mutex_unlock (priv->host_lock);
934 /* The connection failed. */
935 g_mutex_unlock (priv->host_lock);
936 connection_disconnected (conn, session);
938 if (host->connections) {
939 /* Something went wrong this time, but we have at
940 * least one open connection to this host. So just
941 * leave the message in the queue so it can use that
942 * connection once it's free.
947 /* There are two possibilities: either status is
948 * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
949 * will create a new connection (and all we need to do here
950 * is downgrade the message from CONNECTING to QUEUED); or
951 * status is something else, probably CANT_CONNECT or
952 * CANT_RESOLVE or the like, in which case we need to cancel
953 * any messages waiting for this host, since they're out
956 for (msg = soup_message_queue_first (priv->queue, &iter); msg; msg = soup_message_queue_next (priv->queue, &iter)) {
957 if (get_host_for_message (session, msg) == host) {
958 if (status == SOUP_STATUS_TRY_AGAIN) {
959 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING)
960 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
962 soup_session_cancel_message (session, msg,
970 * soup_session_get_connection:
971 * @session: a #SoupSession
972 * @msg: a #SoupMessage
973 * @try_pruning: on return, whether or not to try pruning a connection
974 * @is_new: on return, %TRUE if the returned connection is new and not
977 * Tries to find or create a connection for @msg; this is an internal
978 * method for #SoupSession subclasses.
980 * If there is an idle connection to the relevant host available, then
981 * that connection will be returned (with *@is_new set to %FALSE). The
982 * connection will be marked "reserved", so the caller must call
983 * soup_connection_release() if it ends up not using the connection
986 * If there is no idle connection available, but it is possible to
987 * create a new connection, then one will be created and returned,
988 * with *@is_new set to %TRUE. The caller MUST then call
989 * soup_connection_connect_sync() or soup_connection_connect_async()
990 * to connect it. If the connection attempt succeeds, the connection
991 * will be marked "reserved" and added to @session's connection pool
992 * once it connects. If the connection attempt fails, the connection
995 * If no connection is available and a new connection cannot be made,
996 * soup_session_get_connection() will return %NULL. If @session has
997 * the maximum number of open connections open, but does not have the
998 * maximum number of per-host connections open to the relevant host,
999 * then *@try_pruning will be set to %TRUE. In this case, the caller
1000 * can call soup_session_try_prune_connection() to close an idle
1001 * connection, and then try soup_session_get_connection() again. (If
1002 * calling soup_session_try_prune_connection() wouldn't help, then
1003 * *@try_pruning is left untouched; it is NOT set to %FALSE.)
1005 * Return value: a #SoupConnection, or %NULL
1008 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
1009 gboolean *try_pruning, gboolean *is_new)
1011 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1012 SoupConnection *conn;
1013 SoupSessionHost *host;
1016 g_mutex_lock (priv->host_lock);
1018 host = get_host_for_message (session, msg);
1019 for (conns = host->connections; conns; conns = conns->next) {
1020 if (!soup_connection_is_in_use (conns->data)) {
1021 soup_connection_reserve (conns->data);
1022 g_mutex_unlock (priv->host_lock);
1028 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING) {
1029 /* We already started a connection for this
1030 * message, so don't start another one.
1032 g_mutex_unlock (priv->host_lock);
1036 if (host->num_conns >= priv->max_conns_per_host) {
1037 g_mutex_unlock (priv->host_lock);
1041 if (priv->num_conns >= priv->max_conns) {
1042 *try_pruning = TRUE;
1043 g_mutex_unlock (priv->host_lock);
1047 conn = soup_connection_new (
1048 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
1049 SOUP_CONNECTION_PROXY_URI, priv->proxy_uri,
1050 SOUP_CONNECTION_SSL_CREDENTIALS, priv->ssl_creds,
1051 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
1052 SOUP_CONNECTION_TIMEOUT, priv->io_timeout,
1053 SOUP_CONNECTION_IDLE_TIMEOUT, priv->idle_timeout,
1055 g_signal_connect (conn, "connect_result",
1056 G_CALLBACK (connect_result),
1058 g_signal_connect (conn, "disconnected",
1059 G_CALLBACK (connection_disconnected),
1061 g_signal_connect (conn, "request_started",
1062 G_CALLBACK (connection_started_request),
1065 g_hash_table_insert (priv->conns, conn, host);
1067 /* We increment the connection counts so it counts against the
1068 * totals, but we don't add it to the host's connection list
1069 * yet, since it's not ready for use.
1074 /* Mark the request as connecting, so we don't try to open
1075 * another new connection for it while waiting for this one.
1077 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_CONNECTING);
1079 g_mutex_unlock (priv->host_lock);
1085 soup_session_get_queue (SoupSession *session)
1087 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1093 message_finished (SoupMessage *msg, gpointer user_data)
1095 SoupSession *session = user_data;
1096 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1098 if (!SOUP_MESSAGE_IS_STARTING (msg)) {
1099 soup_message_queue_remove_message (priv->queue, msg);
1100 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
1101 g_signal_handlers_disconnect_by_func (msg, redirect_handler, session);
1102 g_signal_emit (session, signals[REQUEST_UNQUEUED], 0, msg);
1107 queue_message (SoupSession *session, SoupMessage *msg,
1108 SoupSessionCallback callback, gpointer user_data)
1110 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1112 g_signal_connect_after (msg, "finished",
1113 G_CALLBACK (message_finished), session);
1115 if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
1116 soup_message_add_header_handler (
1117 msg, "got_body", "Location",
1118 G_CALLBACK (redirect_handler), session);
1121 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1122 soup_message_queue_append (priv->queue, msg);
1124 g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
1128 * SoupSessionCallback:
1129 * @session: the session
1130 * @msg: the message that has finished
1131 * @user_data: the data passed to soup_session_queue_message
1133 * Prototype for the callback passed to soup_session_queue_message(),
1138 * soup_session_queue_message:
1139 * @session: a #SoupSession
1140 * @msg: the message to queue
1141 * @callback: a #SoupSessionCallback which will be called after the
1142 * message completes or when an unrecoverable error occurs.
1143 * @user_data: a pointer passed to @callback.
1145 * Queues the message @msg for sending. All messages are processed
1146 * while the glib main loop runs. If @msg has been processed before,
1147 * any resources related to the time it was last sent are freed.
1149 * Upon message completion, the callback specified in @callback will
1150 * be invoked (in the thread associated with @session's async
1151 * context). If after returning from this callback the message has not
1152 * been requeued, @msg will be unreffed.
1155 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1156 SoupSessionCallback callback, gpointer user_data)
1158 g_return_if_fail (SOUP_IS_SESSION (session));
1159 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1161 SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1162 callback, user_data);
1166 requeue_message (SoupSession *session, SoupMessage *msg)
1168 soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1172 * soup_session_requeue_message:
1173 * @session: a #SoupSession
1174 * @msg: the message to requeue
1176 * This causes @msg to be placed back on the queue to be attempted
1180 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
1182 g_return_if_fail (SOUP_IS_SESSION (session));
1183 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1185 SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
1190 * soup_session_send_message:
1191 * @session: a #SoupSession
1192 * @msg: the message to send
1194 * Synchronously send @msg. This call will not return until the
1195 * transfer is finished successfully or there is an unrecoverable
1198 * @msg is not freed upon return.
1200 * Return value: the HTTP status code of the response
1203 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1205 g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1206 g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1208 return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1213 * soup_session_pause_message:
1214 * @session: a #SoupSession
1215 * @msg: a #SoupMessage currently running on @session
1217 * Pauses HTTP I/O on @msg. Call soup_session_unpause_message() to
1221 soup_session_pause_message (SoupSession *session,
1224 g_return_if_fail (SOUP_IS_SESSION (session));
1225 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1227 soup_message_io_pause (msg);
1231 * soup_session_unpause_message:
1232 * @session: a #SoupSession
1233 * @msg: a #SoupMessage currently running on @session
1235 * Resumes HTTP I/O on @msg. Use this to resume after calling
1236 * soup_sessino_pause_message().
1238 * If @msg is being sent via blocking I/O, this will resume reading or
1239 * writing immediately. If @msg is using non-blocking I/O, then
1240 * reading or writing won't resume until you return to the main loop.
1243 soup_session_unpause_message (SoupSession *session,
1246 g_return_if_fail (SOUP_IS_SESSION (session));
1247 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1249 soup_message_io_unpause (msg);
1254 cancel_message (SoupSession *session, SoupMessage *msg, guint status_code)
1256 SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1258 soup_message_queue_remove_message (priv->queue, msg);
1259 soup_message_io_stop (msg);
1260 soup_message_set_status (msg, status_code);
1261 soup_message_finished (msg);
1265 * soup_session_cancel_message:
1266 * @session: a #SoupSession
1267 * @msg: the message to cancel
1268 * @status_code: status code to set on @msg (generally
1269 * %SOUP_STATUS_CANCELLED)
1271 * Causes @session to immediately finish processing @msg, with a final
1272 * status_code of @status_code. Depending on when you cancel it, the
1273 * response state may be incomplete or inconsistent.
1276 soup_session_cancel_message (SoupSession *session, SoupMessage *msg,
1279 g_return_if_fail (SOUP_IS_SESSION (session));
1280 g_return_if_fail (SOUP_IS_MESSAGE (msg));
1282 SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg, status_code);
1286 gather_conns (gpointer key, gpointer host, gpointer data)
1288 SoupConnection *conn = key;
1289 GSList **conns = data;
1291 *conns = g_slist_prepend (*conns, conn);
1295 * soup_session_abort:
1296 * @session: the session
1298 * Cancels all pending requests in @session.
1301 soup_session_abort (SoupSession *session)
1303 SoupSessionPrivate *priv;
1304 SoupMessageQueueIter iter;
1308 g_return_if_fail (SOUP_IS_SESSION (session));
1309 priv = SOUP_SESSION_GET_PRIVATE (session);
1311 for (msg = soup_message_queue_first (priv->queue, &iter);
1313 msg = soup_message_queue_next (priv->queue, &iter)) {
1314 soup_session_cancel_message (session, msg,
1315 SOUP_STATUS_CANCELLED);
1318 /* Close all connections */
1319 g_mutex_lock (priv->host_lock);
1321 g_hash_table_foreach (priv->conns, gather_conns, &conns);
1323 for (c = conns; c; c = c->next)
1324 g_object_ref (c->data);
1325 g_mutex_unlock (priv->host_lock);
1326 for (c = conns; c; c = c->next) {
1327 soup_connection_disconnect (c->data);
1328 g_object_unref (c->data);
1331 g_slist_free (conns);
1335 soup_session_add_feature (SoupSession *session, SoupSessionFeature *feature)
1337 SoupSessionPrivate *priv;
1339 g_return_if_fail (SOUP_IS_SESSION (session));
1340 g_return_if_fail (SOUP_IS_SESSION_FEATURE (feature));
1342 priv = SOUP_SESSION_GET_PRIVATE (session);
1343 priv->features = g_slist_prepend (priv->features, g_object_ref (feature));
1344 soup_session_feature_attach (feature, session);
1348 soup_session_add_feature_by_type (SoupSession *session, GType feature_type)
1350 SoupSessionFeature *feature;
1352 g_return_if_fail (SOUP_IS_SESSION (session));
1353 g_return_if_fail (g_type_is_a (feature_type, SOUP_TYPE_SESSION_FEATURE));
1355 feature = g_object_new (feature_type, NULL);
1356 soup_session_add_feature (session, feature);
1357 g_object_unref (feature);
1361 soup_session_remove_feature (SoupSession *session, SoupSessionFeature *feature)
1363 SoupSessionPrivate *priv;
1365 g_return_if_fail (SOUP_IS_SESSION (session));
1367 priv = SOUP_SESSION_GET_PRIVATE (session);
1368 if (g_slist_find (priv->features, feature)) {
1369 priv->features = g_slist_remove (priv->features, feature);
1370 soup_session_feature_detach (feature, session);
1371 g_object_unref (feature);
1376 soup_session_remove_feature_by_type (SoupSession *session, GType feature_type)
1378 SoupSessionPrivate *priv;
1381 g_return_if_fail (SOUP_IS_SESSION (session));
1383 priv = SOUP_SESSION_GET_PRIVATE (session);
1385 for (f = priv->features; f; f = f->next) {
1386 if (G_TYPE_CHECK_INSTANCE_TYPE (f->data, feature_type)) {
1387 soup_session_remove_feature (session, f->data);