Add gthread to glib check
[platform/upstream/libsoup.git] / libsoup / soup-session.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * soup-session.c
4  *
5  * Copyright (C) 2000-2003, Ximian, Inc.
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #include <unistd.h>
13 #include <string.h>
14 #include <stdlib.h>
15
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"
22 #include "soup-ssl.h"
23 #include "soup-uri.h"
24
25 typedef struct {
26         SoupUri    *root_uri;
27
28         GSList     *connections;      /* CONTAINS: SoupConnection */
29         guint       num_conns;
30
31         GHashTable *auth_realms;      /* path -> scheme:realm */
32         GHashTable *auths;            /* scheme:realm -> SoupAuth */
33 } SoupSessionHost;
34
35 struct SoupSessionPrivate {
36         SoupUri *proxy_uri;
37         guint max_conns, max_conns_per_host;
38         gboolean use_ntlm;
39
40         char *ssl_ca_file;
41         gpointer ssl_creds;
42
43         GHashTable *hosts; /* SoupUri -> SoupSessionHost */
44         GHashTable *conns; /* SoupConnection -> SoupSessionHost */
45         guint num_conns;
46
47         SoupSessionHost *proxy_host;
48
49         /* Must hold the host_lock before potentially creating a
50          * new SoupSessionHost, or adding/removing a connection.
51          * Must not emit signals or destroy objects while holding it.
52          */
53         GMutex *host_lock;
54 };
55
56 static guint    host_uri_hash  (gconstpointer key);
57 static gboolean host_uri_equal (gconstpointer v1, gconstpointer v2);
58 static void     free_host      (SoupSessionHost *host, SoupSession *session);
59
60 static void queue_message   (SoupSession *session, SoupMessage *msg,
61                              SoupMessageCallbackFn callback,
62                              gpointer user_data);
63 static void requeue_message (SoupSession *session, SoupMessage *msg);
64 static void cancel_message  (SoupSession *session, SoupMessage *msg);
65
66 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
67 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 4
68
69 #define PARENT_TYPE G_TYPE_OBJECT
70 static GObjectClass *parent_class;
71
72 enum {
73         AUTHENTICATE,
74         REAUTHENTICATE,
75         LAST_SIGNAL
76 };
77
78 static guint signals[LAST_SIGNAL] = { 0 };
79
80 enum {
81   PROP_0,
82
83   PROP_PROXY_URI,
84   PROP_MAX_CONNS,
85   PROP_MAX_CONNS_PER_HOST,
86   PROP_USE_NTLM,
87   PROP_SSL_CA_FILE,
88
89   LAST_PROP
90 };
91
92 static void set_property (GObject *object, guint prop_id,
93                           const GValue *value, GParamSpec *pspec);
94 static void get_property (GObject *object, guint prop_id,
95                           GValue *value, GParamSpec *pspec);
96
97 static void
98 init (GObject *object)
99 {
100         SoupSession *session = SOUP_SESSION (object);
101
102         session->priv = g_new0 (SoupSessionPrivate, 1);
103         session->priv->host_lock = g_mutex_new ();
104         session->queue = soup_message_queue_new ();
105         session->priv->hosts = g_hash_table_new (host_uri_hash,
106                                                  host_uri_equal);
107         session->priv->conns = g_hash_table_new (NULL, NULL);
108
109         session->priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
110         session->priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
111 }
112
113 static gboolean
114 foreach_free_host (gpointer key, gpointer host, gpointer session)
115 {
116         free_host (host, session);
117         return TRUE;
118 }
119
120 static void
121 cleanup_hosts (SoupSession *session)
122 {
123         g_hash_table_foreach_remove (session->priv->hosts,
124                                      foreach_free_host, session);
125 }
126
127 static void
128 dispose (GObject *object)
129 {
130         SoupSession *session = SOUP_SESSION (object);
131
132         soup_session_abort (session);
133         cleanup_hosts (session);
134
135         G_OBJECT_CLASS (parent_class)->dispose (object);
136 }
137
138 static void
139 finalize (GObject *object)
140 {
141         SoupSession *session = SOUP_SESSION (object);
142
143         g_mutex_free (session->priv->host_lock);
144         soup_message_queue_destroy (session->queue);
145         g_hash_table_destroy (session->priv->hosts);
146         g_hash_table_destroy (session->priv->conns);
147         g_free (session->priv);
148
149         G_OBJECT_CLASS (parent_class)->finalize (object);
150 }
151
152 static void
153 class_init (GObjectClass *object_class)
154 {
155         SoupSessionClass *session_class = SOUP_SESSION_CLASS (object_class);
156
157         parent_class = g_type_class_ref (PARENT_TYPE);
158
159         /* virtual method definition */
160         session_class->queue_message = queue_message;
161         session_class->requeue_message = requeue_message;
162         session_class->cancel_message = cancel_message;
163
164         /* virtual method override */
165         object_class->dispose = dispose;
166         object_class->finalize = finalize;
167         object_class->set_property = set_property;
168         object_class->get_property = get_property;
169
170         /* signals */
171         signals[AUTHENTICATE] =
172                 g_signal_new ("authenticate",
173                               G_OBJECT_CLASS_TYPE (object_class),
174                               G_SIGNAL_RUN_FIRST,
175                               G_STRUCT_OFFSET (SoupSessionClass, authenticate),
176                               NULL, NULL,
177                               soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
178                               G_TYPE_NONE, 5,
179                               SOUP_TYPE_MESSAGE,
180                               G_TYPE_STRING,
181                               G_TYPE_STRING,
182                               G_TYPE_POINTER,
183                               G_TYPE_POINTER);
184         signals[REAUTHENTICATE] =
185                 g_signal_new ("reauthenticate",
186                               G_OBJECT_CLASS_TYPE (object_class),
187                               G_SIGNAL_RUN_FIRST,
188                               G_STRUCT_OFFSET (SoupSessionClass, reauthenticate),
189                               NULL, NULL,
190                               soup_marshal_NONE__OBJECT_STRING_STRING_POINTER_POINTER,
191                               G_TYPE_NONE, 5,
192                               SOUP_TYPE_MESSAGE,
193                               G_TYPE_STRING,
194                               G_TYPE_STRING,
195                               G_TYPE_POINTER,
196                               G_TYPE_POINTER);
197
198         /* properties */
199         g_object_class_install_property (
200                 object_class, PROP_PROXY_URI,
201                 g_param_spec_pointer (SOUP_SESSION_PROXY_URI,
202                                       "Proxy URI",
203                                       "The HTTP Proxy to use for this session",
204                                       G_PARAM_READWRITE));
205         g_object_class_install_property (
206                 object_class, PROP_MAX_CONNS,
207                 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
208                                   "Max Connection Count",
209                                   "The maximum number of connections that the session can open at once",
210                                   1,
211                                   G_MAXINT,
212                                   10,
213                                   G_PARAM_READWRITE));
214         g_object_class_install_property (
215                 object_class, PROP_MAX_CONNS_PER_HOST,
216                 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
217                                   "Max Per-Host Connection Count",
218                                   "The maximum number of connections that the session can open at once to a given host",
219                                   1,
220                                   G_MAXINT,
221                                   4,
222                                   G_PARAM_READWRITE));
223         g_object_class_install_property (
224                 object_class, PROP_USE_NTLM,
225                 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
226                                       "Use NTLM",
227                                       "Whether or not to use NTLM authentication",
228                                       FALSE,
229                                       G_PARAM_READWRITE));
230         g_object_class_install_property (
231                 object_class, PROP_SSL_CA_FILE,
232                 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
233                                       "SSL CA file",
234                                       "File containing SSL CA certificates",
235                                       NULL,
236                                       G_PARAM_READWRITE));
237 }
238
239 SOUP_MAKE_TYPE (soup_session, SoupSession, class_init, init, PARENT_TYPE)
240
241 static gboolean
242 safe_uri_equal (const SoupUri *a, const SoupUri *b)
243 {
244         if (!a && !b)
245                 return TRUE;
246
247         if ((a && !b) || (b && !a))
248                 return FALSE;
249
250         return soup_uri_equal (a, b);
251 }
252
253 static void
254 set_property (GObject *object, guint prop_id,
255               const GValue *value, GParamSpec *pspec)
256 {
257         SoupSession *session = SOUP_SESSION (object);
258         gpointer pval;
259         gboolean need_abort = FALSE;
260
261         switch (prop_id) {
262         case PROP_PROXY_URI:
263                 pval = g_value_get_pointer (value);
264
265                 if (!safe_uri_equal (session->priv->proxy_uri, pval))
266                         need_abort = TRUE;
267
268                 if (session->priv->proxy_uri)
269                         soup_uri_free (session->priv->proxy_uri);
270
271                 session->priv->proxy_uri = pval ? soup_uri_copy (pval) : NULL;
272
273                 if (need_abort) {
274                         soup_session_abort (session);
275                         cleanup_hosts (session);
276                 }
277
278                 break;
279         case PROP_MAX_CONNS:
280                 session->priv->max_conns = g_value_get_int (value);
281                 break;
282         case PROP_MAX_CONNS_PER_HOST:
283                 session->priv->max_conns_per_host = g_value_get_int (value);
284                 break;
285         case PROP_USE_NTLM:
286                 session->priv->use_ntlm = g_value_get_boolean (value);
287                 break;
288         case PROP_SSL_CA_FILE:
289                 g_free (session->priv->ssl_ca_file);
290                 session->priv->ssl_ca_file = g_strdup (g_value_get_string (value));
291                 break;
292         default:
293                 break;
294         }
295 }
296
297 static void
298 get_property (GObject *object, guint prop_id,
299               GValue *value, GParamSpec *pspec)
300 {
301         SoupSession *session = SOUP_SESSION (object);
302
303         switch (prop_id) {
304         case PROP_PROXY_URI:
305                 g_value_set_pointer (value, session->priv->proxy_uri ?
306                                      soup_uri_copy (session->priv->proxy_uri) :
307                                      NULL);
308                 break;
309         case PROP_MAX_CONNS:
310                 g_value_set_int (value, session->priv->max_conns);
311                 break;
312         case PROP_MAX_CONNS_PER_HOST:
313                 g_value_set_int (value, session->priv->max_conns_per_host);
314                 break;
315         case PROP_USE_NTLM:
316                 g_value_set_boolean (value, session->priv->use_ntlm);
317                 break;
318         case PROP_SSL_CA_FILE:
319                 g_value_set_string (value, session->priv->ssl_ca_file);
320                 break;
321         default:
322                 break;
323         }
324 }
325
326
327 /* Hosts */
328 static guint
329 host_uri_hash (gconstpointer key)
330 {
331         const SoupUri *uri = key;
332
333         return (uri->protocol << 16) + uri->port + g_str_hash (uri->host);
334 }
335
336 static gboolean
337 host_uri_equal (gconstpointer v1, gconstpointer v2)
338 {
339         const SoupUri *one = v1;
340         const SoupUri *two = v2;
341
342         if (one->protocol != two->protocol)
343                 return FALSE;
344         if (one->port != two->port)
345                 return FALSE;
346
347         return strcmp (one->host, two->host) == 0;
348 }
349
350 static SoupSessionHost *
351 soup_session_host_new (SoupSession *session, const SoupUri *source_uri)
352 {
353         SoupSessionHost *host;
354
355         host = g_new0 (SoupSessionHost, 1);
356         host->root_uri = soup_uri_copy_root (source_uri);
357
358         if (host->root_uri->protocol == SOUP_PROTOCOL_HTTPS &&
359             !session->priv->ssl_creds) {
360                 session->priv->ssl_creds =
361                         soup_ssl_get_client_credentials (session->priv->ssl_ca_file);
362         }
363
364         return host;
365 }
366
367 /* Note: get_host_for_message doesn't lock the host_lock. The caller
368  * must do it itself if there's a chance the host doesn't already
369  * exist.
370  */
371 static SoupSessionHost *
372 get_host_for_message (SoupSession *session, SoupMessage *msg)
373 {
374         SoupSessionHost *host;
375         const SoupUri *source = soup_message_get_uri (msg);
376
377         host = g_hash_table_lookup (session->priv->hosts, source);
378         if (host)
379                 return host;
380
381         host = soup_session_host_new (session, source);
382         g_hash_table_insert (session->priv->hosts, host->root_uri, host);
383
384         return host;
385 }
386
387 /* Note: get_proxy_host doesn't lock the host_lock. The caller must do
388  * it itself if there's a chance the host doesn't already exist.
389  */
390 static SoupSessionHost *
391 get_proxy_host (SoupSession *session)
392 {
393         if (session->priv->proxy_host || !session->priv->proxy_uri)
394                 return session->priv->proxy_host;
395
396         session->priv->proxy_host =
397                 soup_session_host_new (session, session->priv->proxy_uri);
398         return session->priv->proxy_host;
399 }
400
401 static void
402 free_realm (gpointer path, gpointer scheme_realm, gpointer data)
403 {
404         g_free (path);
405         g_free (scheme_realm);
406 }
407
408 static void
409 free_auth (gpointer scheme_realm, gpointer auth, gpointer data)
410 {
411         g_free (scheme_realm);
412         g_object_unref (auth);
413 }
414
415 static void
416 free_host (SoupSessionHost *host, SoupSession *session)
417 {
418         while (host->connections) {
419                 SoupConnection *conn = host->connections->data;
420
421                 host->connections = g_slist_remove (host->connections, conn);
422                 soup_connection_disconnect (conn);
423         }
424
425         if (host->auth_realms) {
426                 g_hash_table_foreach (host->auth_realms, free_realm, NULL);
427                 g_hash_table_destroy (host->auth_realms);
428         }
429         if (host->auths) {
430                 g_hash_table_foreach (host->auths, free_auth, NULL);
431                 g_hash_table_destroy (host->auths);
432         }
433
434         soup_uri_free (host->root_uri);
435         g_free (host);
436 }       
437
438 /* Authentication */
439
440 static SoupAuth *
441 lookup_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
442 {
443         SoupSessionHost *host;
444         char *path, *dir;
445         const char *realm, *const_path;
446
447         if (proxy) {
448                 host = get_proxy_host (session);
449                 const_path = "/";
450         } else {
451                 host = get_host_for_message (session, msg);
452                 const_path = soup_message_get_uri (msg)->path;
453         }
454         g_return_val_if_fail (host != NULL, NULL);
455
456         if (!host->auth_realms)
457                 return NULL;
458
459         path = g_strdup (const_path);
460         dir = path;
461         do {
462                 realm = g_hash_table_lookup (host->auth_realms, path);
463                 if (realm)
464                         break;
465
466                 dir = strrchr (path, '/');
467                 if (dir)
468                         *dir = '\0';
469         } while (dir);
470
471         g_free (path);
472         if (realm)
473                 return g_hash_table_lookup (host->auths, realm);
474         else
475                 return NULL;
476 }
477
478 static void
479 invalidate_auth (SoupSessionHost *host, SoupAuth *auth)
480 {
481         char *realm;
482         gpointer key, value;
483
484         realm = g_strdup_printf ("%s:%s",
485                                  soup_auth_get_scheme_name (auth),
486                                  soup_auth_get_realm (auth));
487
488         if (g_hash_table_lookup_extended (host->auths, realm, &key, &value) &&
489             auth == (SoupAuth *)value) {
490                 g_hash_table_remove (host->auths, realm);
491                 g_free (key);
492                 g_object_unref (auth);
493         }
494         g_free (realm);
495 }
496
497 static gboolean
498 authenticate_auth (SoupSession *session, SoupAuth *auth,
499                    SoupMessage *msg, gboolean prior_auth_failed,
500                    gboolean proxy)
501 {
502         const SoupUri *uri;
503         char *username = NULL, *password = NULL;
504
505         if (proxy)
506                 uri = session->priv->proxy_uri;
507         else
508                 uri = soup_message_get_uri (msg);
509
510         if (uri->passwd && !prior_auth_failed) {
511                 soup_auth_authenticate (auth, uri->user, uri->passwd);
512                 return TRUE;
513         }
514
515         g_signal_emit (session, signals[prior_auth_failed ? REAUTHENTICATE : AUTHENTICATE], 0,
516                        msg, soup_auth_get_scheme_name (auth),
517                        soup_auth_get_realm (auth),
518                        &username, &password);
519         if (username || password)
520                 soup_auth_authenticate (auth, username, password);
521         if (username)
522                 g_free (username);
523         if (password) {
524                 memset (password, 0, strlen (password));
525                 g_free (password);
526         }
527
528         return soup_auth_is_authenticated (auth);
529 }
530
531 static gboolean
532 update_auth_internal (SoupSession *session, SoupMessage *msg,
533                       const GSList *headers, gboolean proxy,
534                       gboolean got_unauthorized)
535 {
536         SoupSessionHost *host;
537         SoupAuth *new_auth, *prior_auth, *old_auth;
538         gpointer old_path, old_realm;
539         const SoupUri *msg_uri;
540         const char *path;
541         char *realm;
542         GSList *pspace, *p;
543         gboolean prior_auth_failed = FALSE;
544
545         if (proxy)
546                 host = get_proxy_host (session);
547         else
548                 host = get_host_for_message (session, msg);
549
550         g_return_val_if_fail (host != NULL, FALSE);
551
552         /* Try to construct a new auth from the headers; if we can't,
553          * there's no way we'll be able to authenticate.
554          */
555         msg_uri = soup_message_get_uri (msg);
556         new_auth = soup_auth_new_from_header_list (headers);
557         if (!new_auth)
558                 return FALSE;
559
560         /* See if this auth is the same auth we used last time */
561         prior_auth = lookup_auth (session, msg, proxy);
562         if (prior_auth &&
563             G_OBJECT_TYPE (prior_auth) == G_OBJECT_TYPE (new_auth) &&
564             !strcmp (soup_auth_get_realm (prior_auth),
565                      soup_auth_get_realm (new_auth))) {
566                 if (!got_unauthorized) {
567                         /* The user is just trying to preauthenticate
568                          * using information we already have, so
569                          * there's nothing more that needs to be done.
570                          */
571                         g_object_unref (new_auth);
572                         return TRUE;
573                 }
574
575                 /* The server didn't like the username/password we
576                  * provided before. Invalidate it and note this fact.
577                  */
578                 invalidate_auth (host, prior_auth);
579                 prior_auth_failed = TRUE;
580         }
581
582         if (!host->auth_realms) {
583                 host->auth_realms = g_hash_table_new (g_str_hash, g_str_equal);
584                 host->auths = g_hash_table_new (g_str_hash, g_str_equal);
585         }
586
587         /* Record where this auth realm is used */
588         realm = g_strdup_printf ("%s:%s",
589                                  soup_auth_get_scheme_name (new_auth),
590                                  soup_auth_get_realm (new_auth));
591
592         /* 
593          * RFC 2617 is somewhat unclear about the scope of protection
594          * spaces with regard to proxies.  The only mention of it is
595          * as an aside in section 3.2.1, where it is defining the fields
596          * of a Digest challenge and says that the protection space is
597          * always the entire proxy.  Is this the case for all authentication
598          * schemes or just Digest?  Who knows, but we're assuming all.
599          */
600         if (proxy)
601                 pspace = g_slist_prepend (NULL, g_strdup (""));
602         else
603                 pspace = soup_auth_get_protection_space (new_auth, msg_uri);
604
605         for (p = pspace; p; p = p->next) {
606                 path = p->data;
607                 if (g_hash_table_lookup_extended (host->auth_realms, path,
608                                                   &old_path, &old_realm)) {
609                         g_hash_table_remove (host->auth_realms, old_path);
610                         g_free (old_path);
611                         g_free (old_realm);
612                 }
613
614                 g_hash_table_insert (host->auth_realms,
615                                      g_strdup (path), g_strdup (realm));
616         }
617         soup_auth_free_protection_space (new_auth, pspace);
618
619         /* Now, make sure the auth is recorded. (If there's a
620          * pre-existing auth, we keep that rather than the new one,
621          * since the old one might already be authenticated.)
622          */
623         old_auth = g_hash_table_lookup (host->auths, realm);
624         if (old_auth) {
625                 g_free (realm);
626                 g_object_unref (new_auth);
627                 new_auth = old_auth;
628         } else 
629                 g_hash_table_insert (host->auths, realm, new_auth);
630
631         /* If we need to authenticate, try to do it. */
632         if (!soup_auth_is_authenticated (new_auth)) {
633                 return authenticate_auth (session, new_auth,
634                                           msg, prior_auth_failed, proxy);
635         }
636
637         /* Otherwise we're good. */
638         return TRUE;
639 }
640
641 static void
642 connection_authenticate (SoupConnection *conn, SoupMessage *msg,
643                          const char *auth_type, const char *auth_realm,
644                          char **username, char **password, gpointer session)
645 {
646         g_signal_emit (session, signals[AUTHENTICATE], 0,
647                        msg, auth_type, auth_realm, username, password);
648 }
649
650 static void
651 connection_reauthenticate (SoupConnection *conn, SoupMessage *msg,
652                            const char *auth_type, const char *auth_realm,
653                            char **username, char **password,
654                            gpointer user_data)
655 {
656         g_signal_emit (conn, signals[REAUTHENTICATE], 0,
657                        msg, auth_type, auth_realm, username, password);
658 }
659
660
661 static void
662 authorize_handler (SoupMessage *msg, gpointer user_data)
663 {
664         SoupSession *session = user_data;
665         const GSList *headers;
666         gboolean proxy;
667
668         if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
669                 headers = soup_message_get_header_list (msg->response_headers,
670                                                         "Proxy-Authenticate");
671                 proxy = TRUE;
672         } else {
673                 headers = soup_message_get_header_list (msg->response_headers,
674                                                         "WWW-Authenticate");
675                 proxy = FALSE;
676         }
677         if (!headers)
678                 return;
679
680         if (update_auth_internal (session, msg, headers, proxy, TRUE))
681                 soup_session_requeue_message (session, msg);
682 }
683
684 static void
685 redirect_handler (SoupMessage *msg, gpointer user_data)
686 {
687         SoupSession *session = user_data;
688         const char *new_loc;
689         SoupUri *new_uri;
690
691         new_loc = soup_message_get_header (msg->response_headers, "Location");
692         if (!new_loc)
693                 return;
694         new_uri = soup_uri_new (new_loc);
695         if (!new_uri) {
696                 soup_message_set_status_full (msg,
697                                               SOUP_STATUS_MALFORMED,
698                                               "Invalid Redirect URL");
699                 return;
700         }
701
702         soup_message_set_uri (msg, new_uri);
703         soup_uri_free (new_uri);
704
705         soup_session_requeue_message (session, msg);
706 }
707
708 static void
709 add_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
710 {
711         const char *header = proxy ? "Proxy-Authorization" : "Authorization";
712         SoupAuth *auth;
713         char *token;
714
715         soup_message_remove_header (msg->request_headers, header);
716
717         auth = lookup_auth (session, msg, proxy);
718         if (!auth)
719                 return;
720         if (!soup_auth_is_authenticated (auth) &&
721             !authenticate_auth (session, auth, msg, FALSE, proxy))
722                 return;
723
724         token = soup_auth_get_authorization (auth, msg);
725         if (token) {
726                 soup_message_add_header (msg->request_headers, header, token);
727                 g_free (token);
728         }
729 }
730
731 void
732 soup_session_send_message_via (SoupSession *session, SoupMessage *msg,
733                                SoupConnection *conn)
734 {
735         msg->status = SOUP_MESSAGE_STATUS_RUNNING;
736
737         add_auth (session, msg, FALSE);
738         if (session->priv->proxy_uri)
739                 add_auth (session, msg, TRUE);
740         soup_connection_send_request (conn, msg);
741 }
742
743 static void
744 find_oldest_connection (gpointer key, gpointer host, gpointer data)
745 {
746         SoupConnection *conn = key, **oldest = data;
747
748         /* Don't prune a connection that is currently in use, or
749          * hasn't been used yet.
750          */
751         if (soup_connection_is_in_use (conn) ||
752             soup_connection_last_used (conn) == 0)
753                 return;
754
755         if (!*oldest || (soup_connection_last_used (conn) <
756                          soup_connection_last_used (*oldest)))
757                 *oldest = conn;
758 }
759
760 /**
761  * soup_session_try_prune_connection:
762  * @session: a #SoupSession
763  *
764  * Finds the least-recently-used idle connection in @session and closes
765  * it.
766  *
767  * Return value: %TRUE if a connection was closed, %FALSE if there are
768  * no idle connections.
769  **/
770 gboolean
771 soup_session_try_prune_connection (SoupSession *session)
772 {
773         SoupConnection *oldest = NULL;
774
775         g_mutex_lock (session->priv->host_lock);
776         g_hash_table_foreach (session->priv->conns, find_oldest_connection,
777                               &oldest);
778         if (oldest) {
779                 /* Ref the connection before unlocking the mutex in
780                  * case someone else tries to prune it too.
781                  */
782                 g_object_ref (oldest);
783                 g_mutex_unlock (session->priv->host_lock);
784                 soup_connection_disconnect (oldest);
785                 g_object_unref (oldest);
786                 return TRUE;
787         } else {
788                 g_mutex_unlock (session->priv->host_lock);
789                 return FALSE;
790         }
791 }
792
793 static void
794 connection_disconnected (SoupConnection *conn, gpointer user_data)
795 {
796         SoupSession *session = user_data;
797         SoupSessionHost *host;
798
799         g_mutex_lock (session->priv->host_lock);
800
801         host = g_hash_table_lookup (session->priv->conns, conn);
802         if (host) {
803                 g_hash_table_remove (session->priv->conns, conn);
804                 host->connections = g_slist_remove (host->connections, conn);
805                 host->num_conns--;
806         }
807
808         g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
809         session->priv->num_conns--;
810
811         g_mutex_unlock (session->priv->host_lock);
812         g_object_unref (conn);
813 }
814
815 static void
816 connect_result (SoupConnection *conn, guint status, gpointer user_data)
817 {
818         SoupSession *session = user_data;
819         SoupSessionHost *host;
820         SoupMessageQueueIter iter;
821         SoupMessage *msg;
822
823         g_mutex_lock (session->priv->host_lock);
824
825         host = g_hash_table_lookup (session->priv->conns, conn);
826         if (!host) {
827                 g_mutex_unlock (session->priv->host_lock);
828                 return;
829         }
830
831         if (status == SOUP_STATUS_OK) {
832                 host->connections = g_slist_prepend (host->connections, conn);
833                 g_mutex_unlock (session->priv->host_lock);
834                 return;
835         }
836
837         /* The connection failed. */
838         g_mutex_unlock (session->priv->host_lock);
839         connection_disconnected (conn, session);
840
841         if (host->connections) {
842                 /* Something went wrong this time, but we have at
843                  * least one open connection to this host. So just
844                  * leave the message in the queue so it can use that
845                  * connection once it's free.
846                  */
847                 return;
848         }
849
850         /* It's hopeless. Cancel everything that was waiting for this host. */
851         for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
852                 if (get_host_for_message (session, msg) == host) {
853                         soup_message_set_status (msg, status);
854                         soup_session_cancel_message (session, msg);
855                 }
856         }
857 }
858
859 /**
860  * soup_session_get_connection:
861  * @session: a #SoupSession
862  * @msg: a #SoupMessage
863  * @try_pruning: on return, whether or not to try pruning a connection
864  * @is_new: on return, %TRUE if the returned connection is new and not
865  * yet connected
866  * 
867  * Tries to find or create a connection for @msg. If there is an idle
868  * connection to the relevant host available, then it will be returned
869  * (with *@is_new set to %FALSE). Otherwise, if it is possible to
870  * create a new connection, one will be created and returned, with
871  * *@is_new set to %TRUE.
872  *
873  * If no connection can be made, it will return %NULL. If @session has
874  * the maximum number of open connections open, but does not have the
875  * maximum number of per-host connections open to the relevant host, then
876  * *@try_pruning will be set to %TRUE. In this case, the caller can
877  * call soup_session_try_prune_connection() to close an idle connection,
878  * and then try soup_session_get_connection() again. (If calling
879  * soup_session_try_prune_connection() wouldn't help, then *@try_pruning
880  * is left untouched; it is NOT set to %FALSE.)
881  *
882  * Return value: a #SoupConnection, or %NULL
883  **/
884 SoupConnection *
885 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
886                              gboolean *try_pruning, gboolean *is_new)
887 {
888         SoupConnection *conn;
889         SoupSessionHost *host;
890         GSList *conns;
891
892         g_mutex_lock (session->priv->host_lock);
893
894         host = get_host_for_message (session, msg);
895         for (conns = host->connections; conns; conns = conns->next) {
896                 if (!soup_connection_is_in_use (conns->data)) {
897                         soup_connection_reserve (conns->data);
898                         g_mutex_unlock (session->priv->host_lock);
899                         *is_new = FALSE;
900                         return conns->data;
901                 }
902         }
903
904         if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING) {
905                 /* We already started a connection for this
906                  * message, so don't start another one.
907                  */
908                 g_mutex_unlock (session->priv->host_lock);
909                 return NULL;
910         }
911
912         if (host->num_conns >= session->priv->max_conns_per_host) {
913                 g_mutex_unlock (session->priv->host_lock);
914                 return NULL;
915         }
916
917         if (session->priv->num_conns >= session->priv->max_conns) {
918                 *try_pruning = TRUE;
919                 g_mutex_unlock (session->priv->host_lock);
920                 return NULL;
921         }
922
923         /* Make sure session->priv->proxy_host gets set now while
924          * we have the host_lock.
925          */
926         if (session->priv->proxy_uri)
927                 get_proxy_host (session);
928
929         conn = g_object_new (
930                 (session->priv->use_ntlm ?
931                  SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
932                 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
933                 SOUP_CONNECTION_PROXY_URI, session->priv->proxy_uri,
934                 SOUP_CONNECTION_SSL_CREDENTIALS, session->priv->ssl_creds,
935                 NULL);
936         g_signal_connect (conn, "connect_result",
937                           G_CALLBACK (connect_result),
938                           session);
939         g_signal_connect (conn, "disconnected",
940                           G_CALLBACK (connection_disconnected),
941                           session);
942         g_signal_connect (conn, "authenticate",
943                           G_CALLBACK (connection_authenticate),
944                           session);
945         g_signal_connect (conn, "reauthenticate",
946                           G_CALLBACK (connection_reauthenticate),
947                           session);
948
949         g_hash_table_insert (session->priv->conns, conn, host);
950
951         /* We increment the connection counts so it counts against the
952          * totals, but we don't add it to the host's connection list
953          * yet, since it's not ready for use.
954          */
955         session->priv->num_conns++;
956         host->num_conns++;
957
958         /* Mark the request as connecting, so we don't try to open
959          * another new connection for it while waiting for this one.
960          */
961         msg->status = SOUP_MESSAGE_STATUS_CONNECTING;
962
963         g_mutex_unlock (session->priv->host_lock);
964         *is_new = TRUE;
965         return conn;
966 }
967
968 static void
969 message_finished (SoupMessage *msg, gpointer user_data)
970 {
971         SoupSession *session = user_data;
972
973         if (!SOUP_MESSAGE_IS_STARTING (msg)) {
974                 soup_message_queue_remove_message (session->queue, msg);
975                 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
976         }
977 }
978
979 static void
980 queue_message (SoupSession *session, SoupMessage *msg,
981                SoupMessageCallbackFn callback, gpointer user_data)
982 {
983         g_signal_connect_after (msg, "finished",
984                                 G_CALLBACK (message_finished), session);
985
986         soup_message_add_status_code_handler  (msg, SOUP_STATUS_UNAUTHORIZED,
987                                                SOUP_HANDLER_POST_BODY,
988                                                authorize_handler, session);
989         soup_message_add_status_code_handler  (msg,
990                                                SOUP_STATUS_PROXY_UNAUTHORIZED,
991                                                SOUP_HANDLER_POST_BODY,
992                                                authorize_handler, session);
993
994         if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
995                 soup_message_add_status_class_handler (
996                         msg, SOUP_STATUS_CLASS_REDIRECT,
997                         SOUP_HANDLER_POST_BODY,
998                         redirect_handler, session);
999         }
1000
1001         msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1002         soup_message_queue_append (session->queue, msg);
1003 }
1004
1005 /**
1006  * soup_session_queue_message:
1007  * @session: a #SoupSession
1008  * @msg: the message to queue
1009  * @callback: a #SoupMessageCallbackFn which will be called after the
1010  * message completes or when an unrecoverable error occurs.
1011  * @user_data: a pointer passed to @callback.
1012  * 
1013  * Queues the message @msg for sending. All messages are processed
1014  * while the glib main loop runs. If @msg has been processed before,
1015  * any resources related to the time it was last sent are freed.
1016  *
1017  * Upon message completion, the callback specified in @callback will
1018  * be invoked. If after returning from this callback the message has
1019  * not been requeued, @msg will be unreffed.
1020  */
1021 void
1022 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1023                             SoupMessageCallbackFn callback, gpointer user_data)
1024 {
1025         g_return_if_fail (SOUP_IS_SESSION (session));
1026         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1027
1028         SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1029                                                          callback, user_data);
1030 }
1031
1032 static void
1033 requeue_message (SoupSession *session, SoupMessage *msg)
1034 {
1035         msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1036 }
1037
1038 /**
1039  * soup_session_requeue_message:
1040  * @session: a #SoupSession
1041  * @msg: the message to requeue
1042  *
1043  * This causes @msg to be placed back on the queue to be attempted
1044  * again.
1045  **/
1046 void
1047 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
1048 {
1049         g_return_if_fail (SOUP_IS_SESSION (session));
1050         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1051
1052         SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
1053 }
1054
1055
1056 /**
1057  * soup_session_send_message:
1058  * @session: a #SoupSession
1059  * @msg: the message to send
1060  * 
1061  * Synchronously send @msg. This call will not return until the
1062  * transfer is finished successfully or there is an unrecoverable
1063  * error.
1064  *
1065  * @msg is not freed upon return.
1066  *
1067  * Return value: the HTTP status code of the response
1068  */
1069 guint
1070 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1071 {
1072         g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1073         g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1074
1075         return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1076 }
1077
1078
1079 static void
1080 cancel_message (SoupSession *session, SoupMessage *msg)
1081 {
1082         soup_message_queue_remove_message (session->queue, msg);
1083         soup_message_finished (msg);
1084 }
1085
1086 /**
1087  * soup_session_cancel_message:
1088  * @session: a #SoupSession
1089  * @msg: the message to cancel
1090  *
1091  * Causes @session to immediately finish processing @msg. You should
1092  * set a status code on @msg with soup_message_set_status() before
1093  * calling this function.
1094  **/
1095 void
1096 soup_session_cancel_message (SoupSession *session, SoupMessage *msg)
1097 {
1098         g_return_if_fail (SOUP_IS_SESSION (session));
1099         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1100
1101         SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg);
1102 }
1103
1104 /**
1105  * soup_session_abort:
1106  * @session: the session
1107  *
1108  * Cancels all pending requests in @session.
1109  **/
1110 void
1111 soup_session_abort (SoupSession *session)
1112 {
1113         SoupMessageQueueIter iter;
1114         SoupMessage *msg;
1115
1116         g_return_if_fail (SOUP_IS_SESSION (session));
1117
1118         for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
1119                 soup_message_set_status (msg, SOUP_STATUS_CANCELLED);
1120                 soup_session_cancel_message (session, msg);
1121         }
1122 }