Change the SoupURI properties to SoupAddress properties.
[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-address.h"
17 #include "soup-auth.h"
18 #include "soup-auth-basic.h"
19 #include "soup-auth-digest.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-feature.h"
27 #include "soup-session-private.h"
28 #include "soup-socket.h"
29 #include "soup-ssl.h"
30 #include "soup-uri.h"
31
32 /**
33  * SECTION:soup-session
34  * @short_description: Soup session state object
35  *
36  * #SoupSession is the object that controls client-side HTTP. A
37  * #SoupSession encapsulates all of the state that libsoup is keeping
38  * on behalf of your program; cached HTTP connections, authentication
39  * information, etc.
40  *
41  * Most applications will only need a single #SoupSession; the primary
42  * reason you might need multiple sessions is if you need to have
43  * multiple independent authentication contexts. (Eg, you are
44  * connecting to a server and authenticating as two different users at
45  * different times; the easiest way to ensure that each #SoupMessage
46  * is sent with the authentication information you intended is to use
47  * one session for the first user, and a second session for the other
48  * user.)
49  *
50  * #SoupSession itself is an abstract class, with two subclasses. If
51  * you are using the glib main loop, you will generally want to use
52  * #SoupSessionAsync, which uses non-blocking I/O and callbacks. On
53  * the other hand, if your application is threaded and you want to do
54  * synchronous I/O in a separate thread from the UI, use
55  * #SoupSessionSync.
56  **/
57
58 typedef struct {
59         SoupAddress *addr;
60
61         GSList      *connections;      /* CONTAINS: SoupConnection */
62         guint        num_conns;
63 } SoupSessionHost;
64
65 typedef struct {
66         SoupURI *proxy_uri;
67         SoupAddress *proxy_addr;
68         SoupAuth *proxy_auth;
69
70         char *ssl_ca_file;
71         SoupSSLCredentials *ssl_creds;
72
73         SoupMessageQueue *queue;
74
75         char *user_agent;
76
77         GSList *features;
78         SoupAuthManager *auth_manager;
79
80         GHashTable *hosts; /* SoupAddress -> SoupSessionHost */
81         GHashTable *conns; /* SoupConnection -> SoupSessionHost */
82         guint num_conns;
83         guint max_conns, max_conns_per_host;
84         guint io_timeout, idle_timeout;
85
86         /* Must hold the host_lock before potentially creating a
87          * new SoupSessionHost, or adding/removing a connection.
88          * Must not emit signals or destroy objects while holding it.
89          */
90         GMutex *host_lock;
91
92         GMainContext *async_context;
93 } SoupSessionPrivate;
94 #define SOUP_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SESSION, SoupSessionPrivate))
95
96 static void     free_host      (SoupSessionHost *host);
97
98 static void queue_message   (SoupSession *session, SoupMessage *msg,
99                              SoupSessionCallback callback, gpointer user_data);
100 static void requeue_message (SoupSession *session, SoupMessage *msg);
101 static void cancel_message  (SoupSession *session, SoupMessage *msg,
102                              guint status_code);
103
104 static void auth_manager_authenticate (SoupAuthManager *manager,
105                                        SoupMessage *msg, SoupAuth *auth,
106                                        gboolean retrying, gpointer user_data);
107
108 #define SOUP_SESSION_MAX_CONNS_DEFAULT 10
109 #define SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT 2
110
111 #define SOUP_SESSION_USER_AGENT_BASE "libsoup/" PACKAGE_VERSION
112
113 G_DEFINE_TYPE (SoupSession, soup_session, G_TYPE_OBJECT)
114
115 enum {
116         REQUEST_QUEUED,
117         REQUEST_STARTED,
118         REQUEST_UNQUEUED,
119         AUTHENTICATE,
120         LAST_SIGNAL
121 };
122
123 static guint signals[LAST_SIGNAL] = { 0 };
124
125 enum {
126         PROP_0,
127
128         PROP_PROXY_URI,
129         PROP_MAX_CONNS,
130         PROP_MAX_CONNS_PER_HOST,
131         PROP_USE_NTLM,
132         PROP_SSL_CA_FILE,
133         PROP_ASYNC_CONTEXT,
134         PROP_TIMEOUT,
135         PROP_USER_AGENT,
136         PROP_IDLE_TIMEOUT,
137         PROP_ADD_FEATURE,
138         PROP_ADD_FEATURE_BY_TYPE,
139         PROP_REMOVE_FEATURE_BY_TYPE,
140
141         LAST_PROP
142 };
143
144 static void set_property (GObject *object, guint prop_id,
145                           const GValue *value, GParamSpec *pspec);
146 static void get_property (GObject *object, guint prop_id,
147                           GValue *value, GParamSpec *pspec);
148
149 static void
150 soup_session_init (SoupSession *session)
151 {
152         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
153
154         priv->queue = soup_message_queue_new (session);
155
156         priv->host_lock = g_mutex_new ();
157         priv->hosts = g_hash_table_new (soup_address_hash_by_ip,
158                                         soup_address_equal_by_ip);
159         priv->conns = g_hash_table_new (NULL, NULL);
160
161         priv->max_conns = SOUP_SESSION_MAX_CONNS_DEFAULT;
162         priv->max_conns_per_host = SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT;
163
164         priv->auth_manager = g_object_new (SOUP_TYPE_AUTH_MANAGER_NTLM,
165                                            SOUP_AUTH_MANAGER_NTLM_USE_NTLM, FALSE,
166                                            NULL);
167         g_signal_connect (priv->auth_manager, "authenticate",
168                           G_CALLBACK (auth_manager_authenticate), session);
169         soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_BASIC);
170         soup_auth_manager_add_type (priv->auth_manager, SOUP_TYPE_AUTH_DIGEST);
171         soup_session_add_feature (session, SOUP_SESSION_FEATURE (priv->auth_manager));
172 }
173
174 static gboolean
175 foreach_free_host (gpointer key, gpointer host, gpointer data)
176 {
177         free_host (host);
178         return TRUE;
179 }
180
181 static void
182 cleanup_hosts (SoupSessionPrivate *priv)
183 {
184         GHashTable *old_hosts;
185
186         g_mutex_lock (priv->host_lock);
187         old_hosts = priv->hosts;
188         priv->hosts = g_hash_table_new (soup_address_hash_by_ip,
189                                         soup_address_equal_by_ip);
190         g_mutex_unlock (priv->host_lock);
191
192         g_hash_table_foreach_remove (old_hosts, foreach_free_host, NULL);
193         g_hash_table_destroy (old_hosts);
194 }
195
196 static void
197 dispose (GObject *object)
198 {
199         SoupSession *session = SOUP_SESSION (object);
200         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
201
202         soup_session_abort (session);
203         cleanup_hosts (priv);
204
205         while (priv->features)
206                 soup_session_remove_feature (session, priv->features->data);
207
208         G_OBJECT_CLASS (soup_session_parent_class)->dispose (object);
209 }
210
211 static void
212 finalize (GObject *object)
213 {
214         SoupSession *session = SOUP_SESSION (object);
215         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
216
217         soup_message_queue_destroy (priv->queue);
218
219         g_mutex_free (priv->host_lock);
220         g_hash_table_destroy (priv->hosts);
221         g_hash_table_destroy (priv->conns);
222
223         g_free (priv->user_agent);
224
225         if (priv->auth_manager)
226                 g_object_unref (priv->auth_manager);
227
228         if (priv->proxy_uri)
229                 soup_uri_free (priv->proxy_uri);
230         if (priv->proxy_addr)
231                 g_object_unref (priv->proxy_addr);
232
233         if (priv->ssl_creds)
234                 soup_ssl_free_client_credentials (priv->ssl_creds);
235
236         if (priv->async_context)
237                 g_main_context_unref (priv->async_context);
238
239         G_OBJECT_CLASS (soup_session_parent_class)->finalize (object);
240 }
241
242 static void
243 soup_session_class_init (SoupSessionClass *session_class)
244 {
245         GObjectClass *object_class = G_OBJECT_CLASS (session_class);
246
247         g_type_class_add_private (session_class, sizeof (SoupSessionPrivate));
248
249         /* virtual method definition */
250         session_class->queue_message = queue_message;
251         session_class->requeue_message = requeue_message;
252         session_class->cancel_message = cancel_message;
253
254         /* virtual method override */
255         object_class->dispose = dispose;
256         object_class->finalize = finalize;
257         object_class->set_property = set_property;
258         object_class->get_property = get_property;
259
260         /* signals */
261
262         /**
263          * SoupSession::request-queued:
264          * @session: the session
265          * @msg: the request that was queued
266          *
267          * Emitted when a request is queued on @session. (Note that
268          * "queued" doesn't just mean soup_session_queue_message();
269          * soup_session_send_message() implicitly queues the message
270          * as well.)
271          *
272          * When sending a request, first #SoupSession::request_queued
273          * is emitted, indicating that the session has become aware of
274          * the request.
275          *
276          * Once a connection is available to send the request on, the
277          * session emits #SoupSession::request_started. Then, various
278          * #SoupMessage signals are emitted as the message is
279          * processed. If the message is requeued, it will emit
280          * #SoupMessage::restarted, which will then be followed by
281          * another #SoupSession::request_started and another set of
282          * #SoupMessage signals when the message is re-sent.
283          *
284          * Eventually, the message will emit #SoupMessage::finished.
285          * Normally, this signals the completion of message
286          * processing. However, it is possible that the application
287          * will requeue the message from the "finished" handler (or
288          * equivalently, from the soup_session_queue_message()
289          * callback). In that case, the process will loop back to
290          * #SoupSession::request_started.
291          *
292          * Eventually, a message will reach "finished" and not be
293          * requeued. At that point, the session will emit
294          * #SoupSession::request_unqueued to indicate that it is done
295          * with the message.
296          *
297          * To sum up: #SoupSession::request_queued and
298          * #SoupSession::request_unqueued are guaranteed to be emitted
299          * exactly once, but #SoupSession::request_started and
300          * #SoupMessage::finished (and all of the other #SoupMessage
301          * signals) may be invoked multiple times for a given message.
302          **/
303         signals[REQUEST_QUEUED] =
304                 g_signal_new ("request-queued",
305                               G_OBJECT_CLASS_TYPE (object_class),
306                               G_SIGNAL_RUN_FIRST,
307                               0, /* FIXME? */
308                               NULL, NULL,
309                               soup_marshal_NONE__OBJECT,
310                               G_TYPE_NONE, 1,
311                               SOUP_TYPE_MESSAGE);
312
313         /**
314          * SoupSession::request-started:
315          * @session: the session
316          * @msg: the request being sent
317          * @socket: the socket the request is being sent on
318          *
319          * Emitted just before a request is sent. See
320          * #SoupSession::request_queued for a detailed description of
321          * the message lifecycle within a session.
322          **/
323         signals[REQUEST_STARTED] =
324                 g_signal_new ("request-started",
325                               G_OBJECT_CLASS_TYPE (object_class),
326                               G_SIGNAL_RUN_FIRST,
327                               G_STRUCT_OFFSET (SoupSessionClass, request_started),
328                               NULL, NULL,
329                               soup_marshal_NONE__OBJECT_OBJECT,
330                               G_TYPE_NONE, 2,
331                               SOUP_TYPE_MESSAGE,
332                               SOUP_TYPE_SOCKET);
333
334         /**
335          * SoupSession::request-unqueued:
336          * @session: the session
337          * @msg: the request that was unqueued
338          *
339          * Emitted when a request is removed from @session's queue,
340          * indicating that @session is done with it. See
341          * #SoupSession::request_queued for a detailed description of the
342          * message lifecycle within a session.
343          **/
344         signals[REQUEST_UNQUEUED] =
345                 g_signal_new ("request-unqueued",
346                               G_OBJECT_CLASS_TYPE (object_class),
347                               G_SIGNAL_RUN_FIRST,
348                               0, /* FIXME? */
349                               NULL, NULL,
350                               soup_marshal_NONE__OBJECT,
351                               G_TYPE_NONE, 1,
352                               SOUP_TYPE_MESSAGE);
353
354         /**
355          * SoupSession::authenticate:
356          * @session: the session
357          * @msg: the #SoupMessage being sent
358          * @auth: the #SoupAuth to authenticate
359          * @retrying: %TRUE if this is the second (or later) attempt
360          *
361          * Emitted when the session requires authentication. If
362          * credentials are available call soup_auth_authenticate() on
363          * @auth. If these credentials fail, the signal will be
364          * emitted again, with @retrying set to %TRUE, which will
365          * continue until you return without calling
366          * soup_auth_authenticate() on @auth.
367          *
368          * Note that this may be emitted before @msg's body has been
369          * fully read.
370          *
371          * If you call soup_session_pause_message() on @msg before
372          * returning, then you can authenticate @auth asynchronously
373          * (as long as you g_object_ref() it to make sure it doesn't
374          * get destroyed), and then unpause @msg when you are ready
375          * for it to continue.
376          **/
377         signals[AUTHENTICATE] =
378                 g_signal_new ("authenticate",
379                               G_OBJECT_CLASS_TYPE (object_class),
380                               G_SIGNAL_RUN_FIRST,
381                               G_STRUCT_OFFSET (SoupSessionClass, authenticate),
382                               NULL, NULL,
383                               soup_marshal_NONE__OBJECT_OBJECT_BOOLEAN,
384                               G_TYPE_NONE, 3,
385                               SOUP_TYPE_MESSAGE,
386                               SOUP_TYPE_AUTH,
387                               G_TYPE_BOOLEAN);
388
389         /* properties */
390         g_object_class_install_property (
391                 object_class, PROP_PROXY_URI,
392                 g_param_spec_boxed (SOUP_SESSION_PROXY_URI,
393                                     "Proxy URI",
394                                     "The HTTP Proxy to use for this session",
395                                     SOUP_TYPE_URI,
396                                     G_PARAM_READWRITE));
397         g_object_class_install_property (
398                 object_class, PROP_MAX_CONNS,
399                 g_param_spec_int (SOUP_SESSION_MAX_CONNS,
400                                   "Max Connection Count",
401                                   "The maximum number of connections that the session can open at once",
402                                   1,
403                                   G_MAXINT,
404                                   SOUP_SESSION_MAX_CONNS_DEFAULT,
405                                   G_PARAM_READWRITE));
406         g_object_class_install_property (
407                 object_class, PROP_MAX_CONNS_PER_HOST,
408                 g_param_spec_int (SOUP_SESSION_MAX_CONNS_PER_HOST,
409                                   "Max Per-Host Connection Count",
410                                   "The maximum number of connections that the session can open at once to a given host",
411                                   1,
412                                   G_MAXINT,
413                                   SOUP_SESSION_MAX_CONNS_PER_HOST_DEFAULT,
414                                   G_PARAM_READWRITE));
415         g_object_class_install_property (
416                 object_class, PROP_IDLE_TIMEOUT,
417                 g_param_spec_uint (SOUP_SESSION_IDLE_TIMEOUT,
418                                    "Idle Timeout",
419                                    "Connection lifetime when idle",
420                                    0, G_MAXUINT, 0,
421                                    G_PARAM_READWRITE));
422         g_object_class_install_property (
423                 object_class, PROP_USE_NTLM,
424                 g_param_spec_boolean (SOUP_SESSION_USE_NTLM,
425                                       "Use NTLM",
426                                       "Whether or not to use NTLM authentication",
427                                       FALSE,
428                                       G_PARAM_READWRITE));
429         g_object_class_install_property (
430                 object_class, PROP_SSL_CA_FILE,
431                 g_param_spec_string (SOUP_SESSION_SSL_CA_FILE,
432                                      "SSL CA file",
433                                      "File containing SSL CA certificates",
434                                      NULL,
435                                      G_PARAM_READWRITE));
436         g_object_class_install_property (
437                 object_class, PROP_ASYNC_CONTEXT,
438                 g_param_spec_pointer (SOUP_SESSION_ASYNC_CONTEXT,
439                                       "Async GMainContext",
440                                       "The GMainContext to dispatch async I/O in",
441                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
442         g_object_class_install_property (
443                 object_class, PROP_TIMEOUT,
444                 g_param_spec_uint (SOUP_SESSION_TIMEOUT,
445                                    "Timeout value",
446                                    "Value in seconds to timeout a blocking I/O",
447                                    0, G_MAXUINT, 0,
448                                    G_PARAM_READWRITE));
449
450         /**
451          * SoupSession:user-agent:
452          *
453          * If non-%NULL, the value to use for the "User-Agent" header
454          * on #SoupMessage<!-- -->s sent from this session.
455          *
456          * RFC 2616 says: "The User-Agent request-header field
457          * contains information about the user agent originating the
458          * request. This is for statistical purposes, the tracing of
459          * protocol violations, and automated recognition of user
460          * agents for the sake of tailoring responses to avoid
461          * particular user agent limitations. User agents SHOULD
462          * include this field with requests."
463          *
464          * The User-Agent header contains a list of one or more
465          * product tokens, separated by whitespace, with the most
466          * significant product token coming first. The tokens must be
467          * brief, ASCII, and mostly alphanumeric (although "-", "_",
468          * and "." are also allowed), and may optionally include a "/"
469          * followed by a version string. You may also put comments,
470          * enclosed in parentheses, between or after the tokens.
471          *
472          * If you set a %user_agent property that has trailing
473          * whitespace, #SoupSession will append its own product token
474          * (eg, "<literal>libsoup/2.3.2</literal>") to the end of the
475          * header for you.
476          **/
477         g_object_class_install_property (
478                 object_class, PROP_USER_AGENT,
479                 g_param_spec_string (SOUP_SESSION_USER_AGENT,
480                                      "User-Agent string",
481                                      "User-Agent string",
482                                      NULL,
483                                      G_PARAM_READWRITE));
484
485         g_object_class_install_property (
486                 object_class, PROP_ADD_FEATURE,
487                 g_param_spec_object (SOUP_SESSION_ADD_FEATURE,
488                                      "Add Feature",
489                                      "Add a feature object to the session",
490                                      SOUP_TYPE_SESSION_FEATURE,
491                                      G_PARAM_READWRITE));
492         g_object_class_install_property (
493                 object_class, PROP_ADD_FEATURE_BY_TYPE,
494                 g_param_spec_gtype (SOUP_SESSION_ADD_FEATURE_BY_TYPE,
495                                     "Add Feature By Type",
496                                     "Add a feature object of the given type to the session",
497                                     SOUP_TYPE_SESSION_FEATURE,
498                                     G_PARAM_READWRITE));
499         g_object_class_install_property (
500                 object_class, PROP_REMOVE_FEATURE_BY_TYPE,
501                 g_param_spec_gtype (SOUP_SESSION_REMOVE_FEATURE_BY_TYPE,
502                                     "Remove Feature By Type",
503                                     "Remove features of the given type from the session",
504                                     SOUP_TYPE_SESSION_FEATURE,
505                                     G_PARAM_READWRITE));
506 }
507
508 static gboolean
509 safe_uri_equal (SoupURI *a, SoupURI *b)
510 {
511         if (!a && !b)
512                 return TRUE;
513
514         if ((a && !b) || (b && !a))
515                 return FALSE;
516
517         return soup_uri_equal (a, b);
518 }
519
520 static gboolean
521 safe_str_equal (const char *a, const char *b)
522 {
523         if (!a && !b)
524                 return TRUE;
525
526         if ((a && !b) || (b && !a))
527                 return FALSE;
528
529         return strcmp (a, b) == 0;
530 }
531
532 static void
533 set_property (GObject *object, guint prop_id,
534               const GValue *value, GParamSpec *pspec)
535 {
536         SoupSession *session = SOUP_SESSION (object);
537         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
538         SoupURI *uri;
539         gboolean need_abort = FALSE;
540         gboolean ca_file_changed = FALSE;
541         const char *new_ca_file, *user_agent;
542
543         switch (prop_id) {
544         case PROP_PROXY_URI:
545                 uri = g_value_get_boxed (value);
546
547                 if (!safe_uri_equal (priv->proxy_uri, uri))
548                         need_abort = TRUE;
549
550                 if (priv->proxy_uri)
551                         soup_uri_free (priv->proxy_uri);
552                 if (priv->proxy_addr)
553                         g_object_unref (priv->proxy_addr);
554
555                 priv->proxy_uri = uri ? soup_uri_copy (uri) : NULL;
556                 priv->proxy_addr = uri ?
557                         soup_address_new (uri->host, uri->port) :
558                         NULL;
559
560                 if (need_abort) {
561                         soup_session_abort (session);
562                         cleanup_hosts (priv);
563                 }
564
565                 break;
566         case PROP_MAX_CONNS:
567                 priv->max_conns = g_value_get_int (value);
568                 break;
569         case PROP_MAX_CONNS_PER_HOST:
570                 priv->max_conns_per_host = g_value_get_int (value);
571                 break;
572         case PROP_USE_NTLM:
573                 g_object_set_property (G_OBJECT (priv->auth_manager),
574                                        SOUP_AUTH_MANAGER_NTLM_USE_NTLM,
575                                        value);
576                 break;
577         case PROP_SSL_CA_FILE:
578                 new_ca_file = g_value_get_string (value);
579
580                 if (!safe_str_equal (priv->ssl_ca_file, new_ca_file))
581                         ca_file_changed = TRUE;
582
583                 g_free (priv->ssl_ca_file);
584                 priv->ssl_ca_file = g_strdup (new_ca_file);
585
586                 if (ca_file_changed) {
587                         if (priv->ssl_creds) {
588                                 soup_ssl_free_client_credentials (priv->ssl_creds);
589                                 priv->ssl_creds = NULL;
590                         }
591
592                         cleanup_hosts (priv);
593                 }
594
595                 break;
596         case PROP_ASYNC_CONTEXT:
597                 priv->async_context = g_value_get_pointer (value);
598                 if (priv->async_context)
599                         g_main_context_ref (priv->async_context);
600                 break;
601         case PROP_TIMEOUT:
602                 priv->io_timeout = g_value_get_uint (value);
603                 break;
604         case PROP_USER_AGENT:
605                 g_free (priv->user_agent);
606                 user_agent = g_value_get_string (value);
607                 if (!user_agent)
608                         priv->user_agent = NULL;
609                 else if (!*user_agent) {
610                         priv->user_agent =
611                                 g_strdup (SOUP_SESSION_USER_AGENT_BASE);
612                 } else if (g_str_has_suffix (user_agent, " ")) {
613                         priv->user_agent =
614                                 g_strdup_printf ("%s%s", user_agent,
615                                                  SOUP_SESSION_USER_AGENT_BASE);
616                 } else
617                         priv->user_agent = g_strdup (user_agent);
618                 break;
619         case PROP_IDLE_TIMEOUT:
620                 priv->idle_timeout = g_value_get_uint (value);
621                 break;
622         case PROP_ADD_FEATURE:
623                 soup_session_add_feature (session, g_value_get_object (value));
624                 break;
625         case PROP_ADD_FEATURE_BY_TYPE:
626                 soup_session_add_feature_by_type (session, g_value_get_gtype (value));
627                 break;
628         case PROP_REMOVE_FEATURE_BY_TYPE:
629                 soup_session_remove_feature_by_type (session, g_value_get_gtype (value));
630                 break;
631         default:
632                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
633                 break;
634         }
635 }
636
637 static void
638 get_property (GObject *object, guint prop_id,
639               GValue *value, GParamSpec *pspec)
640 {
641         SoupSession *session = SOUP_SESSION (object);
642         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
643
644         switch (prop_id) {
645         case PROP_PROXY_URI:
646                 g_value_set_boxed (value, priv->proxy_uri);
647                 break;
648         case PROP_MAX_CONNS:
649                 g_value_set_int (value, priv->max_conns);
650                 break;
651         case PROP_MAX_CONNS_PER_HOST:
652                 g_value_set_int (value, priv->max_conns_per_host);
653                 break;
654         case PROP_USE_NTLM:
655                 g_object_get_property (G_OBJECT (priv->auth_manager),
656                                        SOUP_AUTH_MANAGER_NTLM_USE_NTLM,
657                                        value);
658                 break;
659         case PROP_SSL_CA_FILE:
660                 g_value_set_string (value, priv->ssl_ca_file);
661                 break;
662         case PROP_ASYNC_CONTEXT:
663                 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
664                 break;
665         case PROP_TIMEOUT:
666                 g_value_set_uint (value, priv->io_timeout);
667                 break;
668         case PROP_USER_AGENT:
669                 g_value_set_string (value, priv->user_agent);
670                 break;
671         case PROP_IDLE_TIMEOUT:
672                 g_value_set_uint (value, priv->idle_timeout);
673                 break;
674         default:
675                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
676                 break;
677         }
678 }
679
680
681 /**
682  * soup_session_get_async_context:
683  * @session: a #SoupSession
684  *
685  * Gets @session's async_context. This does not add a ref to the
686  * context, so you will need to ref it yourself if you want it to
687  * outlive its session.
688  *
689  * Return value: @session's #GMainContext, which may be %NULL
690  **/
691 GMainContext *
692 soup_session_get_async_context (SoupSession *session)
693 {
694         SoupSessionPrivate *priv;
695
696         g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
697         priv = SOUP_SESSION_GET_PRIVATE (session);
698
699         return priv->async_context;
700 }
701
702 /* Hosts */
703
704 static SoupSessionHost *
705 soup_session_host_new (SoupSession *session, SoupAddress *addr)
706 {
707         SoupSessionHost *host;
708
709         host = g_slice_new0 (SoupSessionHost);
710         host->addr = g_object_ref (addr);
711         return host;
712 }
713
714 /* Note: get_host_for_message doesn't lock the host_lock. The caller
715  * must do it itself if there's a chance the host doesn't already
716  * exist.
717  */
718 static SoupSessionHost *
719 get_host_for_message (SoupSession *session, SoupMessage *msg)
720 {
721         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
722         SoupSessionHost *host;
723         SoupAddress *addr = soup_message_get_address (msg);
724
725         host = g_hash_table_lookup (priv->hosts, addr);
726         if (host)
727                 return host;
728
729         host = soup_session_host_new (session, addr);
730         g_hash_table_insert (priv->hosts, host->addr, host);
731
732         return host;
733 }
734
735 static void
736 free_host (SoupSessionHost *host)
737 {
738         while (host->connections) {
739                 SoupConnection *conn = host->connections->data;
740
741                 host->connections = g_slist_remove (host->connections, conn);
742                 soup_connection_disconnect (conn);
743         }
744
745         g_object_unref (host->addr);
746         g_slice_free (SoupSessionHost, host);
747 }       
748
749 static void
750 auth_manager_authenticate (SoupAuthManager *manager, SoupMessage *msg,
751                            SoupAuth *auth, gboolean retrying,
752                            gpointer session)
753 {
754         g_signal_emit (session, signals[AUTHENTICATE], 0, msg, auth, retrying);
755 }
756
757 #define SOUP_METHOD_IS_SAFE(method) (method == SOUP_METHOD_GET || \
758                                      method == SOUP_METHOD_HEAD || \
759                                      method == SOUP_METHOD_OPTIONS || \
760                                      method == SOUP_METHOD_PROPFIND)
761
762 static void
763 redirect_handler (SoupMessage *msg, gpointer user_data)
764 {
765         SoupSession *session = user_data;
766         const char *new_loc;
767         SoupURI *new_uri;
768
769         new_loc = soup_message_headers_get (msg->response_headers, "Location");
770         g_return_if_fail (new_loc != NULL);
771
772         if (msg->status_code == SOUP_STATUS_SEE_OTHER ||
773             (msg->status_code == SOUP_STATUS_FOUND &&
774              !SOUP_METHOD_IS_SAFE (msg->method))) {
775                 /* Redirect using a GET */
776                 g_object_set (msg,
777                               SOUP_MESSAGE_METHOD, SOUP_METHOD_GET,
778                               NULL);
779                 soup_message_set_request (msg, NULL,
780                                           SOUP_MEMORY_STATIC, NULL, 0);
781                 soup_message_headers_set_encoding (msg->request_headers,
782                                                    SOUP_ENCODING_NONE);
783         } else if (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY ||
784                    msg->status_code == SOUP_STATUS_TEMPORARY_REDIRECT ||
785                    msg->status_code == SOUP_STATUS_FOUND) {
786                 /* Don't redirect non-safe methods */
787                 if (!SOUP_METHOD_IS_SAFE (msg->method))
788                         return;
789         } else {
790                 /* Three possibilities:
791                  *
792                  *   1) This was a non-3xx response that happened to
793                  *      have a "Location" header
794                  *   2) It's a non-redirecty 3xx response (300, 304,
795                  *      305, 306)
796                  *   3) It's some newly-defined 3xx response (308+)
797                  *
798                  * We ignore all of these cases. In the first two,
799                  * redirecting would be explicitly wrong, and in the
800                  * last case, we have no clue if the 3xx response is
801                  * supposed to be redirecty or non-redirecty. Plus,
802                  * 2616 says unrecognized status codes should be
803                  * treated as the equivalent to the x00 code, and we
804                  * don't redirect on 300, so therefore we shouldn't
805                  * redirect on 308+ either.
806                  */
807                 return;
808         }
809
810         /* Location is supposed to be an absolute URI, but some sites
811          * are lame, so we use soup_uri_new_with_base().
812          */
813         new_uri = soup_uri_new_with_base (soup_message_get_uri (msg), new_loc);
814         if (!new_uri) {
815                 soup_message_set_status_full (msg,
816                                               SOUP_STATUS_MALFORMED,
817                                               "Invalid Redirect URL");
818                 return;
819         }
820
821         soup_message_set_uri (msg, new_uri);
822         soup_uri_free (new_uri);
823
824         soup_session_requeue_message (session, msg);
825 }
826
827 static void
828 connection_started_request (SoupConnection *conn, SoupMessage *msg,
829                             gpointer data)
830 {
831         SoupSession *session = data;
832         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
833
834         if (priv->user_agent) {
835                 soup_message_headers_replace (msg->request_headers,
836                                               "User-Agent", priv->user_agent);
837         }
838
839         /* Kludge to deal with the fact that CONNECT msgs come from the
840          * SoupConnection rather than being queued normally.
841          */
842         if (msg->method == SOUP_METHOD_CONNECT)
843                 g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
844
845         g_signal_emit (session, signals[REQUEST_STARTED], 0,
846                        msg, soup_connection_get_socket (conn));
847 }
848
849 gboolean
850 soup_session_try_prune_connection (SoupSession *session)
851 {
852         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
853         GPtrArray *conns;
854         GHashTableIter iter;
855         gpointer conn, host;
856         int i;
857
858         conns = g_ptr_array_new ();
859
860         g_mutex_lock (priv->host_lock);
861         g_hash_table_iter_init (&iter, priv->conns);
862         while (g_hash_table_iter_next (&iter, &conn, &host)) {
863                 /* Don't prune a connection that is currently in use,
864                  * or hasn't been used yet.
865                  */
866                 if (!soup_connection_is_in_use (conn) &&
867                     soup_connection_last_used (conn) > 0)
868                         g_ptr_array_add (conns, g_object_ref (conn));
869         }
870         g_mutex_unlock (priv->host_lock);
871
872         if (!conns->len) {
873                 g_ptr_array_free (conns, TRUE);
874                 return FALSE;
875         }
876
877         for (i = 0; i < conns->len; i++) {
878                 soup_connection_disconnect (conns->pdata[i]);
879                 g_object_unref (conns->pdata[i]);
880         }
881         g_ptr_array_free (conns, TRUE);
882
883         return TRUE;
884 }
885
886 static void
887 connection_disconnected (SoupConnection *conn, gpointer user_data)
888 {
889         SoupSession *session = user_data;
890         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
891         SoupSessionHost *host;
892
893         g_mutex_lock (priv->host_lock);
894
895         host = g_hash_table_lookup (priv->conns, conn);
896         if (host) {
897                 g_hash_table_remove (priv->conns, conn);
898                 host->connections = g_slist_remove (host->connections, conn);
899                 host->num_conns--;
900         }
901
902         g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
903         priv->num_conns--;
904
905         g_mutex_unlock (priv->host_lock);
906         g_object_unref (conn);
907 }
908
909 static void
910 connect_result (SoupConnection *conn, guint status, gpointer user_data)
911 {
912         SoupSession *session = user_data;
913         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
914         SoupSessionHost *host;
915         SoupMessageQueueItem *item;
916         SoupMessage *msg;
917
918         g_mutex_lock (priv->host_lock);
919
920         host = g_hash_table_lookup (priv->conns, conn);
921         if (!host) {
922                 g_mutex_unlock (priv->host_lock);
923                 return;
924         }
925
926         if (status == SOUP_STATUS_OK) {
927                 soup_connection_reserve (conn);
928                 host->connections = g_slist_prepend (host->connections, conn);
929                 g_mutex_unlock (priv->host_lock);
930                 return;
931         }
932
933         /* The connection failed. */
934         g_mutex_unlock (priv->host_lock);
935         connection_disconnected (conn, session);
936
937         if (host->connections) {
938                 /* Something went wrong this time, but we have at
939                  * least one open connection to this host. So just
940                  * leave the message in the queue so it can use that
941                  * connection once it's free.
942                  */
943                 return;
944         }
945
946         /* There are two possibilities: either status is
947          * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
948          * will create a new connection (and all we need to do here
949          * is downgrade the message from CONNECTING to QUEUED); or
950          * status is something else, probably CANT_CONNECT or
951          * CANT_RESOLVE or the like, in which case we need to cancel
952          * any messages waiting for this host, since they're out
953          * of luck.
954          */
955         g_object_ref (session);
956         for (item = soup_message_queue_first (priv->queue); item; item = soup_message_queue_next (priv->queue, item)) {
957                 msg = item->msg;
958                 if (get_host_for_message (session, msg) == host) {
959                         if (status == SOUP_STATUS_TRY_AGAIN) {
960                                 if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING)
961                                         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
962                         } else {
963                                 soup_session_cancel_message (session, msg,
964                                                              status);
965                         }
966                 }
967         }
968         g_object_unref (session);
969 }
970
971 /**
972  * soup_session_get_connection:
973  * @session: a #SoupSession
974  * @msg: a #SoupMessage
975  * @try_pruning: on return, whether or not to try pruning a connection
976  * @is_new: on return, %TRUE if the returned connection is new and not
977  * yet connected
978  * 
979  * Tries to find or create a connection for @msg; this is an internal
980  * method for #SoupSession subclasses.
981  *
982  * If there is an idle connection to the relevant host available, then
983  * that connection will be returned (with *@is_new set to %FALSE). The
984  * connection will be marked "reserved", so the caller must call
985  * soup_connection_release() if it ends up not using the connection
986  * right away.
987  *
988  * If there is no idle connection available, but it is possible to
989  * create a new connection, then one will be created and returned,
990  * with *@is_new set to %TRUE. The caller MUST then call
991  * soup_connection_connect_sync() or soup_connection_connect_async()
992  * to connect it. If the connection attempt succeeds, the connection
993  * will be marked "reserved" and added to @session's connection pool
994  * once it connects. If the connection attempt fails, the connection
995  * will be unreffed.
996  *
997  * If no connection is available and a new connection cannot be made,
998  * soup_session_get_connection() will return %NULL. If @session has
999  * the maximum number of open connections open, but does not have the
1000  * maximum number of per-host connections open to the relevant host,
1001  * then *@try_pruning will be set to %TRUE. In this case, the caller
1002  * can call soup_session_try_prune_connection() to close an idle
1003  * connection, and then try soup_session_get_connection() again. (If
1004  * calling soup_session_try_prune_connection() wouldn't help, then
1005  * *@try_pruning is left untouched; it is NOT set to %FALSE.)
1006  *
1007  * Return value: a #SoupConnection, or %NULL
1008  **/
1009 SoupConnection *
1010 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
1011                              gboolean *try_pruning, gboolean *is_new)
1012 {
1013         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1014         SoupConnection *conn;
1015         SoupSessionHost *host;
1016         SoupSSLCredentials *ssl_creds;
1017         GSList *conns;
1018         SoupURI *uri;
1019
1020         g_mutex_lock (priv->host_lock);
1021
1022         host = get_host_for_message (session, msg);
1023         for (conns = host->connections; conns; conns = conns->next) {
1024                 if (!soup_connection_is_in_use (conns->data)) {
1025                         soup_connection_reserve (conns->data);
1026                         g_mutex_unlock (priv->host_lock);
1027                         *is_new = FALSE;
1028                         return conns->data;
1029                 }
1030         }
1031
1032         if (soup_message_get_io_status (msg) == SOUP_MESSAGE_IO_STATUS_CONNECTING) {
1033                 /* We already started a connection for this
1034                  * message, so don't start another one.
1035                  */
1036                 g_mutex_unlock (priv->host_lock);
1037                 return NULL;
1038         }
1039
1040         if (host->num_conns >= priv->max_conns_per_host) {
1041                 g_mutex_unlock (priv->host_lock);
1042                 return NULL;
1043         }
1044
1045         if (priv->num_conns >= priv->max_conns) {
1046                 *try_pruning = TRUE;
1047                 g_mutex_unlock (priv->host_lock);
1048                 return NULL;
1049         }
1050
1051         uri = soup_message_get_uri (msg);
1052         if (uri->scheme == SOUP_URI_SCHEME_HTTPS) {
1053                 if (!priv->ssl_creds)
1054                         priv->ssl_creds = soup_ssl_get_client_credentials (priv->ssl_ca_file);
1055                 ssl_creds = priv->ssl_creds;
1056         } else
1057                 ssl_creds = NULL;
1058
1059         conn = soup_connection_new (
1060                 SOUP_CONNECTION_SERVER_ADDRESS, host->addr,
1061                 SOUP_CONNECTION_PROXY_ADDRESS, priv->proxy_addr,
1062                 SOUP_CONNECTION_SSL_CREDENTIALS, ssl_creds,
1063                 SOUP_CONNECTION_ASYNC_CONTEXT, priv->async_context,
1064                 SOUP_CONNECTION_TIMEOUT, priv->io_timeout,
1065                 SOUP_CONNECTION_IDLE_TIMEOUT, priv->idle_timeout,
1066                 NULL);
1067         g_signal_connect (conn, "connect_result",
1068                           G_CALLBACK (connect_result),
1069                           session);
1070         g_signal_connect (conn, "disconnected",
1071                           G_CALLBACK (connection_disconnected),
1072                           session);
1073         g_signal_connect (conn, "request_started",
1074                           G_CALLBACK (connection_started_request),
1075                           session);
1076
1077         g_hash_table_insert (priv->conns, conn, host);
1078
1079         /* We increment the connection counts so it counts against the
1080          * totals, but we don't add it to the host's connection list
1081          * yet, since it's not ready for use.
1082          */
1083         priv->num_conns++;
1084         host->num_conns++;
1085
1086         /* Mark the request as connecting, so we don't try to open
1087          * another new connection for it while waiting for this one.
1088          */
1089         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_CONNECTING);
1090
1091         g_mutex_unlock (priv->host_lock);
1092         *is_new = TRUE;
1093         return conn;
1094 }
1095
1096 SoupMessageQueue *
1097 soup_session_get_queue (SoupSession *session)
1098 {
1099         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1100
1101         return priv->queue;
1102 }
1103
1104 static void
1105 message_finished (SoupMessage *msg, gpointer user_data)
1106 {
1107         SoupMessageQueueItem *item = user_data;
1108         SoupSession *session = item->session;
1109         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1110
1111         if (!SOUP_MESSAGE_IS_STARTING (msg)) {
1112                 soup_message_queue_remove (priv->queue, item);
1113                 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
1114                 g_signal_handlers_disconnect_by_func (msg, redirect_handler, session);
1115                 g_signal_emit (session, signals[REQUEST_UNQUEUED], 0, msg);
1116                 soup_message_queue_item_unref (item);
1117         }
1118 }
1119
1120 static void
1121 queue_message (SoupSession *session, SoupMessage *msg,
1122                SoupSessionCallback callback, gpointer user_data)
1123 {
1124         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1125         SoupMessageQueueItem *item;
1126
1127         item = soup_message_queue_append (priv->queue, msg, callback, user_data);
1128         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1129
1130         g_signal_connect_after (msg, "finished",
1131                                 G_CALLBACK (message_finished), item);
1132
1133         if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
1134                 soup_message_add_header_handler (
1135                         msg, "got_body", "Location",
1136                         G_CALLBACK (redirect_handler), session);
1137         }
1138
1139         g_signal_emit (session, signals[REQUEST_QUEUED], 0, msg);
1140 }
1141
1142 /**
1143  * SoupSessionCallback:
1144  * @session: the session
1145  * @msg: the message that has finished
1146  * @user_data: the data passed to soup_session_queue_message
1147  *
1148  * Prototype for the callback passed to soup_session_queue_message(),
1149  * qv.
1150  **/
1151
1152 /**
1153  * soup_session_queue_message:
1154  * @session: a #SoupSession
1155  * @msg: the message to queue
1156  * @callback: a #SoupSessionCallback which will be called after the
1157  * message completes or when an unrecoverable error occurs.
1158  * @user_data: a pointer passed to @callback.
1159  * 
1160  * Queues the message @msg for sending. All messages are processed
1161  * while the glib main loop runs. If @msg has been processed before,
1162  * any resources related to the time it was last sent are freed.
1163  *
1164  * Upon message completion, the callback specified in @callback will
1165  * be invoked (in the thread associated with @session's async
1166  * context). If after returning from this callback the message has not
1167  * been requeued, @msg will be unreffed.
1168  */
1169 void
1170 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1171                             SoupSessionCallback callback, gpointer user_data)
1172 {
1173         g_return_if_fail (SOUP_IS_SESSION (session));
1174         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1175
1176         SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1177                                                          callback, user_data);
1178 }
1179
1180 static void
1181 requeue_message (SoupSession *session, SoupMessage *msg)
1182 {
1183         soup_message_set_io_status (msg, SOUP_MESSAGE_IO_STATUS_QUEUED);
1184 }
1185
1186 /**
1187  * soup_session_requeue_message:
1188  * @session: a #SoupSession
1189  * @msg: the message to requeue
1190  *
1191  * This causes @msg to be placed back on the queue to be attempted
1192  * again.
1193  **/
1194 void
1195 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
1196 {
1197         g_return_if_fail (SOUP_IS_SESSION (session));
1198         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1199
1200         SOUP_SESSION_GET_CLASS (session)->requeue_message (session, msg);
1201 }
1202
1203
1204 /**
1205  * soup_session_send_message:
1206  * @session: a #SoupSession
1207  * @msg: the message to send
1208  * 
1209  * Synchronously send @msg. This call will not return until the
1210  * transfer is finished successfully or there is an unrecoverable
1211  * error.
1212  *
1213  * @msg is not freed upon return.
1214  *
1215  * Return value: the HTTP status code of the response
1216  */
1217 guint
1218 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1219 {
1220         g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1221         g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1222
1223         return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1224 }
1225
1226
1227 /**
1228  * soup_session_pause_message:
1229  * @session: a #SoupSession
1230  * @msg: a #SoupMessage currently running on @session
1231  *
1232  * Pauses HTTP I/O on @msg. Call soup_session_unpause_message() to
1233  * resume I/O.
1234  **/
1235 void
1236 soup_session_pause_message (SoupSession *session,
1237                             SoupMessage *msg)
1238 {
1239         g_return_if_fail (SOUP_IS_SESSION (session));
1240         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1241
1242         soup_message_io_pause (msg);
1243 }
1244
1245 /**
1246  * soup_session_unpause_message:
1247  * @session: a #SoupSession
1248  * @msg: a #SoupMessage currently running on @session
1249  *
1250  * Resumes HTTP I/O on @msg. Use this to resume after calling
1251  * soup_sessino_pause_message().
1252  *
1253  * If @msg is being sent via blocking I/O, this will resume reading or
1254  * writing immediately. If @msg is using non-blocking I/O, then
1255  * reading or writing won't resume until you return to the main loop.
1256  **/
1257 void
1258 soup_session_unpause_message (SoupSession *session,
1259                               SoupMessage *msg)
1260 {
1261         g_return_if_fail (SOUP_IS_SESSION (session));
1262         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1263
1264         soup_message_io_unpause (msg);
1265 }
1266
1267
1268 static void
1269 cancel_message (SoupSession *session, SoupMessage *msg, guint status_code)
1270 {
1271         SoupSessionPrivate *priv = SOUP_SESSION_GET_PRIVATE (session);
1272         SoupMessageQueueItem *item;
1273
1274         item = soup_message_queue_lookup (priv->queue, msg);
1275         if (item) {
1276                 soup_message_queue_remove (priv->queue, item);
1277                 if (item->cancellable)
1278                         g_cancellable_cancel (item->cancellable);
1279                 soup_message_queue_item_unref (item);
1280         }
1281
1282         soup_message_io_stop (msg);
1283         soup_message_set_status (msg, status_code);
1284         soup_message_finished (msg);
1285 }
1286
1287 /**
1288  * soup_session_cancel_message:
1289  * @session: a #SoupSession
1290  * @msg: the message to cancel
1291  * @status_code: status code to set on @msg (generally
1292  * %SOUP_STATUS_CANCELLED)
1293  *
1294  * Causes @session to immediately finish processing @msg, with a final
1295  * status_code of @status_code. Depending on when you cancel it, the
1296  * response state may be incomplete or inconsistent.
1297  **/
1298 void
1299 soup_session_cancel_message (SoupSession *session, SoupMessage *msg,
1300                              guint status_code)
1301 {
1302         g_return_if_fail (SOUP_IS_SESSION (session));
1303         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1304
1305         SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg, status_code);
1306 }
1307
1308 static void
1309 gather_conns (gpointer key, gpointer host, gpointer data)
1310 {
1311         SoupConnection *conn = key;
1312         GSList **conns = data;
1313
1314         *conns = g_slist_prepend (*conns, g_object_ref (conn));
1315 }
1316
1317 /**
1318  * soup_session_abort:
1319  * @session: the session
1320  *
1321  * Cancels all pending requests in @session.
1322  **/
1323 void
1324 soup_session_abort (SoupSession *session)
1325 {
1326         SoupSessionPrivate *priv;
1327         SoupMessageQueueItem *item;
1328         GSList *conns, *c;
1329
1330         g_return_if_fail (SOUP_IS_SESSION (session));
1331         priv = SOUP_SESSION_GET_PRIVATE (session);
1332
1333         for (item = soup_message_queue_first (priv->queue);
1334              item;
1335              item = soup_message_queue_next (priv->queue, item)) {
1336                 soup_session_cancel_message (session, item->msg,
1337                                              SOUP_STATUS_CANCELLED);
1338         }
1339
1340         /* Close all connections */
1341         g_mutex_lock (priv->host_lock);
1342         conns = NULL;
1343         g_hash_table_foreach (priv->conns, gather_conns, &conns);
1344
1345         g_mutex_unlock (priv->host_lock);
1346         for (c = conns; c; c = c->next) {
1347                 soup_connection_disconnect (c->data);
1348                 g_object_unref (c->data);
1349         }
1350
1351         g_slist_free (conns);
1352 }
1353
1354 /**
1355  * soup_session_add_feature:
1356  * @session: a #SoupSession
1357  * @feature: an object that implements #SoupSessionFeature
1358  *
1359  * Adds @feature's functionality to @session. You can also add a
1360  * feature to the session at construct time by using the
1361  * %SOUP_SESSION_ADD_FEATURE property.
1362  **/
1363 void
1364 soup_session_add_feature (SoupSession *session, SoupSessionFeature *feature)
1365 {
1366         SoupSessionPrivate *priv;
1367
1368         g_return_if_fail (SOUP_IS_SESSION (session));
1369         g_return_if_fail (SOUP_IS_SESSION_FEATURE (feature));
1370
1371         priv = SOUP_SESSION_GET_PRIVATE (session);
1372         priv->features = g_slist_prepend (priv->features, g_object_ref (feature));
1373         soup_session_feature_attach (feature, session);
1374 }
1375
1376 /**
1377  * soup_session_add_feature_by_type:
1378  * @session: a #SoupSession
1379  * @feature_type: the #GType of a class that implements #SoupSessionFeature
1380  *
1381  * Creates a new feature of type @feature_type and adds it to
1382  * @session. You can use this instead of soup_session_add_feature() in
1383  * the case wher you don't need to customize the new feature in any
1384  * way. You can also add a feature to the session at construct time by
1385  * using the %SOUP_SESSION_ADD_FEATURE_BY_TYPE property.
1386  **/
1387 void
1388 soup_session_add_feature_by_type (SoupSession *session, GType feature_type)
1389 {
1390         SoupSessionFeature *feature;
1391
1392         g_return_if_fail (SOUP_IS_SESSION (session));
1393         g_return_if_fail (g_type_is_a (feature_type, SOUP_TYPE_SESSION_FEATURE));
1394
1395         feature = g_object_new (feature_type, NULL);
1396         soup_session_add_feature (session, feature);
1397         g_object_unref (feature);
1398 }
1399
1400 /**
1401  * soup_session_remove_feature:
1402  * @session: a #SoupSession
1403  * @feature: a feature that has previously been added to @session
1404  *
1405  * Removes @feature's functionality from @session.
1406  **/
1407 void
1408 soup_session_remove_feature (SoupSession *session, SoupSessionFeature *feature)
1409 {
1410         SoupSessionPrivate *priv;
1411
1412         g_return_if_fail (SOUP_IS_SESSION (session));
1413
1414         priv = SOUP_SESSION_GET_PRIVATE (session);
1415         if (g_slist_find (priv->features, feature)) {
1416                 priv->features = g_slist_remove (priv->features, feature);
1417                 soup_session_feature_detach (feature, session);
1418                 g_object_unref (feature);
1419         }
1420 }
1421
1422 /**
1423  * soup_session_remove_feature_by_type:
1424  * @session: a #SoupSession
1425  * @feature_type: the #GType of a class that implements #SoupSessionFeature
1426  *
1427  * Removes all features of type @feature_type (or any subclass of
1428  * @feature_type) from @session. You can also remove standard features
1429  * from the session at construct time by using the
1430  * %SOUP_SESSION_REMOVE_FEATURE_BY_TYPE property.
1431  **/
1432 void
1433 soup_session_remove_feature_by_type (SoupSession *session, GType feature_type)
1434 {
1435         SoupSessionPrivate *priv;
1436         GSList *f;
1437
1438         g_return_if_fail (SOUP_IS_SESSION (session));
1439
1440         priv = SOUP_SESSION_GET_PRIVATE (session);
1441 restart:
1442         for (f = priv->features; f; f = f->next) {
1443                 if (G_TYPE_CHECK_INSTANCE_TYPE (f->data, feature_type)) {
1444                         soup_session_remove_feature (session, f->data);
1445                         goto restart;
1446                 }
1447         }
1448 }