1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
5 * Copyright (C) 2000-2003, Ximian, Inc.
16 #include "soup-session.h"
17 #include "soup-connection.h"
18 #include "soup-connection-ntlm.h"
19 #include "soup-marshal.h"
20 #include "soup-message-queue.h"
21 #include "soup-private.h"
27 GSList *connections; /* CONTAINS: SoupConnection */
30 GHashTable *auth_realms; /* path -> scheme:realm */
31 GHashTable *auths; /* scheme:realm -> SoupAuth */
34 struct SoupSessionPrivate {
36 guint max_conns, max_conns_per_host;
39 SoupMessageQueue *queue;
41 GHashTable *hosts; /* SoupUri -> SoupSessionHost */
42 GHashTable *conns; /* SoupConnection -> SoupSessionHost */
45 SoupSessionHost *proxy_host;
48 static guint host_uri_hash (gconstpointer key);
49 static gboolean host_uri_equal (gconstpointer v1, gconstpointer v2);
51 static gboolean run_queue (SoupSession *session, gboolean try_pruning);
53 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
54 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 4
56 #define PARENT_TYPE G_TYPE_OBJECT
57 static GObjectClass *parent_class;
65 static guint signals[LAST_SIGNAL] = { 0 };
72 PROP_MAX_CONNS_PER_HOST,
78 static void set_property (GObject *object, guint prop_id,
79 const GValue *value, GParamSpec *pspec);
80 static void get_property (GObject *object, guint prop_id,
81 GValue *value, GParamSpec *pspec);
84 init (GObject *object)
86 SoupSession *session = SOUP_SESSION (object);
88 session->priv = g_new0 (SoupSessionPrivate, 1);
89 session->priv->queue = soup_message_queue_new ();
90 session->priv->hosts = g_hash_table_new (host_uri_hash,
92 session->priv->conns = g_hash_table_new (NULL, NULL);
94 session->priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
95 session->priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
99 dispose (GObject *object)
101 SoupSession *session = SOUP_SESSION (object);
103 soup_session_abort (session);
105 G_OBJECT_CLASS (parent_class)->dispose (object);
109 finalize (GObject *object)
111 SoupSession *session = SOUP_SESSION (object);
113 soup_message_queue_destroy (session->priv->queue);
114 g_free (session->priv);
116 G_OBJECT_CLASS (parent_class)->finalize (object);
120 class_init (GObjectClass *object_class)
122 parent_class = g_type_class_ref (PARENT_TYPE);
124 /* virtual method override */
125 object_class->dispose = dispose;
126 object_class->finalize = finalize;
127 object_class->set_property = set_property;
128 object_class->get_property = get_property;
131 signals[AUTHENTICATE] =
132 g_signal_new ("authenticate",
133 G_OBJECT_CLASS_TYPE (object_class),
135 G_STRUCT_OFFSET (SoupSessionClass, authenticate),
137 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
144 signals[REAUTHENTICATE] =
145 g_signal_new ("reauthenticate",
146 G_OBJECT_CLASS_TYPE (object_class),
148 G_STRUCT_OFFSET (SoupSessionClass, reauthenticate),
150 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
159 g_object_class_install_property (
160 object_class, PROP_PROXY_URI,
161 g_param_spec_pointer (SOUP_SESSION_PROXY_URI,
163 "The HTTP Proxy to use for this session",
164 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
165 g_object_class_install_property (
166 object_class, PROP_MAX_CONNS,
167 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
168 "Max Connection Count",
169 "The maximum number of connections that the session can open at once",
174 g_object_class_install_property (
175 object_class, PROP_MAX_CONNS_PER_HOST,
176 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
177 "Max Per-Host Connection Count",
178 "The maximum number of connections that the session can open at once to a given host",
183 g_object_class_install_property (
184 object_class, PROP_USE_NTLM,
185 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
187 "Whether or not to use NTLM authentication",
192 SOUP_MAKE_TYPE (soup_session, SoupSession, class_init, init, PARENT_TYPE)
195 soup_session_new (void)
197 return g_object_new (SOUP_TYPE_SESSION, NULL);
201 soup_session_new_with_options (const char *optname1, ...)
203 SoupSession *session;
206 va_start (ap, optname1);
207 session = (SoupSession *)g_object_new_valist (SOUP_TYPE_SESSION, optname1, ap);
214 set_property (GObject *object, guint prop_id,
215 const GValue *value, GParamSpec *pspec)
217 SoupSession *session = SOUP_SESSION (object);
222 pval = g_value_get_pointer (value);
223 session->priv->proxy_uri = pval ? soup_uri_copy (pval) : NULL;
226 session->priv->max_conns = g_value_get_int (value);
228 case PROP_MAX_CONNS_PER_HOST:
229 session->priv->max_conns_per_host = g_value_get_int (value);
232 session->priv->use_ntlm = g_value_get_boolean (value);
240 get_property (GObject *object, guint prop_id,
241 GValue *value, GParamSpec *pspec)
243 SoupSession *session = SOUP_SESSION (object);
247 g_value_set_pointer (value, session->priv->proxy_uri ?
248 soup_uri_copy (session->priv->proxy_uri) :
252 g_value_set_int (value, session->priv->max_conns);
254 case PROP_MAX_CONNS_PER_HOST:
255 g_value_set_int (value, session->priv->max_conns_per_host);
258 g_value_set_boolean (value, session->priv->use_ntlm);
268 host_uri_hash (gconstpointer key)
270 const SoupUri *uri = key;
272 return (uri->protocol << 16) + uri->port + g_str_hash (uri->host);
276 host_uri_equal (gconstpointer v1, gconstpointer v2)
278 const SoupUri *one = v1;
279 const SoupUri *two = v2;
281 if (one->protocol != two->protocol)
283 if (one->port != two->port)
286 return strcmp (one->host, two->host) == 0;
289 static SoupSessionHost *
290 get_host_for_message (SoupSession *session, SoupMessage *msg)
292 SoupSessionHost *host;
293 const SoupUri *source = soup_message_get_uri (msg);
295 host = g_hash_table_lookup (session->priv->hosts, source);
299 host = g_new0 (SoupSessionHost, 1);
300 host->root_uri = soup_uri_copy_root (source);
302 g_hash_table_insert (session->priv->hosts, host->root_uri, host);
310 lookup_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
312 SoupSessionHost *host;
314 const char *realm, *const_path;
317 host = session->priv->proxy_host;
320 host = get_host_for_message (session, msg);
321 const_path = soup_message_get_uri (msg)->path;
323 g_return_val_if_fail (host != NULL, NULL);
325 if (!host->auth_realms)
328 path = g_strdup (const_path);
331 realm = g_hash_table_lookup (host->auth_realms, path);
335 dir = strrchr (path, '/');
342 return g_hash_table_lookup (host->auths, realm);
348 invalidate_auth (SoupSessionHost *host, SoupAuth *auth)
353 realm = g_strdup_printf ("%s:%s",
354 soup_auth_get_scheme_name (auth),
355 soup_auth_get_realm (auth));
357 if (g_hash_table_lookup_extended (host->auths, realm, &key, &value) &&
358 auth == (SoupAuth *)value) {
359 g_hash_table_remove (host->auths, realm);
361 g_object_unref (auth);
367 authenticate_auth (SoupSession *session, SoupAuth *auth,
368 SoupMessage *msg, gboolean prior_auth_failed)
370 const SoupUri *uri = soup_message_get_uri (msg);
371 char *username = NULL, *password = NULL;
373 if (uri->passwd && !prior_auth_failed) {
374 soup_auth_authenticate (auth, uri->user, uri->passwd);
378 g_signal_emit (session, signals[prior_auth_failed ? REAUTHENTICATE : AUTHENTICATE], 0,
379 msg, soup_auth_get_scheme_name (auth),
380 soup_auth_get_realm (auth),
381 &username, &password);
382 if (username || password)
383 soup_auth_authenticate (auth, username, password);
387 memset (password, 0, strlen (password));
391 return soup_auth_is_authenticated (auth);
395 update_auth_internal (SoupSession *session, SoupMessage *msg,
396 const GSList *headers, gboolean proxy,
397 gboolean got_unauthorized)
399 SoupSessionHost *host;
400 SoupAuth *new_auth, *prior_auth, *old_auth;
401 gpointer old_path, old_realm;
402 const SoupUri *msg_uri;
406 gboolean prior_auth_failed = FALSE;
408 host = get_host_for_message (session, msg);
409 g_return_val_if_fail (host != NULL, FALSE);
411 /* Try to construct a new auth from the headers; if we can't,
412 * there's no way we'll be able to authenticate.
414 msg_uri = soup_message_get_uri (msg);
415 new_auth = soup_auth_new_from_header_list (headers);
419 /* See if this auth is the same auth we used last time */
420 prior_auth = lookup_auth (session, msg, proxy);
422 G_OBJECT_TYPE (prior_auth) == G_OBJECT_TYPE (new_auth) &&
423 !strcmp (soup_auth_get_realm (prior_auth),
424 soup_auth_get_realm (new_auth))) {
425 if (!got_unauthorized) {
426 /* The user is just trying to preauthenticate
427 * using information we already have, so
428 * there's nothing more that needs to be done.
430 g_object_unref (new_auth);
434 /* The server didn't like the username/password we
435 * provided before. Invalidate it and note this fact.
437 invalidate_auth (host, prior_auth);
438 prior_auth_failed = TRUE;
441 if (!host->auth_realms) {
442 host->auth_realms = g_hash_table_new (g_str_hash, g_str_equal);
443 host->auths = g_hash_table_new (g_str_hash, g_str_equal);
446 /* Record where this auth realm is used */
447 realm = g_strdup_printf ("%s:%s",
448 soup_auth_get_scheme_name (new_auth),
449 soup_auth_get_realm (new_auth));
450 pspace = soup_auth_get_protection_space (new_auth, msg_uri);
451 for (p = pspace; p; p = p->next) {
453 if (g_hash_table_lookup_extended (host->auth_realms, path,
454 &old_path, &old_realm)) {
455 g_hash_table_remove (host->auth_realms, old_path);
460 g_hash_table_insert (host->auth_realms,
461 g_strdup (path), g_strdup (realm));
463 soup_auth_free_protection_space (new_auth, pspace);
465 /* Now, make sure the auth is recorded. (If there's a
466 * pre-existing auth, we keep that rather than the new one,
467 * since the old one might already be authenticated.)
469 old_auth = g_hash_table_lookup (host->auths, realm);
472 g_object_unref (new_auth);
475 g_hash_table_insert (host->auths, realm, new_auth);
477 /* If we need to authenticate, try to do it. */
478 if (!soup_auth_is_authenticated (new_auth)) {
479 return authenticate_auth (session, new_auth,
480 msg, prior_auth_failed);
483 /* Otherwise we're good. */
488 connection_authenticate (SoupConnection *conn, SoupMessage *msg,
489 const char *auth_type, const char *auth_realm,
490 char **username, char **password, gpointer session)
492 g_signal_emit (session, signals[AUTHENTICATE], 0,
493 msg, auth_type, auth_realm, username, password);
497 connection_reauthenticate (SoupConnection *conn, SoupMessage *msg,
498 const char *auth_type, const char *auth_realm,
499 char **username, char **password,
502 g_signal_emit (conn, signals[REAUTHENTICATE], 0,
503 msg, auth_type, auth_realm, username, password);
508 authorize_handler (SoupMessage *msg, gpointer user_data)
510 SoupSession *session = user_data;
511 const GSList *headers;
514 if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
515 headers = soup_message_get_header_list (msg->response_headers,
516 "Proxy-Authenticate");
519 headers = soup_message_get_header_list (msg->response_headers,
526 if (update_auth_internal (session, msg, headers, proxy, TRUE))
527 soup_session_requeue_message (session, msg);
531 redirect_handler (SoupMessage *msg, gpointer user_data)
533 SoupSession *session = user_data;
537 new_loc = soup_message_get_header (msg->response_headers, "Location");
540 new_uri = soup_uri_new (new_loc);
542 goto INVALID_REDIRECT;
544 soup_message_set_uri (msg, new_uri);
545 soup_uri_free (new_uri);
547 soup_session_requeue_message (session, msg);
551 soup_message_set_status_full (msg,
552 SOUP_STATUS_MALFORMED,
553 "Invalid Redirect URL");
557 request_finished (SoupMessage *req, gpointer user_data)
559 req->status = SOUP_MESSAGE_STATUS_FINISHED;
563 final_finished (SoupMessage *req, gpointer user_data)
565 SoupSession *session = user_data;
567 if (!SOUP_MESSAGE_IS_STARTING (req)) {
568 soup_message_queue_remove_message (session->priv->queue, req);
570 g_signal_handlers_disconnect_by_func (req, request_finished, session);
571 g_signal_handlers_disconnect_by_func (req, final_finished, session);
572 g_object_unref (req);
574 run_queue (session, FALSE);
579 add_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
581 const char *header = proxy ? "Proxy-Authorization" : "Authorization";
585 soup_message_remove_header (msg->request_headers, header);
587 auth = lookup_auth (session, msg, proxy);
590 if (!soup_auth_is_authenticated (auth) &&
591 !authenticate_auth (session, auth, msg, FALSE))
594 token = soup_auth_get_authorization (auth, msg);
596 soup_message_add_header (msg->request_headers, header, token);
602 send_request (SoupSession *session, SoupMessage *req, SoupConnection *conn)
604 req->status = SOUP_MESSAGE_STATUS_RUNNING;
606 add_auth (session, req, FALSE);
607 if (session->priv->proxy_uri)
608 add_auth (session, req, TRUE);
609 soup_connection_send_request (conn, req);
613 find_oldest_connection (gpointer key, gpointer host, gpointer data)
615 SoupConnection *conn = key, **oldest = data;
617 /* Don't prune a connection that hasn't even been used yet. */
618 if (soup_connection_last_used (conn) == 0)
621 if (!*oldest || (soup_connection_last_used (conn) <
622 soup_connection_last_used (*oldest)))
627 try_prune_connection (SoupSession *session)
629 SoupConnection *oldest = NULL;
631 g_hash_table_foreach (session->priv->conns, find_oldest_connection,
634 soup_connection_disconnect (oldest);
635 g_object_unref (oldest);
641 static void connection_closed (SoupConnection *conn, SoupSession *session);
644 cleanup_connection (SoupSession *session, SoupConnection *conn)
646 SoupSessionHost *host =
647 g_hash_table_lookup (session->priv->conns, conn);
649 g_return_if_fail (host != NULL);
651 g_hash_table_remove (session->priv->conns, conn);
652 g_signal_handlers_disconnect_by_func (conn, connection_closed, session);
653 session->priv->num_conns--;
655 host->connections = g_slist_remove (host->connections, conn);
660 connection_closed (SoupConnection *conn, SoupSession *session)
662 cleanup_connection (session, conn);
664 /* Run the queue in case anyone was waiting for a connection
667 run_queue (session, FALSE);
671 got_connection (SoupConnection *conn, guint status, gpointer user_data)
673 SoupSession *session = user_data;
674 SoupSessionHost *host = g_hash_table_lookup (session->priv->conns, conn);
676 g_return_if_fail (host != NULL);
678 if (status == SOUP_STATUS_OK) {
679 host->connections = g_slist_prepend (host->connections, conn);
680 run_queue (session, FALSE);
685 cleanup_connection (session, conn);
686 g_object_unref (conn);
688 if (host->connections) {
689 /* Something went wrong this time, but we have at
690 * least one open connection to this host. So just
691 * leave the message in the queue so it can use that
692 * connection once it's free.
697 /* Flush any queued messages for this host */
698 host->error = status;
699 run_queue (session, FALSE);
701 if (status != SOUP_STATUS_CANT_RESOLVE &&
702 status != SOUP_STATUS_CANT_RESOLVE_PROXY) {
703 /* If the error was "can't resolve", then it's not likely
704 * to improve. But if it was something else, it may have
705 * been transient, so we clear the error so the user can
713 run_queue (SoupSession *session, gboolean try_pruning)
715 SoupMessageQueueIter iter;
717 SoupConnection *conn;
718 SoupSessionHost *host;
719 gboolean skipped_any = FALSE, started_any = FALSE;
722 /* FIXME: prefer CONNECTING messages */
725 for (msg = soup_message_queue_first (session->priv->queue, &iter); msg; msg = soup_message_queue_next (session->priv->queue, &iter)) {
727 if (!SOUP_MESSAGE_IS_STARTING (msg))
730 host = get_host_for_message (session, msg);
732 /* If the hostname is known to be bad, fail right away */
734 soup_message_set_status (msg, host->error);
735 soup_message_finished (msg);
738 /* If there is an idle connection, use it */
739 for (conns = host->connections; conns; conns = conns->next) {
740 if (!soup_connection_is_in_use (conns->data))
744 send_request (session, msg, conns->data);
749 if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING) {
750 /* We already started a connection for this
751 * message, so don't start another one.
756 /* If we have the max number of per-host connections
757 * or total connections open, we'll have to wait.
759 if (host->num_conns >= session->priv->max_conns_per_host)
761 else if (session->priv->num_conns >= session->priv->max_conns) {
762 /* In this case, closing an idle connection
763 * somewhere else would let us open one here.
769 /* Otherwise, open a new connection */
770 conn = g_object_new (
771 (session->priv->use_ntlm ?
772 SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
773 SOUP_CONNECTION_DEST_URI, host->root_uri,
774 SOUP_CONNECTION_PROXY_URI, session->priv->proxy_uri,
776 g_signal_connect (conn, "authenticate",
777 G_CALLBACK (connection_authenticate),
779 g_signal_connect (conn, "reauthenticate",
780 G_CALLBACK (connection_reauthenticate),
783 soup_connection_connect_async (conn, got_connection, session);
784 g_signal_connect (conn, "disconnected",
785 G_CALLBACK (connection_closed), session);
786 g_hash_table_insert (session->priv->conns, conn, host);
787 session->priv->num_conns++;
789 /* Increment the host's connection count, but don't add
790 * this connection to the list yet, since it's not ready.
794 /* Mark the request as connecting, so we don't try to
795 * open another new connection for it next time around.
797 msg->status = SOUP_MESSAGE_STATUS_CONNECTING;
802 if (try_pruning && skipped_any && !started_any) {
803 /* We didn't manage to start any message, but there is
804 * at least one message in the queue that could be
805 * sent if we pruned an idle connection from some
808 if (try_prune_connection (session)) {
818 queue_message (SoupSession *session, SoupMessage *req, gboolean requeue)
820 req->status = SOUP_MESSAGE_STATUS_QUEUED;
822 soup_message_queue_append (session->priv->queue, req);
823 run_queue (session, TRUE);
828 * soup_session_queue_message:
829 * @session: a #SoupSession
830 * @req: the message to queue
831 * @callback: a #SoupMessageCallbackFn which will be called after the
832 * message completes or when an unrecoverable error occurs.
833 * @user_data: a pointer passed to @callback.
835 * Queues the message @req for sending. All messages are processed
836 * while the glib main loop runs. If @req has been processed before,
837 * any resources related to the time it was last sent are freed.
839 * Upon message completion, the callback specified in @callback will
840 * be invoked. If after returning from this callback the message has
841 * not been requeued, @req will be unreffed.
844 soup_session_queue_message (SoupSession *session, SoupMessage *req,
845 SoupMessageCallbackFn callback, gpointer user_data)
847 g_return_if_fail (SOUP_IS_SESSION (session));
848 g_return_if_fail (SOUP_IS_MESSAGE (req));
850 g_signal_connect (req, "finished",
851 G_CALLBACK (request_finished), session);
853 g_signal_connect (req, "finished",
854 G_CALLBACK (callback), user_data);
856 g_signal_connect_after (req, "finished",
857 G_CALLBACK (final_finished), session);
859 soup_message_add_status_code_handler (req, SOUP_STATUS_UNAUTHORIZED,
860 SOUP_HANDLER_POST_BODY,
861 authorize_handler, session);
862 soup_message_add_status_code_handler (req,
863 SOUP_STATUS_PROXY_UNAUTHORIZED,
864 SOUP_HANDLER_POST_BODY,
865 authorize_handler, session);
867 if (!(soup_message_get_flags (req) & SOUP_MESSAGE_NO_REDIRECT)) {
868 soup_message_add_status_class_handler (
869 req, SOUP_STATUS_CLASS_REDIRECT,
870 SOUP_HANDLER_POST_BODY,
871 redirect_handler, session);
874 queue_message (session, req, FALSE);
878 * soup_session_requeue_message:
879 * @session: a #SoupSession
880 * @req: the message to requeue
882 * This causes @req to be placed back on the queue to be attempted
886 soup_session_requeue_message (SoupSession *session, SoupMessage *req)
888 g_return_if_fail (SOUP_IS_SESSION (session));
889 g_return_if_fail (SOUP_IS_MESSAGE (req));
891 queue_message (session, req, TRUE);
896 * soup_session_send_message:
897 * @session: a #SoupSession
898 * @req: the message to send
900 * Synchronously send @req. This call will not return until the
901 * transfer is finished successfully or there is an unrecoverable
904 * @req is not freed upon return.
906 * Return value: the HTTP status code of the response
909 soup_session_send_message (SoupSession *session, SoupMessage *req)
911 g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
912 g_return_val_if_fail (SOUP_IS_MESSAGE (req), SOUP_STATUS_MALFORMED);
914 /* Balance out the unref that final_finished will do */
917 soup_session_queue_message (session, req, NULL, NULL);
920 g_main_iteration (TRUE);
922 if (req->status == SOUP_MESSAGE_STATUS_FINISHED ||
923 SOUP_STATUS_IS_TRANSPORT (req->status_code))
927 return req->status_code;
931 * soup_session_abort:
932 * @session: the session
934 * Cancels all pending requests in @session.
937 soup_session_abort (SoupSession *session)
939 SoupMessageQueueIter iter;
942 for (msg = soup_message_queue_first (session->priv->queue, &iter); msg; msg = soup_message_queue_next (session->priv->queue, &iter)) {
943 soup_message_queue_remove (session->priv->queue, &iter);
944 soup_message_cancel (msg);