Replaces SoupConnectionNTLM; now works as a SoupSession::request_started
[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-auth-manager-ntlm.h"
21 #include "soup-connection.h"
22 #include "soup-marshal.h"
23 #include "soup-message-private.h"
24 #include "soup-message-queue.h"
25 #include "soup-session.h"
26 #include "soup-session-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
53         char *ssl_ca_file;
54         SoupSSLCredentials *ssl_creds;
55
56         SoupMessageQueue *queue;
57
58         SoupAuthManager *auth_manager;
59         SoupAuthManagerNTLM *ntlm_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                 if (g_value_get_boolean (value)) {
389                         if (!priv->ntlm_manager)
390                                 priv->ntlm_manager = soup_auth_manager_ntlm_new (session);
391                 } else {
392                         if (priv->ntlm_manager) {
393                                 soup_auth_manager_ntlm_free (priv->ntlm_manager);
394                                 priv->ntlm_manager = NULL;
395                         }
396                 }
397                 break;
398         case PROP_SSL_CA_FILE:
399                 new_ca_file = g_value_get_string (value);
400
401                 if (!safe_str_equal (priv->ssl_ca_file, new_ca_file))
402                         ca_file_changed = TRUE;
403
404                 g_free (priv->ssl_ca_file);
405                 priv->ssl_ca_file = g_strdup (new_ca_file);
406
407                 if (ca_file_changed) {
408                         if (priv->ssl_creds) {
409                                 soup_ssl_free_client_credentials (priv->ssl_creds);
410                                 priv->ssl_creds = NULL;
411                         }
412
413                         cleanup_hosts (priv);
414                 }
415
416                 break;
417         case PROP_ASYNC_CONTEXT:
418                 priv->async_context = g_value_get_pointer (value);
419                 if (priv->async_context)
420                         g_main_context_ref (priv->async_context);
421                 break;
422         case PROP_TIMEOUT:
423                 priv->timeout = g_value_get_uint (value);
424                 break;
425         default:
426                 break;
427         }
428 }
429
430 static void
431 get_property (GObject *object, guint prop_id,
432               GValue *value, GParamSpec *pspec)
433 {
434         SoupSession *session = SOUP_SESSION (object);
435         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
436
437         switch (prop_id) {
438         case PROP_PROXY_URI:
439                 g_value_set_boxed (value, priv->proxy_uri);
440                 break;
441         case PROP_MAX_CONNS:
442                 g_value_set_int (value, priv->max_conns);
443                 break;
444         case PROP_MAX_CONNS_PER_HOST:
445                 g_value_set_int (value, priv->max_conns_per_host);
446                 break;
447         case PROP_USE_NTLM:
448                 g_value_set_boolean (value, priv->ntlm_manager != NULL);
449                 break;
450         case PROP_SSL_CA_FILE:
451                 g_value_set_string (value, priv->ssl_ca_file);
452                 break;
453         case PROP_ASYNC_CONTEXT:
454                 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
455                 break;
456         case PROP_TIMEOUT:
457                 g_value_set_uint (value, priv->timeout);
458                 break;
459         default:
460                 break;
461         }
462 }
463
464
465 /**
466  * soup_session_get_async_context:
467  * @session: a #SoupSession
468  *
469  * Gets @session's async_context. This does not add a ref to the
470  * context, so you will need to ref it yourself if you want it to
471  * outlive its session.
472  *
473  * Return value: @session's #GMainContext, which may be %NULL
474  **/
475 GMainContext *
476 soup_session_get_async_context (SoupSession *session)
477 {
478         SoupSessionPrivate *priv;
479
480         g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
481         priv = SOUP_SESSION_GET_PRIVATE (session);
482
483         return priv->async_context;
484 }
485
486 /* Hosts */
487
488 static SoupSessionHost *
489 soup_session_host_new (SoupSession *session, SoupURI *source_uri)
490 {
491         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
492         SoupSessionHost *host;
493
494         host = g_slice_new0 (SoupSessionHost);
495         host->root_uri = soup_uri_copy_root (source_uri);
496
497         if (host->root_uri->scheme == SOUP_URI_SCHEME_HTTPS &&
498             !priv->ssl_creds) {
499                 priv->ssl_creds =
500                         soup_ssl_get_client_credentials (priv->ssl_ca_file);
501         }
502
503         return host;
504 }
505
506 /* Note: get_host_for_message doesn't lock the host_lock. The caller
507  * must do it itself if there's a chance the host doesn't already
508  * exist.
509  */
510 static SoupSessionHost *
511 get_host_for_message (SoupSession *session, SoupMessage *msg)
512 {
513         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
514         SoupSessionHost *host;
515         SoupURI *source = soup_message_get_uri (msg);
516
517         host = g_hash_table_lookup (priv->hosts, source);
518         if (host)
519                 return host;
520
521         host = soup_session_host_new (session, source);
522         g_hash_table_insert (priv->hosts, host->root_uri, host);
523
524         return host;
525 }
526
527 static void
528 free_host (SoupSessionHost *host)
529 {
530         while (host->connections) {
531                 SoupConnection *conn = host->connections->data;
532
533                 host->connections = g_slist_remove (host->connections, conn);
534                 soup_connection_disconnect (conn);
535         }
536
537         soup_uri_free (host->root_uri);
538         g_slice_free (SoupSessionHost, host);
539 }       
540
541 void
542 soup_session_emit_authenticate (SoupSession *session, SoupMessage *msg,
543                                 SoupAuth *auth, gboolean retrying)
544 {
545         g_signal_emit (session, signals[AUTHENTICATE], 0, msg, auth, retrying);
546 }
547
548 static void
549 redirect_handler (SoupMessage *msg, gpointer user_data)
550 {
551         SoupSession *session = user_data;
552         const char *new_loc;
553         SoupURI *new_uri;
554
555         if (!SOUP_STATUS_IS_REDIRECTION (msg->status_code))
556                 return;
557
558         new_loc = soup_message_headers_get (msg->response_headers, "Location");
559         if (!new_loc)
560                 return;
561
562         /* Location is supposed to be an absolute URI, but some sites
563          * are lame, so we use soup_uri_new_with_base().
564          */
565         new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
566         if (!new_uri) {
567                 soup_message_set_status_full (msg,
568                                               SOUP_STATUS_MALFORMED,
569                                               "Invalid Redirect URL");
570                 return;
571         }
572
573         soup_message_set_uri (msg, new_uri);
574         soup_uri_free (new_uri);
575
576         soup_session_requeue_message (session, msg);
577 }
578
579 static void
580 connection_started_request (SoupConnection *conn, SoupMessage *msg,
581                             gpointer data)
582 {
583         SoupSession *session = data;
584
585         g_signal_emit (session, signals[REQUEST_STARTED], 0,
586                        msg, soup_connection_get_socket (conn));
587 }
588
589 static void
590 find_oldest_connection (gpointer key, gpointer host, gpointer data)
591 {
592         SoupConnection *conn = key, **oldest = data;
593
594         /* Don't prune a connection that is currently in use, or
595          * hasn't been used yet.
596          */
597         if (soup_connection_is_in_use (conn) ||
598             soup_connection_last_used (conn) == 0)
599                 return;
600
601         if (!*oldest || (soup_connection_last_used (conn) <
602                          soup_connection_last_used (*oldest)))
603                 *oldest = conn;
604 }
605
606 /**
607  * soup_session_try_prune_connection:
608  * @session: a #SoupSession
609  *
610  * Finds the least-recently-used idle connection in @session and closes
611  * it.
612  *
613  * Return value: %TRUE if a connection was closed, %FALSE if there are
614  * no idle connections.
615  **/
616 gboolean
617 soup_session_try_prune_connection (SoupSession *session)
618 {
619         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
620         SoupConnection *oldest = NULL;
621
622         g_mutex_lock (priv->host_lock);
623         g_hash_table_foreach (priv->conns, find_oldest_connection,
624                               &oldest);
625         if (oldest) {
626                 /* Ref the connection before unlocking the mutex in
627                  * case someone else tries to prune it too.
628                  */
629                 g_object_ref (oldest);
630                 g_mutex_unlock (priv->host_lock);
631                 soup_connection_disconnect (oldest);
632                 g_object_unref (oldest);
633                 return TRUE;
634         } else {
635                 g_mutex_unlock (priv->host_lock);
636                 return FALSE;
637         }
638 }
639
640 static void
641 connection_disconnected (SoupConnection *conn, gpointer user_data)
642 {
643         SoupSession *session = user_data;
644         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
645         SoupSessionHost *host;
646
647         g_mutex_lock (priv->host_lock);
648
649         host = g_hash_table_lookup (priv->conns, conn);
650         if (host) {
651                 g_hash_table_remove (priv->conns, conn);
652                 host->connections = g_slist_remove (host->connections, conn);
653                 host->num_conns--;
654         }
655
656         g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
657         priv->num_conns--;
658
659         g_mutex_unlock (priv->host_lock);
660         g_object_unref (conn);
661 }
662
663 static void
664 connect_result (SoupConnection *conn, guint status, gpointer user_data)
665 {
666         SoupSession *session = user_data;
667         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
668         SoupSessionHost *host;
669         SoupMessageQueueIter iter;
670         SoupMessage *msg;
671
672         g_mutex_lock (priv->host_lock);
673
674         host = g_hash_table_lookup (priv->conns, conn);
675         if (!host) {
676                 g_mutex_unlock (priv->host_lock);
677                 return;
678         }
679
680         if (status == SOUP_STATUS_OK) {
681                 soup_connection_reserve (conn);
682                 host->connections = g_slist_prepend (host->connections, conn);
683                 g_mutex_unlock (priv->host_lock);
684                 return;
685         }
686
687         /* The connection failed. */
688         g_mutex_unlock (priv->host_lock);
689         connection_disconnected (conn, session);
690
691         if (host->connections) {
692                 /* Something went wrong this time, but we have at
693                  * least one open connection to this host. So just
694                  * leave the message in the queue so it can use that
695                  * connection once it's free.
696                  */
697                 return;
698         }
699
700         /* There are two possibilities: either status is
701          * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
702          * will create a new connection (and all we need to do here
703          * is downgrade the message from CONNECTING to QUEUED); or
704          * status is something else, probably CANT_CONNECT or
705          * CANT_RESOLVE or the like, in which case we need to cancel
706          * any messages waiting for this host, since they're out
707          * of luck.
708          */
709         for (msg = soup_message_queue_first (priv->queue, &iter); msg; msg = soup_message_queue_next (priv->queue, &iter)) {
710                 if (get_host_for_message (session, msg) == host) {
711                         if (status == SOUP_STATUS_TRY_AGAIN) {
712                                 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING)
713                                         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
714                         } else {
715                                 soup_session_cancel_message (session, msg,
716                                                              status);
717                         }
718                 }
719         }
720 }
721
722 /**
723  * soup_session_get_connection:
724  * @session: a #SoupSession
725  * @msg: a #SoupMessage
726  * @try_pruning: on return, whether or not to try pruning a connection
727  * @is_new: on return, %TRUE if the returned connection is new and not
728  * yet connected
729  * 
730  * Tries to find or create a connection for @msg; this is an internal
731  * method for #SoupSession subclasses.
732  *
733  * If there is an idle connection to the relevant host available, then
734  * that connection will be returned (with *@is_new set to %FALSE). The
735  * connection will be marked "reserved", so the caller must call
736  * soup_connection_release() if it ends up not using the connection
737  * right away.
738  *
739  * If there is no idle connection available, but it is possible to
740  * create a new connection, then one will be created and returned,
741  * with *@is_new set to %TRUE. The caller MUST then call
742  * soup_connection_connect_sync() or soup_connection_connect_async()
743  * to connect it. If the connection attempt succeeds, the connection
744  * will be marked "reserved" and added to @session's connection pool
745  * once it connects. If the connection attempt fails, the connection
746  * will be unreffed.
747  *
748  * If no connection is available and a new connection cannot be made,
749  * soup_session_get_connection() will return %NULL. If @session has
750  * the maximum number of open connections open, but does not have the
751  * maximum number of per-host connections open to the relevant host,
752  * then *@try_pruning will be set to %TRUE. In this case, the caller
753  * can call soup_session_try_prune_connection() to close an idle
754  * connection, and then try soup_session_get_connection() again. (If
755  * calling soup_session_try_prune_connection() wouldn't help, then
756  * *@try_pruning is left untouched; it is NOT set to %FALSE.)
757  *
758  * Return value: a #SoupConnection, or %NULL
759  **/
760 SoupConnection *
761 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
762                              gboolean *try_pruning, gboolean *is_new)
763 {
764         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
765         SoupConnection *conn;
766         SoupSessionHost *host;
767         GSList *conns;
768
769         g_mutex_lock (priv->host_lock);
770
771         host = get_host_for_message (session, msg);
772         for (conns = host->connections; conns; conns = conns->next) {
773                 if (!soup_connection_is_in_use (conns->data)) {
774                         soup_connection_reserve (conns->data);
775                         g_mutex_unlock (priv->host_lock);
776                         *is_new = FALSE;
777                         return conns->data;
778                 }
779         }
780
781         if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING) {
782                 /* We already started a connection for this
783                  * message, so don't start another one.
784                  */
785                 g_mutex_unlock (priv->host_lock);
786                 return NULL;
787         }
788
789         if (host->num_conns >= priv->max_conns_per_host) {
790                 g_mutex_unlock (priv->host_lock);
791                 return NULL;
792         }
793
794         if (priv->num_conns >= priv->max_conns) {
795                 *try_pruning = TRUE;
796                 g_mutex_unlock (priv->host_lock);
797                 return NULL;
798         }
799
800         conn = soup_connection_new (
801                 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
802                 SOUP_CONNECTION_PROXY_URI, priv->proxy_uri,
803                 SOUP_CONNECTION_SSL_CREDENTIALS, priv->ssl_creds,
804                 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
805                 SOUP_CONNECTION_TIMEOUT, priv->timeout,
806                 NULL);
807         g_signal_connect (conn, "connect_result",
808                           G_CALLBACK (connect_result),
809                           session);
810         g_signal_connect (conn, "disconnected",
811                           G_CALLBACK (connection_disconnected),
812                           session);
813         g_signal_connect (conn, "request_started",
814                           G_CALLBACK (connection_started_request),
815                           session);
816
817         g_hash_table_insert (priv->conns, conn, host);
818
819         /* We increment the connection counts so it counts against the
820          * totals, but we don't add it to the host's connection list
821          * yet, since it's not ready for use.
822          */
823         priv->num_conns++;
824         host->num_conns++;
825
826         /* Mark the request as connecting, so we don't try to open
827          * another new connection for it while waiting for this one.
828          */
829         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_CONNECTING);
830
831         g_mutex_unlock (priv->host_lock);
832         *is_new = TRUE;
833         return conn;
834 }
835
836 SoupMessageQueue *
837 soup_session_get_queue (SoupSession *session)
838 {
839         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
840
841         return priv->queue;
842 }
843
844 static void
845 message_finished (SoupMessage *msg, gpointer user_data)
846 {
847         SoupSession *session = user_data;
848         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
849
850         if (!SOUP_MESSAGE_IS_STARTING (msg)) {
851                 soup_message_queue_remove_message (priv->queue, msg);
852                 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
853         }
854 }
855
856 static void
857 queue_message (SoupSession *session, SoupMessage *msg,
858                SoupSessionCallback callback, gpointer user_data)
859 {
860         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
861
862         g_signal_connect_after (msg, "finished",
863                                 G_CALLBACK (message_finished), session);
864
865         if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
866                 soup_message_add_header_handler (
867                         msg, "got_body", "Location",
868                         G_CALLBACK (redirect_handler), session);
869         }
870
871         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
872         soup_message_queue_append (priv->queue, msg);
873 }
874
875 /**
876  * soup_session_queue_message:
877  * @session: a #SoupSession
878  * @msg: the message to queue
879  * @callback: a #SoupSessionCallback which will be called after the
880  * message completes or when an unrecoverable error occurs.
881  * @user_data: a pointer passed to @callback.
882  * 
883  * Queues the message @msg for sending. All messages are processed
884  * while the glib main loop runs. If @msg has been processed before,
885  * any resources related to the time it was last sent are freed.
886  *
887  * Upon message completion, the callback specified in @callback will
888  * be invoked (in the thread associated with @session's async
889  * context). If after returning from this callback the message has not
890  * been requeued, @msg will be unreffed.
891  */
892 void
893 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
894                             SoupSessionCallback callback, gpointer user_data)
895 {
896         g_return_if_fail (SOUP_IS_SESSION (session));
897         g_return_if_fail (SOUP_IS_MESSAGE (msg));
898
899         SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
900                                                          callback, user_data);
901 }
902
903 static void
904 requeue_message (SoupSession *session, SoupMessage *msg)
905 {
906         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
907 }
908
909 /**
910  * soup_session_requeue_message:
911  * @session: a #SoupSession
912  * @msg: the message to requeue
913  *
914  * This causes @msg to be placed back on the queue to be attempted
915  * again.
916  **/
917 void
918 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
919 {
920         g_return_if_fail (SOUP_IS_SESSION (session));
921         g_return_if_fail (SOUP_IS_MESSAGE (msg));
922
923         SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
924 }
925
926
927 /**
928  * soup_session_send_message:
929  * @session: a #SoupSession
930  * @msg: the message to send
931  * 
932  * Synchronously send @msg. This call will not return until the
933  * transfer is finished successfully or there is an unrecoverable
934  * error.
935  *
936  * @msg is not freed upon return.
937  *
938  * Return value: the HTTP status code of the response
939  */
940 guint
941 soup_session_send_message (SoupSession *session, SoupMessage *msg)
942 {
943         g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
944         g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
945
946         return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
947 }
948
949
950 /**
951  * soup_session_pause_message:
952  * @session: a #SoupSession
953  * @msg: a #SoupMessage currently running on @session
954  *
955  * Pauses HTTP I/O on @msg. Call soup_session_unpause_message() to
956  * resume I/O.
957  **/
958 void
959 soup_session_pause_message (SoupSession *session,
960                             SoupMessage *msg)
961 {
962         g_return_if_fail (SOUP_IS_SESSION (session));
963         g_return_if_fail (SOUP_IS_MESSAGE (msg));
964
965         soup_message_io_pause (msg);
966 }
967
968 /**
969  * soup_session_unpause_message:
970  * @session: a #SoupSession
971  * @msg: a #SoupMessage currently running on @session
972  *
973  * Resumes HTTP I/O on @msg. Use this to resume after calling
974  * soup_sessino_pause_message().
975  *
976  * If @msg is being sent via blocking I/O, this will resume reading or
977  * writing immediately. If @msg is using non-blocking I/O, then
978  * reading or writing won't resume until you return to the main loop.
979  **/
980 void
981 soup_session_unpause_message (SoupSession *session,
982                               SoupMessage *msg)
983 {
984         g_return_if_fail (SOUP_IS_SESSION (session));
985         g_return_if_fail (SOUP_IS_MESSAGE (msg));
986
987         soup_message_io_unpause (msg);
988 }
989
990
991 static void
992 cancel_message (SoupSession *session, SoupMessage *msg, guint status_code)
993 {
994         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
995
996         soup_message_queue_remove_message (priv->queue, msg);
997         soup_message_io_stop (msg);
998         soup_message_set_status (msg, status_code);
999         soup_message_finished (msg);
1000 }
1001
1002 /**
1003  * soup_session_cancel_message:
1004  * @session: a #SoupSession
1005  * @msg: the message to cancel
1006  * @status_code: status code to set on @msg (generally
1007  * %SOUP_STATUS_CANCELLED)
1008  *
1009  * Causes @session to immediately finish processing @msg, with a final
1010  * status_code of @status_code. Depending on when you cancel it, the
1011  * response state may be incomplete or inconsistent.
1012  **/
1013 void
1014 soup_session_cancel_message (SoupSession *session, SoupMessage *msg,
1015                              guint status_code)
1016 {
1017         g_return_if_fail (SOUP_IS_SESSION (session));
1018         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1019
1020         SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg, status_code);
1021 }
1022
1023 static void
1024 gather_conns (gpointer key, gpointer host, gpointer data)
1025 {
1026         SoupConnection *conn = key;
1027         GSList **conns = data;
1028
1029         *conns = g_slist_prepend (*conns, conn);
1030 }
1031
1032 /**
1033  * soup_session_abort:
1034  * @session: the session
1035  *
1036  * Cancels all pending requests in @session.
1037  **/
1038 void
1039 soup_session_abort (SoupSession *session)
1040 {
1041         SoupSessionPrivate *priv;
1042         SoupMessageQueueIter iter;
1043         SoupMessage *msg;
1044         GSList *conns, *c;
1045
1046         g_return_if_fail (SOUP_IS_SESSION (session));
1047         priv = SOUP_SESSION_GET_PRIVATE (session);
1048
1049         for (msg = soup_message_queue_first (priv->queue, &iter);
1050              msg;
1051              msg = soup_message_queue_next (priv->queue, &iter)) {
1052                 soup_session_cancel_message (session, msg,
1053                                              SOUP_STATUS_CANCELLED);
1054         }
1055
1056         /* Close all connections */
1057         g_mutex_lock (priv->host_lock);
1058         conns = NULL;
1059         g_hash_table_foreach (priv->conns, gather_conns, &conns);
1060
1061         for (c = conns; c; c = c->next)
1062                 g_object_ref (c->data);
1063         g_mutex_unlock (priv->host_lock);
1064         for (c = conns; c; c = c->next) {
1065                 soup_connection_disconnect (c->data);
1066                 g_object_unref (c->data);
1067         }
1068
1069         g_slist_free (conns);
1070 }