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