1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
5 * Copyright (C) 2000-2003, Ximian, Inc.
16 #include "soup-auth.h"
17 #include "soup-session.h"
18 #include "soup-connection.h"
19 #include "soup-connection-ntlm.h"
20 #include "soup-marshal.h"
21 #include "soup-message-queue.h"
28 GSList *connections; /* CONTAINS: SoupConnection */
31 GHashTable *auth_realms; /* path -> scheme:realm */
32 GHashTable *auths; /* scheme:realm -> SoupAuth */
35 struct SoupSessionPrivate {
37 guint max_conns, max_conns_per_host;
40 SoupMessageQueue *queue;
42 GHashTable *hosts; /* SoupUri -> SoupSessionHost */
43 GHashTable *conns; /* SoupConnection -> SoupSessionHost */
46 SoupSessionHost *proxy_host;
49 static guint host_uri_hash (gconstpointer key);
50 static gboolean host_uri_equal (gconstpointer v1, gconstpointer v2);
51 static void free_host (SoupSessionHost *host, SoupSession *session);
53 static gboolean run_queue (SoupSession *session, gboolean try_pruning);
55 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
56 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 4
58 #define PARENT_TYPE G_TYPE_OBJECT
59 static GObjectClass *parent_class;
67 static guint signals[LAST_SIGNAL] = { 0 };
74 PROP_MAX_CONNS_PER_HOST,
80 static void set_property (GObject *object, guint prop_id,
81 const GValue *value, GParamSpec *pspec);
82 static void get_property (GObject *object, guint prop_id,
83 GValue *value, GParamSpec *pspec);
86 init (GObject *object)
88 SoupSession *session = SOUP_SESSION (object);
90 session->priv = g_new0 (SoupSessionPrivate, 1);
91 session->priv->queue = soup_message_queue_new ();
92 session->priv->hosts = g_hash_table_new (host_uri_hash,
94 session->priv->conns = g_hash_table_new (NULL, NULL);
96 session->priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
97 session->priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
101 foreach_free_host (gpointer key, gpointer host, gpointer session)
103 free_host (host, session);
108 cleanup_hosts (SoupSession *session)
110 g_hash_table_foreach_remove (session->priv->hosts,
111 foreach_free_host, session);
115 dispose (GObject *object)
117 SoupSession *session = SOUP_SESSION (object);
119 soup_session_abort (session);
120 cleanup_hosts (session);
122 G_OBJECT_CLASS (parent_class)->dispose (object);
126 finalize (GObject *object)
128 SoupSession *session = SOUP_SESSION (object);
130 soup_message_queue_destroy (session->priv->queue);
131 g_hash_table_destroy (session->priv->hosts);
132 g_hash_table_destroy (session->priv->conns);
133 g_free (session->priv);
135 G_OBJECT_CLASS (parent_class)->finalize (object);
139 class_init (GObjectClass *object_class)
141 parent_class = g_type_class_ref (PARENT_TYPE);
143 /* virtual method override */
144 object_class->dispose = dispose;
145 object_class->finalize = finalize;
146 object_class->set_property = set_property;
147 object_class->get_property = get_property;
150 signals[AUTHENTICATE] =
151 g_signal_new ("authenticate",
152 G_OBJECT_CLASS_TYPE (object_class),
154 G_STRUCT_OFFSET (SoupSessionClass, authenticate),
156 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
163 signals[REAUTHENTICATE] =
164 g_signal_new ("reauthenticate",
165 G_OBJECT_CLASS_TYPE (object_class),
167 G_STRUCT_OFFSET (SoupSessionClass, reauthenticate),
169 soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
178 g_object_class_install_property (
179 object_class, PROP_PROXY_URI,
180 g_param_spec_pointer (SOUP_SESSION_PROXY_URI,
182 "The HTTP Proxy to use for this session",
184 g_object_class_install_property (
185 object_class, PROP_MAX_CONNS,
186 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
187 "Max Connection Count",
188 "The maximum number of connections that the session can open at once",
193 g_object_class_install_property (
194 object_class, PROP_MAX_CONNS_PER_HOST,
195 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
196 "Max Per-Host Connection Count",
197 "The maximum number of connections that the session can open at once to a given host",
202 g_object_class_install_property (
203 object_class, PROP_USE_NTLM,
204 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
206 "Whether or not to use NTLM authentication",
211 SOUP_MAKE_TYPE (soup_session, SoupSession, class_init, init, PARENT_TYPE)
214 soup_session_new (void)
216 return g_object_new (SOUP_TYPE_SESSION, NULL);
220 soup_session_new_with_options (const char *optname1, ...)
222 SoupSession *session;
225 va_start (ap, optname1);
226 session = (SoupSession *)g_object_new_valist (SOUP_TYPE_SESSION, optname1, ap);
233 set_property (GObject *object, guint prop_id,
234 const GValue *value, GParamSpec *pspec)
236 SoupSession *session = SOUP_SESSION (object);
241 if (session->priv->proxy_uri)
242 soup_uri_free (session->priv->proxy_uri);
243 pval = g_value_get_pointer (value);
244 session->priv->proxy_uri = pval ? soup_uri_copy (pval) : NULL;
246 soup_session_abort (session);
247 cleanup_hosts (session);
250 session->priv->max_conns = g_value_get_int (value);
252 case PROP_MAX_CONNS_PER_HOST:
253 session->priv->max_conns_per_host = g_value_get_int (value);
256 session->priv->use_ntlm = g_value_get_boolean (value);
264 get_property (GObject *object, guint prop_id,
265 GValue *value, GParamSpec *pspec)
267 SoupSession *session = SOUP_SESSION (object);
271 g_value_set_pointer (value, session->priv->proxy_uri ?
272 soup_uri_copy (session->priv->proxy_uri) :
276 g_value_set_int (value, session->priv->max_conns);
278 case PROP_MAX_CONNS_PER_HOST:
279 g_value_set_int (value, session->priv->max_conns_per_host);
282 g_value_set_boolean (value, session->priv->use_ntlm);
292 host_uri_hash (gconstpointer key)
294 const SoupUri *uri = key;
296 return (uri->protocol << 16) + uri->port + g_str_hash (uri->host);
300 host_uri_equal (gconstpointer v1, gconstpointer v2)
302 const SoupUri *one = v1;
303 const SoupUri *two = v2;
305 if (one->protocol != two->protocol)
307 if (one->port != two->port)
310 return strcmp (one->host, two->host) == 0;
313 static SoupSessionHost *
314 get_host_for_message (SoupSession *session, SoupMessage *msg)
316 SoupSessionHost *host;
317 const SoupUri *source = soup_message_get_uri (msg);
319 host = g_hash_table_lookup (session->priv->hosts, source);
323 host = g_new0 (SoupSessionHost, 1);
324 host->root_uri = soup_uri_copy_root (source);
326 g_hash_table_insert (session->priv->hosts, host->root_uri, host);
331 free_realm (gpointer path, gpointer scheme_realm, gpointer data)
334 g_free (scheme_realm);
338 free_auth (gpointer scheme_realm, gpointer auth, gpointer data)
340 g_free (scheme_realm);
341 g_object_unref (auth);
345 free_host (SoupSessionHost *host, SoupSession *session)
347 while (host->connections) {
348 SoupConnection *conn = host->connections->data;
350 host->connections = g_slist_remove (host->connections, conn);
351 soup_connection_disconnect (conn);
354 if (host->auth_realms) {
355 g_hash_table_foreach (host->auth_realms, free_realm, NULL);
356 g_hash_table_destroy (host->auth_realms);
359 g_hash_table_foreach (host->auths, free_auth, NULL);
360 g_hash_table_destroy (host->auths);
363 soup_uri_free (host->root_uri);
369 lookup_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
371 SoupSessionHost *host;
373 const char *realm, *const_path;
376 host = session->priv->proxy_host;
379 host = get_host_for_message (session, msg);
380 const_path = soup_message_get_uri (msg)->path;
382 g_return_val_if_fail (host != NULL, NULL);
384 if (!host->auth_realms)
387 path = g_strdup (const_path);
390 realm = g_hash_table_lookup (host->auth_realms, path);
394 dir = strrchr (path, '/');
401 return g_hash_table_lookup (host->auths, realm);
407 invalidate_auth (SoupSessionHost *host, SoupAuth *auth)
412 realm = g_strdup_printf ("%s:%s",
413 soup_auth_get_scheme_name (auth),
414 soup_auth_get_realm (auth));
416 if (g_hash_table_lookup_extended (host->auths, realm, &key, &value) &&
417 auth == (SoupAuth *)value) {
418 g_hash_table_remove (host->auths, realm);
420 g_object_unref (auth);
426 authenticate_auth (SoupSession *session, SoupAuth *auth,
427 SoupMessage *msg, gboolean prior_auth_failed)
429 const SoupUri *uri = soup_message_get_uri (msg);
430 char *username = NULL, *password = NULL;
432 if (uri->passwd && !prior_auth_failed) {
433 soup_auth_authenticate (auth, uri->user, uri->passwd);
437 g_signal_emit (session, signals[prior_auth_failed ? REAUTHENTICATE : AUTHENTICATE], 0,
438 msg, soup_auth_get_scheme_name (auth),
439 soup_auth_get_realm (auth),
440 &username, &password);
441 if (username || password)
442 soup_auth_authenticate (auth, username, password);
446 memset (password, 0, strlen (password));
450 return soup_auth_is_authenticated (auth);
454 update_auth_internal (SoupSession *session, SoupMessage *msg,
455 const GSList *headers, gboolean proxy,
456 gboolean got_unauthorized)
458 SoupSessionHost *host;
459 SoupAuth *new_auth, *prior_auth, *old_auth;
460 gpointer old_path, old_realm;
461 const SoupUri *msg_uri;
465 gboolean prior_auth_failed = FALSE;
467 host = get_host_for_message (session, msg);
468 g_return_val_if_fail (host != NULL, FALSE);
470 /* Try to construct a new auth from the headers; if we can't,
471 * there's no way we'll be able to authenticate.
473 msg_uri = soup_message_get_uri (msg);
474 new_auth = soup_auth_new_from_header_list (headers);
478 /* See if this auth is the same auth we used last time */
479 prior_auth = lookup_auth (session, msg, proxy);
481 G_OBJECT_TYPE (prior_auth) == G_OBJECT_TYPE (new_auth) &&
482 !strcmp (soup_auth_get_realm (prior_auth),
483 soup_auth_get_realm (new_auth))) {
484 if (!got_unauthorized) {
485 /* The user is just trying to preauthenticate
486 * using information we already have, so
487 * there's nothing more that needs to be done.
489 g_object_unref (new_auth);
493 /* The server didn't like the username/password we
494 * provided before. Invalidate it and note this fact.
496 invalidate_auth (host, prior_auth);
497 prior_auth_failed = TRUE;
500 if (!host->auth_realms) {
501 host->auth_realms = g_hash_table_new (g_str_hash, g_str_equal);
502 host->auths = g_hash_table_new (g_str_hash, g_str_equal);
505 /* Record where this auth realm is used */
506 realm = g_strdup_printf ("%s:%s",
507 soup_auth_get_scheme_name (new_auth),
508 soup_auth_get_realm (new_auth));
509 pspace = soup_auth_get_protection_space (new_auth, msg_uri);
510 for (p = pspace; p; p = p->next) {
512 if (g_hash_table_lookup_extended (host->auth_realms, path,
513 &old_path, &old_realm)) {
514 g_hash_table_remove (host->auth_realms, old_path);
519 g_hash_table_insert (host->auth_realms,
520 g_strdup (path), g_strdup (realm));
522 soup_auth_free_protection_space (new_auth, pspace);
524 /* Now, make sure the auth is recorded. (If there's a
525 * pre-existing auth, we keep that rather than the new one,
526 * since the old one might already be authenticated.)
528 old_auth = g_hash_table_lookup (host->auths, realm);
531 g_object_unref (new_auth);
534 g_hash_table_insert (host->auths, realm, new_auth);
536 /* If we need to authenticate, try to do it. */
537 if (!soup_auth_is_authenticated (new_auth)) {
538 return authenticate_auth (session, new_auth,
539 msg, prior_auth_failed);
542 /* Otherwise we're good. */
547 connection_authenticate (SoupConnection *conn, SoupMessage *msg,
548 const char *auth_type, const char *auth_realm,
549 char **username, char **password, gpointer session)
551 g_signal_emit (session, signals[AUTHENTICATE], 0,
552 msg, auth_type, auth_realm, username, password);
556 connection_reauthenticate (SoupConnection *conn, SoupMessage *msg,
557 const char *auth_type, const char *auth_realm,
558 char **username, char **password,
561 g_signal_emit (conn, signals[REAUTHENTICATE], 0,
562 msg, auth_type, auth_realm, username, password);
567 authorize_handler (SoupMessage *msg, gpointer user_data)
569 SoupSession *session = user_data;
570 const GSList *headers;
573 if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
574 headers = soup_message_get_header_list (msg->response_headers,
575 "Proxy-Authenticate");
578 headers = soup_message_get_header_list (msg->response_headers,
585 if (update_auth_internal (session, msg, headers, proxy, TRUE))
586 soup_session_requeue_message (session, msg);
590 redirect_handler (SoupMessage *msg, gpointer user_data)
592 SoupSession *session = user_data;
596 new_loc = soup_message_get_header (msg->response_headers, "Location");
599 new_uri = soup_uri_new (new_loc);
601 goto INVALID_REDIRECT;
603 soup_message_set_uri (msg, new_uri);
604 soup_uri_free (new_uri);
606 soup_session_requeue_message (session, msg);
610 soup_message_set_status_full (msg,
611 SOUP_STATUS_MALFORMED,
612 "Invalid Redirect URL");
616 request_finished (SoupMessage *req, gpointer user_data)
618 if (!SOUP_MESSAGE_IS_STARTING (req))
619 req->status = SOUP_MESSAGE_STATUS_FINISHED;
623 final_finished (SoupMessage *req, gpointer user_data)
625 SoupSession *session = user_data;
627 if (!SOUP_MESSAGE_IS_STARTING (req)) {
628 soup_message_queue_remove_message (session->priv->queue, req);
630 g_signal_handlers_disconnect_by_func (req, request_finished, session);
631 g_signal_handlers_disconnect_by_func (req, final_finished, session);
632 g_object_unref (req);
635 run_queue (session, FALSE);
639 add_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
641 const char *header = proxy ? "Proxy-Authorization" : "Authorization";
645 soup_message_remove_header (msg->request_headers, header);
647 auth = lookup_auth (session, msg, proxy);
650 if (!soup_auth_is_authenticated (auth) &&
651 !authenticate_auth (session, auth, msg, FALSE))
654 token = soup_auth_get_authorization (auth, msg);
656 soup_message_add_header (msg->request_headers, header, token);
662 send_request (SoupSession *session, SoupMessage *req, SoupConnection *conn)
664 req->status = SOUP_MESSAGE_STATUS_RUNNING;
666 add_auth (session, req, FALSE);
667 if (session->priv->proxy_uri)
668 add_auth (session, req, TRUE);
669 soup_connection_send_request (conn, req);
673 find_oldest_connection (gpointer key, gpointer host, gpointer data)
675 SoupConnection *conn = key, **oldest = data;
677 /* Don't prune a connection that hasn't even been used yet. */
678 if (soup_connection_last_used (conn) == 0)
681 if (!*oldest || (soup_connection_last_used (conn) <
682 soup_connection_last_used (*oldest)))
687 try_prune_connection (SoupSession *session)
689 SoupConnection *oldest = NULL;
691 g_hash_table_foreach (session->priv->conns, find_oldest_connection,
694 soup_connection_disconnect (oldest);
695 g_object_unref (oldest);
701 static void connection_closed (SoupConnection *conn, SoupSession *session);
704 cleanup_connection (SoupSession *session, SoupConnection *conn)
706 SoupSessionHost *host =
707 g_hash_table_lookup (session->priv->conns, conn);
709 g_return_if_fail (host != NULL);
711 g_hash_table_remove (session->priv->conns, conn);
712 g_signal_handlers_disconnect_by_func (conn, connection_closed, session);
713 session->priv->num_conns--;
715 host->connections = g_slist_remove (host->connections, conn);
720 connection_closed (SoupConnection *conn, SoupSession *session)
722 cleanup_connection (session, conn);
724 /* Run the queue in case anyone was waiting for a connection
727 run_queue (session, FALSE);
731 got_connection (SoupConnection *conn, guint status, gpointer user_data)
733 SoupSession *session = user_data;
734 SoupSessionHost *host = g_hash_table_lookup (session->priv->conns, conn);
736 g_return_if_fail (host != NULL);
738 if (status == SOUP_STATUS_OK) {
739 host->connections = g_slist_prepend (host->connections, conn);
740 run_queue (session, FALSE);
745 cleanup_connection (session, conn);
746 g_object_unref (conn);
748 if (host->connections) {
749 /* Something went wrong this time, but we have at
750 * least one open connection to this host. So just
751 * leave the message in the queue so it can use that
752 * connection once it's free.
757 /* Flush any queued messages for this host */
758 host->error = status;
759 run_queue (session, FALSE);
761 if (status != SOUP_STATUS_CANT_RESOLVE &&
762 status != SOUP_STATUS_CANT_RESOLVE_PROXY) {
763 /* If the error was "can't resolve", then it's not likely
764 * to improve. But if it was something else, it may have
765 * been transient, so we clear the error so the user can
773 run_queue (SoupSession *session, gboolean try_pruning)
775 SoupMessageQueueIter iter;
777 SoupConnection *conn;
778 SoupSessionHost *host;
779 gboolean skipped_any = FALSE, started_any = FALSE;
782 /* FIXME: prefer CONNECTING messages */
785 for (msg = soup_message_queue_first (session->priv->queue, &iter); msg; msg = soup_message_queue_next (session->priv->queue, &iter)) {
787 if (!SOUP_MESSAGE_IS_STARTING (msg))
790 host = get_host_for_message (session, msg);
792 /* If the hostname is known to be bad, fail right away */
794 soup_message_set_status (msg, host->error);
795 soup_message_finished (msg);
798 /* If there is an idle connection, use it */
799 for (conns = host->connections; conns; conns = conns->next) {
800 if (!soup_connection_is_in_use (conns->data))
804 send_request (session, msg, conns->data);
809 if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING) {
810 /* We already started a connection for this
811 * message, so don't start another one.
816 /* If we have the max number of per-host connections
817 * or total connections open, we'll have to wait.
819 if (host->num_conns >= session->priv->max_conns_per_host)
821 else if (session->priv->num_conns >= session->priv->max_conns) {
822 /* In this case, closing an idle connection
823 * somewhere else would let us open one here.
829 /* Otherwise, open a new connection */
830 conn = g_object_new (
831 (session->priv->use_ntlm ?
832 SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
833 SOUP_CONNECTION_DEST_URI, host->root_uri,
834 SOUP_CONNECTION_PROXY_URI, session->priv->proxy_uri,
836 g_signal_connect (conn, "authenticate",
837 G_CALLBACK (connection_authenticate),
839 g_signal_connect (conn, "reauthenticate",
840 G_CALLBACK (connection_reauthenticate),
843 soup_connection_connect_async (conn, got_connection, session);
844 g_signal_connect (conn, "disconnected",
845 G_CALLBACK (connection_closed), session);
846 g_hash_table_insert (session->priv->conns, conn, host);
847 session->priv->num_conns++;
849 /* Increment the host's connection count, but don't add
850 * this connection to the list yet, since it's not ready.
854 /* Mark the request as connecting, so we don't try to
855 * open another new connection for it next time around.
857 msg->status = SOUP_MESSAGE_STATUS_CONNECTING;
862 if (try_pruning && skipped_any && !started_any) {
863 /* We didn't manage to start any message, but there is
864 * at least one message in the queue that could be
865 * sent if we pruned an idle connection from some
868 if (try_prune_connection (session)) {
878 queue_message (SoupSession *session, SoupMessage *req, gboolean requeue)
880 req->status = SOUP_MESSAGE_STATUS_QUEUED;
882 soup_message_queue_append (session->priv->queue, req);
883 run_queue (session, TRUE);
888 * soup_session_queue_message:
889 * @session: a #SoupSession
890 * @req: the message to queue
891 * @callback: a #SoupMessageCallbackFn which will be called after the
892 * message completes or when an unrecoverable error occurs.
893 * @user_data: a pointer passed to @callback.
895 * Queues the message @req for sending. All messages are processed
896 * while the glib main loop runs. If @req has been processed before,
897 * any resources related to the time it was last sent are freed.
899 * Upon message completion, the callback specified in @callback will
900 * be invoked. If after returning from this callback the message has
901 * not been requeued, @req will be unreffed.
904 soup_session_queue_message (SoupSession *session, SoupMessage *req,
905 SoupMessageCallbackFn callback, gpointer user_data)
907 g_return_if_fail (SOUP_IS_SESSION (session));
908 g_return_if_fail (SOUP_IS_MESSAGE (req));
910 g_signal_connect (req, "finished",
911 G_CALLBACK (request_finished), session);
913 g_signal_connect (req, "finished",
914 G_CALLBACK (callback), user_data);
916 g_signal_connect_after (req, "finished",
917 G_CALLBACK (final_finished), session);
919 soup_message_add_status_code_handler (req, SOUP_STATUS_UNAUTHORIZED,
920 SOUP_HANDLER_POST_BODY,
921 authorize_handler, session);
922 soup_message_add_status_code_handler (req,
923 SOUP_STATUS_PROXY_UNAUTHORIZED,
924 SOUP_HANDLER_POST_BODY,
925 authorize_handler, session);
927 if (!(soup_message_get_flags (req) & SOUP_MESSAGE_NO_REDIRECT)) {
928 soup_message_add_status_class_handler (
929 req, SOUP_STATUS_CLASS_REDIRECT,
930 SOUP_HANDLER_POST_BODY,
931 redirect_handler, session);
934 queue_message (session, req, FALSE);
938 * soup_session_requeue_message:
939 * @session: a #SoupSession
940 * @req: the message to requeue
942 * This causes @req to be placed back on the queue to be attempted
946 soup_session_requeue_message (SoupSession *session, SoupMessage *req)
948 g_return_if_fail (SOUP_IS_SESSION (session));
949 g_return_if_fail (SOUP_IS_MESSAGE (req));
951 queue_message (session, req, TRUE);
956 * soup_session_send_message:
957 * @session: a #SoupSession
958 * @req: the message to send
960 * Synchronously send @req. This call will not return until the
961 * transfer is finished successfully or there is an unrecoverable
964 * @req is not freed upon return.
966 * Return value: the HTTP status code of the response
969 soup_session_send_message (SoupSession *session, SoupMessage *req)
971 g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
972 g_return_val_if_fail (SOUP_IS_MESSAGE (req), SOUP_STATUS_MALFORMED);
974 /* Balance out the unref that final_finished will do */
977 soup_session_queue_message (session, req, NULL, NULL);
979 while (req->status != SOUP_MESSAGE_STATUS_FINISHED &&
980 !SOUP_STATUS_IS_TRANSPORT_ERROR (req->status_code))
981 g_main_iteration (TRUE);
983 return req->status_code;
987 * soup_session_abort:
988 * @session: the session
990 * Cancels all pending requests in @session.
993 soup_session_abort (SoupSession *session)
995 SoupMessageQueueIter iter;
998 for (msg = soup_message_queue_first (session->priv->queue, &iter); msg; msg = soup_message_queue_next (session->priv->queue, &iter)) {
999 soup_message_queue_remove (session->priv->queue, &iter);
1000 soup_message_cancel (msg);