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