Merge libsoup-2.4 branch to trunk
[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-auth-basic.h"
18 #include "soup-auth-digest.h"
19 #include "soup-auth-manager.h"
20 #include "soup-connection.h"
21 #include "soup-connection-ntlm.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-private.h"
27 #include "soup-socket.h"
28 #include "soup-ssl.h"
29 #include "soup-uri.h"
30
31 /**
32  * SECTION:soup-session
33  * @short_description: Soup session state object
34  *
35  **/
36
37 typedef struct {
38         SoupURI    *root_uri;
39
40         GSList     *connections;      /* CONTAINS: SoupConnection */
41         guint       num_conns;
42
43         GHashTable *auth_realms;      /* path -> scheme:realm */
44         GHashTable *auths;            /* scheme:realm -> SoupAuth */
45 } SoupSessionHost;
46
47 typedef struct {
48         SoupURI *proxy_uri;
49         SoupAuth *proxy_auth;
50
51         guint max_conns, max_conns_per_host;
52         gboolean use_ntlm;
53
54         char *ssl_ca_file;
55         SoupSSLCredentials *ssl_creds;
56
57         SoupMessageQueue *queue;
58
59         SoupAuthManager *auth_manager;
60
61         GHashTable *hosts; /* SoupURI -> SoupSessionHost */
62         GHashTable *conns; /* SoupConnection -> SoupSessionHost */
63         guint num_conns;
64
65         /* Must hold the host_lock before potentially creating a
66          * new SoupSessionHost, or adding/removing a connection.
67          * Must not emit signals or destroy objects while holding it.
68          */
69         GMutex *host_lock;
70
71         GMainContext *async_context;
72
73         /* Holds the timeout value for the connection, when
74            no response is received.
75         */
76         guint timeout;
77 } SoupSessionPrivate;
78 #define SOUP_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SESSION, SoupSessionPrivate))
79
80 static void     free_host      (SoupSessionHost *host);
81
82 static void queue_message   (SoupSession *session, SoupMessage *msg,
83                              SoupSessionCallback callback, gpointer user_data);
84 static void requeue_message (SoupSession *session, SoupMessage *msg);
85 static void cancel_message  (SoupSession *session, SoupMessage *msg,
86                              guint status_code);
87
88 /* temporary until we fix this to index hosts by SoupAddress */
89 extern guint     soup_uri_host_hash  (gconstpointer  key);
90 extern gboolean  soup_uri_host_equal (gconstpointer  v1,
91                                       gconstpointer  v2);
92 extern SoupURI  *soup_uri_copy_root  (SoupURI *uri);
93
94 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
95 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 4
96
97 G_DEFINE_TYPE (SoupSession, soup_session, G_TYPE_OBJECT)
98
99 enum {
100         REQUEST_STARTED,
101         AUTHENTICATE,
102         LAST_SIGNAL
103 };
104
105 static guint signals[LAST_SIGNAL] = { 0 };
106
107 enum {
108         PROP_0,
109
110         PROP_PROXY_URI,
111         PROP_MAX_CONNS,
112         PROP_MAX_CONNS_PER_HOST,
113         PROP_USE_NTLM,
114         PROP_SSL_CA_FILE,
115         PROP_ASYNC_CONTEXT,
116         PROP_TIMEOUT,
117
118         LAST_PROP
119 };
120
121 static void set_property (GObject *object, guint prop_id,
122                           const GValue *value, GParamSpec *pspec);
123 static void get_property (GObject *object, guint prop_id,
124                           GValue *value, GParamSpec *pspec);
125
126 static void
127 soup_session_init (SoupSession *session)
128 {
129         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
130
131         priv->queue = soup_message_queue_new ();
132
133         priv->host_lock = g_mutex_new ();
134         priv->hosts = g_hash_table_new (soup_uri_host_hash,
135                                         soup_uri_host_equal);
136         priv->conns = g_hash_table_new (NULL, NULL);
137
138         priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
139         priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
140
141         priv->timeout = 0;
142
143         priv->auth_manager = soup_auth_manager_new (session);
144         soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_BASIC);
145         soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_DIGEST);
146 }
147
148 static gboolean
149 foreach_free_host (gpointer key, gpointer host, gpointer data)
150 {
151         free_host (host);
152         return TRUE;
153 }
154
155 static void
156 cleanup_hosts (SoupSessionPrivate *priv)
157 {
158         GHashTable *old_hosts;
159
160         g_mutex_lock (priv->host_lock);
161         old_hosts = priv->hosts;
162         priv->hosts = g_hash_table_new (soup_uri_host_hash,
163                                         soup_uri_host_equal);
164         g_mutex_unlock (priv->host_lock);
165
166         g_hash_table_foreach_remove (old_hosts, foreach_free_host, NULL);
167         g_hash_table_destroy (old_hosts);
168 }
169
170 static void
171 dispose (GObject *object)
172 {
173         SoupSession *session = SOUP_SESSION (object);
174         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
175
176         soup_session_abort (session);
177         cleanup_hosts (priv);
178
179         G_OBJECT_CLASS (soup_session_parent_class)->dispose (object);
180 }
181
182 static void
183 finalize (GObject *object)
184 {
185         SoupSession *session = SOUP_SESSION (object);
186         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
187
188         soup_message_queue_destroy (priv->queue);
189
190         g_mutex_free (priv->host_lock);
191         g_hash_table_destroy (priv->hosts);
192         g_hash_table_destroy (priv->conns);
193
194         soup_auth_manager_free (priv->auth_manager);
195
196         if (priv->proxy_uri)
197                 soup_uri_free (priv->proxy_uri);
198
199         if (priv->ssl_creds)
200                 soup_ssl_free_client_credentials (priv->ssl_creds);
201
202         if (priv->async_context)
203                 g_main_context_unref (priv->async_context);
204
205         G_OBJECT_CLASS (soup_session_parent_class)->finalize (object);
206 }
207
208 static void
209 soup_session_class_init (SoupSessionClass *session_class)
210 {
211         GObjectClass *object_class = G_OBJECT_CLASS (session_class);
212
213         g_type_class_add_private (session_class, sizeof (SoupSessionPrivate));
214
215         /* virtual method definition */
216         session_class->queue_message = queue_message;
217         session_class->requeue_message = requeue_message;
218         session_class->cancel_message = cancel_message;
219
220         /* virtual method override */
221         object_class->dispose = dispose;
222         object_class->finalize = finalize;
223         object_class->set_property = set_property;
224         object_class->get_property = get_property;
225
226         /* signals */
227
228         /**
229          * SoupSession::request-started:
230          * @session: the session
231          * @msg: the request being sent
232          * @socket: the socket the request is being sent on
233          *
234          * Emitted just before a request is sent.
235          **/
236         signals[REQUEST_STARTED] =
237                 g_signal_new ("request-started",
238                               G_OBJECT_CLASS_TYPE (object_class),
239                               G_SIGNAL_RUN_FIRST,
240                               G_STRUCT_OFFSET (SoupSessionClass, request_started),
241                               NULL, NULL,
242                               soup_marshal_NONE__OBJECT_OBJECT,
243                               G_TYPE_NONE, 2,
244                               SOUP_TYPE_MESSAGE,
245                               SOUP_TYPE_SOCKET);
246
247         /**
248          * SoupSession::authenticate:
249          * @session: the session
250          * @msg: the #SoupMessage being sent
251          * @auth: the #SoupAuth to authenticate
252          * @retrying: %TRUE if this is the second (or later) attempt
253          *
254          * Emitted when the session requires authentication. If
255          * credentials are available call soup_auth_authenticate() on
256          * @auth. If these credentials fail, the signal will be
257          * emitted again, with @retrying set to %TRUE, which will
258          * continue until you return without calling
259          * soup_auth_authenticate() on @auth.
260          **/
261         signals[AUTHENTICATE] =
262                 g_signal_new ("authenticate",
263                               G_OBJECT_CLASS_TYPE (object_class),
264                               G_SIGNAL_RUN_FIRST,
265                               G_STRUCT_OFFSET (SoupSessionClass, authenticate),
266                               NULL, NULL,
267                               soup_marshal_NONE__OBJECT_OBJECT_BOOLEAN,
268                               G_TYPE_NONE, 3,
269                               SOUP_TYPE_MESSAGE,
270                               SOUP_TYPE_AUTH,
271                               G_TYPE_BOOLEAN);
272
273         /* properties */
274         g_object_class_install_property (
275                 object_class, PROP_PROXY_URI,
276                 g_param_spec_boxed (SOUP_SESSION_PROXY_URI,
277                                     "Proxy URI",
278                                     "The HTTP Proxy to use for this session",
279                                     SOUP_TYPE_URI,
280                                     G_PARAM_READWRITE));
281         g_object_class_install_property (
282                 object_class, PROP_MAX_CONNS,
283                 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
284                                   "Max Connection Count",
285                                   "The maximum number of connections that the session can open at once",
286                                   1,
287                                   G_MAXINT,
288                                   10,
289                                   G_PARAM_READWRITE));
290         g_object_class_install_property (
291                 object_class, PROP_MAX_CONNS_PER_HOST,
292                 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
293                                   "Max Per-Host Connection Count",
294                                   "The maximum number of connections that the session can open at once to a given host",
295                                   1,
296                                   G_MAXINT,
297                                   2,
298                                   G_PARAM_READWRITE));
299         g_object_class_install_property (
300                 object_class, PROP_USE_NTLM,
301                 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
302                                       "Use NTLM",
303                                       "Whether or not to use NTLM authentication",
304                                       FALSE,
305                                       G_PARAM_READWRITE));
306         g_object_class_install_property (
307                 object_class, PROP_SSL_CA_FILE,
308                 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
309                                      "SSL CA file",
310                                      "File containing SSL CA certificates",
311                                      NULL,
312                                      G_PARAM_READWRITE));
313         g_object_class_install_property (
314                 object_class, PROP_ASYNC_CONTEXT,
315                 g_param_spec_pointer (SOUP_SESSION_ASYNC_CONTEXT,
316                                       "Async GMainContext",
317                                       "The GMainContext to dispatch async I/O in",
318                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
319         g_object_class_install_property (
320                 object_class, PROP_TIMEOUT,
321                 g_param_spec_uint (SOUP_SESSION_TIMEOUT,
322                                    "Timeout value",
323                                    "Value in seconds to timeout a blocking I/O",
324                                    0, G_MAXUINT, 0,
325                                    G_PARAM_READWRITE));
326 }
327
328 static gboolean
329 safe_uri_equal (SoupURI *a, SoupURI *b)
330 {
331         if (!a && !b)
332                 return TRUE;
333
334         if ((a && !b) || (b && !a))
335                 return FALSE;
336
337         return soup_uri_equal (a, b);
338 }
339
340 static gboolean
341 safe_str_equal (const char *a, const char *b)
342 {
343         if (!a && !b)
344                 return TRUE;
345
346         if ((a && !b) || (b && !a))
347                 return FALSE;
348
349         return strcmp (a, b) == 0;
350 }
351
352 static void
353 set_property (GObject *object, guint prop_id,
354               const GValue *value, GParamSpec *pspec)
355 {
356         SoupSession *session = SOUP_SESSION (object);
357         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
358         SoupURI *uri;
359         gboolean need_abort = FALSE;
360         gboolean ca_file_changed = FALSE;
361         const char *new_ca_file;
362
363         switch (prop_id) {
364         case PROP_PROXY_URI:
365                 uri = g_value_get_boxed (value);
366
367                 if (!safe_uri_equal (priv->proxy_uri, uri))
368                         need_abort = TRUE;
369
370                 if (priv->proxy_uri)
371                         soup_uri_free (priv->proxy_uri);
372
373                 priv->proxy_uri = uri ? soup_uri_copy (uri) : NULL;
374
375                 if (need_abort) {
376                         soup_session_abort (session);
377                         cleanup_hosts (priv);
378                 }
379
380                 break;
381         case PROP_MAX_CONNS:
382                 priv->max_conns = g_value_get_int (value);
383                 break;
384         case PROP_MAX_CONNS_PER_HOST:
385                 priv->max_conns_per_host = g_value_get_int (value);
386                 break;
387         case PROP_USE_NTLM:
388                 priv->use_ntlm = g_value_get_boolean (value);
389                 break;
390         case PROP_SSL_CA_FILE:
391                 new_ca_file = g_value_get_string (value);
392
393                 if (!safe_str_equal (priv->ssl_ca_file, new_ca_file))
394                         ca_file_changed = TRUE;
395
396                 g_free (priv->ssl_ca_file);
397                 priv->ssl_ca_file = g_strdup (new_ca_file);
398
399                 if (ca_file_changed) {
400                         if (priv->ssl_creds) {
401                                 soup_ssl_free_client_credentials (priv->ssl_creds);
402                                 priv->ssl_creds = NULL;
403                         }
404
405                         cleanup_hosts (priv);
406                 }
407
408                 break;
409         case PROP_ASYNC_CONTEXT:
410                 priv->async_context = g_value_get_pointer (value);
411                 if (priv->async_context)
412                         g_main_context_ref (priv->async_context);
413                 break;
414         case PROP_TIMEOUT:
415                 priv->timeout = g_value_get_uint (value);
416                 break;
417         default:
418                 break;
419         }
420 }
421
422 static void
423 get_property (GObject *object, guint prop_id,
424               GValue *value, GParamSpec *pspec)
425 {
426         SoupSession *session = SOUP_SESSION (object);
427         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
428
429         switch (prop_id) {
430         case PROP_PROXY_URI:
431                 g_value_set_boxed (value, priv->proxy_uri);
432                 break;
433         case PROP_MAX_CONNS:
434                 g_value_set_int (value, priv->max_conns);
435                 break;
436         case PROP_MAX_CONNS_PER_HOST:
437                 g_value_set_int (value, priv->max_conns_per_host);
438                 break;
439         case PROP_USE_NTLM:
440                 g_value_set_boolean (value, priv->use_ntlm);
441                 break;
442         case PROP_SSL_CA_FILE:
443                 g_value_set_string (value, priv->ssl_ca_file);
444                 break;
445         case PROP_ASYNC_CONTEXT:
446                 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
447                 break;
448         case PROP_TIMEOUT:
449                 g_value_set_uint (value, priv->timeout);
450                 break;
451         default:
452                 break;
453         }
454 }
455
456
457 /**
458  * soup_session_get_async_context:
459  * @session: a #SoupSession
460  *
461  * Gets @session's async_context. This does not add a ref to the
462  * context, so you will need to ref it yourself if you want it to
463  * outlive its session.
464  *
465  * Return value: @session's #GMainContext, which may be %NULL
466  **/
467 GMainContext *
468 soup_session_get_async_context (SoupSession *session)
469 {
470         SoupSessionPrivate *priv;
471
472         g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
473         priv = SOUP_SESSION_GET_PRIVATE (session);
474
475         return priv->async_context;
476 }
477
478 /* Hosts */
479
480 static SoupSessionHost *
481 soup_session_host_new (SoupSession *session, SoupURI *source_uri)
482 {
483         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
484         SoupSessionHost *host;
485
486         host = g_slice_new0 (SoupSessionHost);
487         host->root_uri = soup_uri_copy_root (source_uri);
488
489         if (host->root_uri->scheme == SOUP_URI_SCHEME_HTTPS &&
490             !priv->ssl_creds) {
491                 priv->ssl_creds =
492                         soup_ssl_get_client_credentials (priv->ssl_ca_file);
493         }
494
495         return host;
496 }
497
498 /* Note: get_host_for_message doesn't lock the host_lock. The caller
499  * must do it itself if there's a chance the host doesn't already
500  * exist.
501  */
502 static SoupSessionHost *
503 get_host_for_message (SoupSession *session, SoupMessage *msg)
504 {
505         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
506         SoupSessionHost *host;
507         SoupURI *source = soup_message_get_uri (msg);
508
509         host = g_hash_table_lookup (priv->hosts, source);
510         if (host)
511                 return host;
512
513         host = soup_session_host_new (session, source);
514         g_hash_table_insert (priv->hosts, host->root_uri, host);
515
516         return host;
517 }
518
519 static void
520 free_host (SoupSessionHost *host)
521 {
522         while (host->connections) {
523                 SoupConnection *conn = host->connections->data;
524
525                 host->connections = g_slist_remove (host->connections, conn);
526                 soup_connection_disconnect (conn);
527         }
528
529         soup_uri_free (host->root_uri);
530         g_slice_free (SoupSessionHost, host);
531 }       
532
533 void
534 soup_session_emit_authenticate (SoupSession *session, SoupMessage *msg,
535                                 SoupAuth *auth, gboolean retrying)
536 {
537         g_signal_emit (session, signals[AUTHENTICATE], 0, msg, auth, retrying);
538 }
539
540 static void
541 reemit_authenticate (SoupConnection *conn, SoupMessage *msg,
542                      SoupAuth *auth, gboolean retrying, gpointer session)
543 {
544         soup_session_emit_authenticate (session, msg, auth, retrying);
545 }
546
547 static void
548 redirect_handler (SoupMessage *msg, gpointer user_data)
549 {
550         SoupSession *session = user_data;
551         const char *new_loc;
552         SoupURI *new_uri;
553
554         if (!SOUP_STATUS_IS_REDIRECTION (msg->status_code))
555                 return;
556
557         new_loc = soup_message_headers_get (msg->response_headers, "Location");
558         if (!new_loc)
559                 return;
560
561         /* Location is supposed to be an absolute URI, but some sites
562          * are lame, so we use soup_uri_new_with_base().
563          */
564         new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
565         if (!new_uri) {
566                 soup_message_set_status_full (msg,
567                                               SOUP_STATUS_MALFORMED,
568                                               "Invalid Redirect URL");
569                 return;
570         }
571
572         soup_message_set_uri (msg, new_uri);
573         soup_uri_free (new_uri);
574
575         soup_session_requeue_message (session, msg);
576 }
577
578 static void
579 connection_started_request (SoupConnection *conn, SoupMessage *msg,
580                             gpointer data)
581 {
582         SoupSession *session = data;
583
584         g_signal_emit (session, signals[REQUEST_STARTED], 0,
585                        msg, soup_connection_get_socket (conn));
586 }
587
588 static void
589 find_oldest_connection (gpointer key, gpointer host, gpointer data)
590 {
591         SoupConnection *conn = key, **oldest = data;
592
593         /* Don't prune a connection that is currently in use, or
594          * hasn't been used yet.
595          */
596         if (soup_connection_is_in_use (conn) ||
597             soup_connection_last_used (conn) == 0)
598                 return;
599
600         if (!*oldest || (soup_connection_last_used (conn) <
601                          soup_connection_last_used (*oldest)))
602                 *oldest = conn;
603 }
604
605 /**
606  * soup_session_try_prune_connection:
607  * @session: a #SoupSession
608  *
609  * Finds the least-recently-used idle connection in @session and closes
610  * it.
611  *
612  * Return value: %TRUE if a connection was closed, %FALSE if there are
613  * no idle connections.
614  **/
615 gboolean
616 soup_session_try_prune_connection (SoupSession *session)
617 {
618         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
619         SoupConnection *oldest = NULL;
620
621         g_mutex_lock (priv->host_lock);
622         g_hash_table_foreach (priv->conns, find_oldest_connection,
623                               &oldest);
624         if (oldest) {
625                 /* Ref the connection before unlocking the mutex in
626                  * case someone else tries to prune it too.
627                  */
628                 g_object_ref (oldest);
629                 g_mutex_unlock (priv->host_lock);
630                 soup_connection_disconnect (oldest);
631                 g_object_unref (oldest);
632                 return TRUE;
633         } else {
634                 g_mutex_unlock (priv->host_lock);
635                 return FALSE;
636         }
637 }
638
639 static void
640 connection_disconnected (SoupConnection *conn, gpointer user_data)
641 {
642         SoupSession *session = user_data;
643         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
644         SoupSessionHost *host;
645
646         g_mutex_lock (priv->host_lock);
647
648         host = g_hash_table_lookup (priv->conns, conn);
649         if (host) {
650                 g_hash_table_remove (priv->conns, conn);
651                 host->connections = g_slist_remove (host->connections, conn);
652                 host->num_conns--;
653         }
654
655         g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
656         priv->num_conns--;
657
658         g_mutex_unlock (priv->host_lock);
659         g_object_unref (conn);
660 }
661
662 static void
663 connect_result (SoupConnection *conn, guint status, gpointer user_data)
664 {
665         SoupSession *session = user_data;
666         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
667         SoupSessionHost *host;
668         SoupMessageQueueIter iter;
669         SoupMessage *msg;
670
671         g_mutex_lock (priv->host_lock);
672
673         host = g_hash_table_lookup (priv->conns, conn);
674         if (!host) {
675                 g_mutex_unlock (priv->host_lock);
676                 return;
677         }
678
679         if (status == SOUP_STATUS_OK) {
680                 soup_connection_reserve (conn);
681                 host->connections = g_slist_prepend (host->connections, conn);
682                 g_mutex_unlock (priv->host_lock);
683                 return;
684         }
685
686         /* The connection failed. */
687         g_mutex_unlock (priv->host_lock);
688         connection_disconnected (conn, session);
689
690         if (host->connections) {
691                 /* Something went wrong this time, but we have at
692                  * least one open connection to this host. So just
693                  * leave the message in the queue so it can use that
694                  * connection once it's free.
695                  */
696                 return;
697         }
698
699         /* There are two possibilities: either status is
700          * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
701          * will create a new connection (and all we need to do here
702          * is downgrade the message from CONNECTING to QUEUED); or
703          * status is something else, probably CANT_CONNECT or
704          * CANT_RESOLVE or the like, in which case we need to cancel
705          * any messages waiting for this host, since they're out
706          * of luck.
707          */
708         for (msg = soup_message_queue_first (priv->queue, &iter); msg; msg = soup_message_queue_next (priv->queue, &iter)) {
709                 if (get_host_for_message (session, msg) == host) {
710                         if (status == SOUP_STATUS_TRY_AGAIN) {
711                                 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING)
712                                         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
713                         } else {
714                                 soup_session_cancel_message (session, msg,
715                                                              status);
716                         }
717                 }
718         }
719 }
720
721 /**
722  * soup_session_get_connection:
723  * @session: a #SoupSession
724  * @msg: a #SoupMessage
725  * @try_pruning: on return, whether or not to try pruning a connection
726  * @is_new: on return, %TRUE if the returned connection is new and not
727  * yet connected
728  * 
729  * Tries to find or create a connection for @msg; this is an internal
730  * method for #SoupSession subclasses.
731  *
732  * If there is an idle connection to the relevant host available, then
733  * that connection will be returned (with *@is_new set to %FALSE). The
734  * connection will be marked "reserved", so the caller must call
735  * soup_connection_release() if it ends up not using the connection
736  * right away.
737  *
738  * If there is no idle connection available, but it is possible to
739  * create a new connection, then one will be created and returned,
740  * with *@is_new set to %TRUE. The caller MUST then call
741  * soup_connection_connect_sync() or soup_connection_connect_async()
742  * to connect it. If the connection attempt succeeds, the connection
743  * will be marked "reserved" and added to @session's connection pool
744  * once it connects. If the connection attempt fails, the connection
745  * will be unreffed.
746  *
747  * If no connection is available and a new connection cannot be made,
748  * soup_session_get_connection() will return %NULL. If @session has
749  * the maximum number of open connections open, but does not have the
750  * maximum number of per-host connections open to the relevant host,
751  * then *@try_pruning will be set to %TRUE. In this case, the caller
752  * can call soup_session_try_prune_connection() to close an idle
753  * connection, and then try soup_session_get_connection() again. (If
754  * calling soup_session_try_prune_connection() wouldn't help, then
755  * *@try_pruning is left untouched; it is NOT set to %FALSE.)
756  *
757  * Return value: a #SoupConnection, or %NULL
758  **/
759 SoupConnection *
760 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
761                              gboolean *try_pruning, gboolean *is_new)
762 {
763         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
764         SoupConnection *conn;
765         SoupSessionHost *host;
766         GSList *conns;
767
768         g_mutex_lock (priv->host_lock);
769
770         host = get_host_for_message (session, msg);
771         for (conns = host->connections; conns; conns = conns->next) {
772                 if (!soup_connection_is_in_use (conns->data)) {
773                         soup_connection_reserve (conns->data);
774                         g_mutex_unlock (priv->host_lock);
775                         *is_new = FALSE;
776                         return conns->data;
777                 }
778         }
779
780         if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING) {
781                 /* We already started a connection for this
782                  * message, so don't start another one.
783                  */
784                 g_mutex_unlock (priv->host_lock);
785                 return NULL;
786         }
787
788         if (host->num_conns >= priv->max_conns_per_host) {
789                 g_mutex_unlock (priv->host_lock);
790                 return NULL;
791         }
792
793         if (priv->num_conns >= priv->max_conns) {
794                 *try_pruning = TRUE;
795                 g_mutex_unlock (priv->host_lock);
796                 return NULL;
797         }
798
799         conn = g_object_new (
800                 (priv->use_ntlm ?
801                  SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
802                 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
803                 SOUP_CONNECTION_PROXY_URI, priv->proxy_uri,
804                 SOUP_CONNECTION_SSL_CREDENTIALS, priv->ssl_creds,
805                 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
806                 SOUP_CONNECTION_TIMEOUT, priv->timeout,
807                 NULL);
808         g_signal_connect (conn, "connect_result",
809                           G_CALLBACK (connect_result),
810                           session);
811         g_signal_connect (conn, "disconnected",
812                           G_CALLBACK (connection_disconnected),
813                           session);
814         g_signal_connect (conn, "request_started",
815                           G_CALLBACK (connection_started_request),
816                           session);
817         g_signal_connect (conn, "authenticate",
818                           G_CALLBACK (reemit_authenticate),
819                           session);
820
821         g_hash_table_insert (priv->conns, conn, host);
822
823         /* We increment the connection counts so it counts against the
824          * totals, but we don't add it to the host's connection list
825          * yet, since it's not ready for use.
826          */
827         priv->num_conns++;
828         host->num_conns++;
829
830         /* Mark the request as connecting, so we don't try to open
831          * another new connection for it while waiting for this one.
832          */
833         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_CONNECTING);
834
835         g_mutex_unlock (priv->host_lock);
836         *is_new = TRUE;
837         return conn;
838 }
839
840 SoupMessageQueue *
841 soup_session_get_queue (SoupSession *session)
842 {
843         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
844
845         return priv->queue;
846 }
847
848 static void
849 message_finished (SoupMessage *msg, gpointer user_data)
850 {
851         SoupSession *session = user_data;
852         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
853
854         if (!SOUP_MESSAGE_IS_STARTING (msg)) {
855                 soup_message_queue_remove_message (priv->queue, msg);
856                 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
857         }
858 }
859
860 static void
861 queue_message (SoupSession *session, SoupMessage *msg,
862                SoupSessionCallback callback, gpointer user_data)
863 {
864         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
865
866         g_signal_connect_after (msg, "finished",
867                                 G_CALLBACK (message_finished), session);
868
869         if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
870                 soup_message_add_header_handler (
871                         msg, "got_body", "Location",
872                         G_CALLBACK (redirect_handler), session);
873         }
874
875         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
876         soup_message_queue_append (priv->queue, msg);
877 }
878
879 /**
880  * soup_session_queue_message:
881  * @session: a #SoupSession
882  * @msg: the message to queue
883  * @callback: a #SoupSessionCallback which will be called after the
884  * message completes or when an unrecoverable error occurs.
885  * @user_data: a pointer passed to @callback.
886  * 
887  * Queues the message @msg for sending. All messages are processed
888  * while the glib main loop runs. If @msg has been processed before,
889  * any resources related to the time it was last sent are freed.
890  *
891  * Upon message completion, the callback specified in @callback will
892  * be invoked (in the thread associated with @session's async
893  * context). If after returning from this callback the message has not
894  * been requeued, @msg will be unreffed.
895  */
896 void
897 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
898                             SoupSessionCallback callback, gpointer user_data)
899 {
900         g_return_if_fail (SOUP_IS_SESSION (session));
901         g_return_if_fail (SOUP_IS_MESSAGE (msg));
902
903         SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
904                                                          callback, user_data);
905 }
906
907 static void
908 requeue_message (SoupSession *session, SoupMessage *msg)
909 {
910         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
911 }
912
913 /**
914  * soup_session_requeue_message:
915  * @session: a #SoupSession
916  * @msg: the message to requeue
917  *
918  * This causes @msg to be placed back on the queue to be attempted
919  * again.
920  **/
921 void
922 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
923 {
924         g_return_if_fail (SOUP_IS_SESSION (session));
925         g_return_if_fail (SOUP_IS_MESSAGE (msg));
926
927         SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
928 }
929
930
931 /**
932  * soup_session_send_message:
933  * @session: a #SoupSession
934  * @msg: the message to send
935  * 
936  * Synchronously send @msg. This call will not return until the
937  * transfer is finished successfully or there is an unrecoverable
938  * error.
939  *
940  * @msg is not freed upon return.
941  *
942  * Return value: the HTTP status code of the response
943  */
944 guint
945 soup_session_send_message (SoupSession *session, SoupMessage *msg)
946 {
947         g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
948         g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
949
950         return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
951 }
952
953
954 /**
955  * soup_session_pause_message:
956  * @session: a #SoupSession
957  * @msg: a #SoupMessage currently running on @session
958  *
959  * Pauses HTTP I/O on @msg. Call soup_session_unpause_message() to
960  * resume I/O.
961  **/
962 void
963 soup_session_pause_message (SoupSession *session,
964                             SoupMessage *msg)
965 {
966         g_return_if_fail (SOUP_IS_SESSION (session));
967         g_return_if_fail (SOUP_IS_MESSAGE (msg));
968
969         soup_message_io_pause (msg);
970 }
971
972 /**
973  * soup_session_unpause_message:
974  * @session: a #SoupSession
975  * @msg: a #SoupMessage currently running on @session
976  *
977  * Resumes HTTP I/O on @msg. Use this to resume after calling
978  * soup_sessino_pause_message().
979  *
980  * If @msg is being sent via blocking I/O, this will resume reading or
981  * writing immediately. If @msg is using non-blocking I/O, then
982  * reading or writing won't resume until you return to the main loop.
983  **/
984 void
985 soup_session_unpause_message (SoupSession *session,
986                               SoupMessage *msg)
987 {
988         g_return_if_fail (SOUP_IS_SESSION (session));
989         g_return_if_fail (SOUP_IS_MESSAGE (msg));
990
991         soup_message_io_unpause (msg);
992 }
993
994
995 static void
996 cancel_message (SoupSession *session, SoupMessage *msg, guint status_code)
997 {
998         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
999
1000         soup_message_queue_remove_message (priv->queue, msg);
1001         soup_message_io_stop (msg);
1002         soup_message_set_status (msg, status_code);
1003         soup_message_finished (msg);
1004 }
1005
1006 /**
1007  * soup_session_cancel_message:
1008  * @session: a #SoupSession
1009  * @msg: the message to cancel
1010  * @status_code: status code to set on @msg (generally
1011  * %SOUP_STATUS_CANCELLED)
1012  *
1013  * Causes @session to immediately finish processing @msg, with a final
1014  * status_code of @status_code. Depending on when you cancel it, the
1015  * response state may be incomplete or inconsistent.
1016  **/
1017 void
1018 soup_session_cancel_message (SoupSession *session, SoupMessage *msg,
1019                              guint status_code)
1020 {
1021         g_return_if_fail (SOUP_IS_SESSION (session));
1022         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1023
1024         SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg, status_code);
1025 }
1026
1027 static void
1028 gather_conns (gpointer key, gpointer host, gpointer data)
1029 {
1030         SoupConnection *conn = key;
1031         GSList **conns = data;
1032
1033         *conns = g_slist_prepend (*conns, conn);
1034 }
1035
1036 /**
1037  * soup_session_abort:
1038  * @session: the session
1039  *
1040  * Cancels all pending requests in @session.
1041  **/
1042 void
1043 soup_session_abort (SoupSession *session)
1044 {
1045         SoupSessionPrivate *priv;
1046         SoupMessageQueueIter iter;
1047         SoupMessage *msg;
1048         GSList *conns, *c;
1049
1050         g_return_if_fail (SOUP_IS_SESSION (session));
1051         priv = SOUP_SESSION_GET_PRIVATE (session);
1052
1053         for (msg = soup_message_queue_first (priv->queue, &iter);
1054              msg;
1055              msg = soup_message_queue_next (priv->queue, &iter)) {
1056                 soup_session_cancel_message (session, msg,
1057                                              SOUP_STATUS_CANCELLED);
1058         }
1059
1060         /* Close all connections */
1061         g_mutex_lock (priv->host_lock);
1062         conns = NULL;
1063         g_hash_table_foreach (priv->conns, gather_conns, &conns);
1064
1065         for (c = conns; c; c = c->next)
1066                 g_object_ref (c->data);
1067         g_mutex_unlock (priv->host_lock);
1068         for (c = conns; c; c = c->next) {
1069                 soup_connection_disconnect (c->data);
1070                 g_object_unref (c->data);
1071         }
1072
1073         g_slist_free (conns);
1074 }