Call soup_message_io_stop so we don't get a callback on the io after it's
[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 gboolean
274 safe_str_equal (const char *a, const char *b)
275 {
276         if (!a && !b)
277                 return TRUE;
278
279         if ((a && !b) || (b && !a))
280                 return FALSE;
281
282         return strcmp (a, b) == 0;
283 }
284
285 static void
286 set_property (GObject *object, guint prop_id,
287               const GValue *value, GParamSpec *pspec)
288 {
289         SoupSession *session = SOUP_SESSION (object);
290         gpointer pval;
291         gboolean need_abort = FALSE;
292         gboolean ca_file_changed = FALSE;
293         const char *new_ca_file;
294
295         switch (prop_id) {
296         case PROP_PROXY_URI:
297                 pval = g_value_get_pointer (value);
298
299                 if (!safe_uri_equal (session->priv->proxy_uri, pval))
300                         need_abort = TRUE;
301
302                 if (session->priv->proxy_uri)
303                         soup_uri_free (session->priv->proxy_uri);
304
305                 session->priv->proxy_uri = pval ? soup_uri_copy (pval) : NULL;
306
307                 if (need_abort) {
308                         soup_session_abort (session);
309                         cleanup_hosts (session);
310                 }
311
312                 break;
313         case PROP_MAX_CONNS:
314                 session->priv->max_conns = g_value_get_int (value);
315                 break;
316         case PROP_MAX_CONNS_PER_HOST:
317                 session->priv->max_conns_per_host = g_value_get_int (value);
318                 break;
319         case PROP_USE_NTLM:
320                 session->priv->use_ntlm = g_value_get_boolean (value);
321                 break;
322         case PROP_SSL_CA_FILE:
323                 new_ca_file = g_value_get_string (value);
324
325                 if (!safe_str_equal (session->priv->ssl_ca_file, new_ca_file))
326                         ca_file_changed = TRUE;
327
328                 g_free (session->priv->ssl_ca_file);
329                 session->priv->ssl_ca_file = g_strdup (new_ca_file);
330
331                 if (ca_file_changed) {
332                         if (session->priv->ssl_creds) {
333                                 soup_ssl_free_client_credentials (session->priv->ssl_creds);
334                                 session->priv->ssl_creds = NULL;
335                         }
336
337                         cleanup_hosts (session);
338                 }
339
340                 break;
341         default:
342                 break;
343         }
344 }
345
346 static void
347 get_property (GObject *object, guint prop_id,
348               GValue *value, GParamSpec *pspec)
349 {
350         SoupSession *session = SOUP_SESSION (object);
351
352         switch (prop_id) {
353         case PROP_PROXY_URI:
354                 g_value_set_pointer (value, session->priv->proxy_uri ?
355                                      soup_uri_copy (session->priv->proxy_uri) :
356                                      NULL);
357                 break;
358         case PROP_MAX_CONNS:
359                 g_value_set_int (value, session->priv->max_conns);
360                 break;
361         case PROP_MAX_CONNS_PER_HOST:
362                 g_value_set_int (value, session->priv->max_conns_per_host);
363                 break;
364         case PROP_USE_NTLM:
365                 g_value_set_boolean (value, session->priv->use_ntlm);
366                 break;
367         case PROP_SSL_CA_FILE:
368                 g_value_set_string (value, session->priv->ssl_ca_file);
369                 break;
370         default:
371                 break;
372         }
373 }
374
375
376 /**
377  * soup_session_add_filter:
378  * @session: a #SoupSession
379  * @filter: an object implementing the #SoupMessageFilter interface
380  *
381  * Adds @filter to @session's list of message filters to be applied to
382  * all messages.
383  **/
384 void
385 soup_session_add_filter (SoupSession *session, SoupMessageFilter *filter)
386 {
387         g_return_if_fail (SOUP_IS_SESSION (session));
388         g_return_if_fail (SOUP_IS_MESSAGE_FILTER (filter));
389
390         session->priv->filters = g_slist_prepend (session->priv->filters,
391                                                   filter);
392 }
393
394 /**
395  * soup_session_remove_filter:
396  * @session: a #SoupSession
397  * @filter: an object implementing the #SoupMessageFilter interface
398  *
399  * Removes @filter from @session's list of message filters
400  **/
401 void
402 soup_session_remove_filter (SoupSession *session, SoupMessageFilter *filter)
403 {
404         g_return_if_fail (SOUP_IS_SESSION (session));
405         g_return_if_fail (SOUP_IS_MESSAGE_FILTER (filter));
406
407         session->priv->filters = g_slist_remove (session->priv->filters,
408                                                  filter);
409 }
410
411
412 /* Hosts */
413 static guint
414 host_uri_hash (gconstpointer key)
415 {
416         const SoupUri *uri = key;
417
418         return (uri->protocol << 16) + uri->port + g_str_hash (uri->host);
419 }
420
421 static gboolean
422 host_uri_equal (gconstpointer v1, gconstpointer v2)
423 {
424         const SoupUri *one = v1;
425         const SoupUri *two = v2;
426
427         if (one->protocol != two->protocol)
428                 return FALSE;
429         if (one->port != two->port)
430                 return FALSE;
431
432         return strcmp (one->host, two->host) == 0;
433 }
434
435 static SoupSessionHost *
436 soup_session_host_new (SoupSession *session, const SoupUri *source_uri)
437 {
438         SoupSessionHost *host;
439
440         host = g_new0 (SoupSessionHost, 1);
441         host->root_uri = soup_uri_copy_root (source_uri);
442
443         if (host->root_uri->protocol == SOUP_PROTOCOL_HTTPS &&
444             !session->priv->ssl_creds) {
445                 session->priv->ssl_creds =
446                         soup_ssl_get_client_credentials (session->priv->ssl_ca_file);
447         }
448
449         return host;
450 }
451
452 /* Note: get_host_for_message doesn't lock the host_lock. The caller
453  * must do it itself if there's a chance the host doesn't already
454  * exist.
455  */
456 static SoupSessionHost *
457 get_host_for_message (SoupSession *session, SoupMessage *msg)
458 {
459         SoupSessionHost *host;
460         const SoupUri *source = soup_message_get_uri (msg);
461
462         host = g_hash_table_lookup (session->priv->hosts, source);
463         if (host)
464                 return host;
465
466         host = soup_session_host_new (session, source);
467         g_hash_table_insert (session->priv->hosts, host->root_uri, host);
468
469         return host;
470 }
471
472 /* Note: get_proxy_host doesn't lock the host_lock. The caller must do
473  * it itself if there's a chance the host doesn't already exist.
474  */
475 static SoupSessionHost *
476 get_proxy_host (SoupSession *session)
477 {
478         if (session->priv->proxy_host || !session->priv->proxy_uri)
479                 return session->priv->proxy_host;
480
481         session->priv->proxy_host =
482                 soup_session_host_new (session, session->priv->proxy_uri);
483         return session->priv->proxy_host;
484 }
485
486 static void
487 free_realm (gpointer path, gpointer scheme_realm, gpointer data)
488 {
489         g_free (path);
490         g_free (scheme_realm);
491 }
492
493 static void
494 free_auth (gpointer scheme_realm, gpointer auth, gpointer data)
495 {
496         g_free (scheme_realm);
497         g_object_unref (auth);
498 }
499
500 static void
501 free_host (SoupSessionHost *host, SoupSession *session)
502 {
503         while (host->connections) {
504                 SoupConnection *conn = host->connections->data;
505
506                 host->connections = g_slist_remove (host->connections, conn);
507                 soup_connection_disconnect (conn);
508         }
509
510         if (host->auth_realms) {
511                 g_hash_table_foreach (host->auth_realms, free_realm, NULL);
512                 g_hash_table_destroy (host->auth_realms);
513         }
514         if (host->auths) {
515                 g_hash_table_foreach (host->auths, free_auth, NULL);
516                 g_hash_table_destroy (host->auths);
517         }
518
519         soup_uri_free (host->root_uri);
520         g_free (host);
521 }       
522
523 /* Authentication */
524
525 static SoupAuth *
526 lookup_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
527 {
528         SoupSessionHost *host;
529         char *path, *dir;
530         const char *realm, *const_path;
531
532         if (proxy) {
533                 host = get_proxy_host (session);
534                 const_path = "/";
535         } else {
536                 host = get_host_for_message (session, msg);
537                 const_path = soup_message_get_uri (msg)->path;
538
539                 if (!const_path)
540                         const_path = "/";
541         }
542         g_return_val_if_fail (host != NULL, NULL);
543
544         if (!host->auth_realms)
545                 return NULL;
546
547         path = g_strdup (const_path);
548         dir = path;
549         do {
550                 realm = g_hash_table_lookup (host->auth_realms, path);
551                 if (realm)
552                         break;
553
554                 dir = strrchr (path, '/');
555                 if (dir)
556                         *dir = '\0';
557         } while (dir);
558
559         g_free (path);
560         if (realm)
561                 return g_hash_table_lookup (host->auths, realm);
562         else
563                 return NULL;
564 }
565
566 static void
567 invalidate_auth (SoupSessionHost *host, SoupAuth *auth)
568 {
569         char *realm;
570         gpointer key, value;
571
572         realm = g_strdup_printf ("%s:%s",
573                                  soup_auth_get_scheme_name (auth),
574                                  soup_auth_get_realm (auth));
575
576         if (g_hash_table_lookup_extended (host->auths, realm, &key, &value) &&
577             auth == (SoupAuth *)value) {
578                 g_hash_table_remove (host->auths, realm);
579                 g_free (key);
580                 g_object_unref (auth);
581         }
582         g_free (realm);
583 }
584
585 static gboolean
586 authenticate_auth (SoupSession *session, SoupAuth *auth,
587                    SoupMessage *msg, gboolean prior_auth_failed,
588                    gboolean proxy)
589 {
590         const SoupUri *uri;
591         char *username = NULL, *password = NULL;
592
593         if (proxy)
594                 uri = session->priv->proxy_uri;
595         else
596                 uri = soup_message_get_uri (msg);
597
598         if (uri->passwd && !prior_auth_failed) {
599                 soup_auth_authenticate (auth, uri->user, uri->passwd);
600                 return TRUE;
601         }
602
603         g_signal_emit (session, signals[prior_auth_failed ? REAUTHENTICATE : AUTHENTICATE], 0,
604                        msg, soup_auth_get_scheme_name (auth),
605                        soup_auth_get_realm (auth),
606                        &username, &password);
607         if (username || password)
608                 soup_auth_authenticate (auth, username, password);
609         if (username)
610                 g_free (username);
611         if (password) {
612                 memset (password, 0, strlen (password));
613                 g_free (password);
614         }
615
616         return soup_auth_is_authenticated (auth);
617 }
618
619 static gboolean
620 update_auth_internal (SoupSession *session, SoupMessage *msg,
621                       const GSList *headers, gboolean proxy,
622                       gboolean got_unauthorized)
623 {
624         SoupSessionHost *host;
625         SoupAuth *new_auth, *prior_auth, *old_auth;
626         gpointer old_path, old_realm;
627         const SoupUri *msg_uri;
628         const char *path;
629         char *realm;
630         GSList *pspace, *p;
631         gboolean prior_auth_failed = FALSE;
632
633         if (proxy)
634                 host = get_proxy_host (session);
635         else
636                 host = get_host_for_message (session, msg);
637
638         g_return_val_if_fail (host != NULL, FALSE);
639
640         /* Try to construct a new auth from the headers; if we can't,
641          * there's no way we'll be able to authenticate.
642          */
643         msg_uri = soup_message_get_uri (msg);
644         new_auth = soup_auth_new_from_header_list (headers);
645         if (!new_auth)
646                 return FALSE;
647
648         /* See if this auth is the same auth we used last time */
649         prior_auth = lookup_auth (session, msg, proxy);
650         if (prior_auth &&
651             G_OBJECT_TYPE (prior_auth) == G_OBJECT_TYPE (new_auth) &&
652             !strcmp (soup_auth_get_realm (prior_auth),
653                      soup_auth_get_realm (new_auth))) {
654                 if (!got_unauthorized) {
655                         /* The user is just trying to preauthenticate
656                          * using information we already have, so
657                          * there's nothing more that needs to be done.
658                          */
659                         g_object_unref (new_auth);
660                         return TRUE;
661                 }
662
663                 /* The server didn't like the username/password we
664                  * provided before. Invalidate it and note this fact.
665                  */
666                 invalidate_auth (host, prior_auth);
667                 prior_auth_failed = TRUE;
668         }
669
670         if (!host->auth_realms) {
671                 host->auth_realms = g_hash_table_new (g_str_hash, g_str_equal);
672                 host->auths = g_hash_table_new (g_str_hash, g_str_equal);
673         }
674
675         /* Record where this auth realm is used */
676         realm = g_strdup_printf ("%s:%s",
677                                  soup_auth_get_scheme_name (new_auth),
678                                  soup_auth_get_realm (new_auth));
679
680         /* 
681          * RFC 2617 is somewhat unclear about the scope of protection
682          * spaces with regard to proxies.  The only mention of it is
683          * as an aside in section 3.2.1, where it is defining the fields
684          * of a Digest challenge and says that the protection space is
685          * always the entire proxy.  Is this the case for all authentication
686          * schemes or just Digest?  Who knows, but we're assuming all.
687          */
688         if (proxy)
689                 pspace = g_slist_prepend (NULL, g_strdup (""));
690         else
691                 pspace = soup_auth_get_protection_space (new_auth, msg_uri);
692
693         for (p = pspace; p; p = p->next) {
694                 path = p->data;
695                 if (g_hash_table_lookup_extended (host->auth_realms, path,
696                                                   &old_path, &old_realm)) {
697                         g_hash_table_remove (host->auth_realms, old_path);
698                         g_free (old_path);
699                         g_free (old_realm);
700                 }
701
702                 g_hash_table_insert (host->auth_realms,
703                                      g_strdup (path), g_strdup (realm));
704         }
705         soup_auth_free_protection_space (new_auth, pspace);
706
707         /* Now, make sure the auth is recorded. (If there's a
708          * pre-existing auth, we keep that rather than the new one,
709          * since the old one might already be authenticated.)
710          */
711         old_auth = g_hash_table_lookup (host->auths, realm);
712         if (old_auth) {
713                 g_free (realm);
714                 g_object_unref (new_auth);
715                 new_auth = old_auth;
716         } else 
717                 g_hash_table_insert (host->auths, realm, new_auth);
718
719         /* If we need to authenticate, try to do it. */
720         if (!soup_auth_is_authenticated (new_auth)) {
721                 return authenticate_auth (session, new_auth,
722                                           msg, prior_auth_failed, proxy);
723         }
724
725         /* Otherwise we're good. */
726         return TRUE;
727 }
728
729 static void
730 connection_authenticate (SoupConnection *conn, SoupMessage *msg,
731                          const char *auth_type, const char *auth_realm,
732                          char **username, char **password, gpointer session)
733 {
734         g_signal_emit (session, signals[AUTHENTICATE], 0,
735                        msg, auth_type, auth_realm, username, password);
736 }
737
738 static void
739 connection_reauthenticate (SoupConnection *conn, SoupMessage *msg,
740                            const char *auth_type, const char *auth_realm,
741                            char **username, char **password,
742                            gpointer user_data)
743 {
744         g_signal_emit (conn, signals[REAUTHENTICATE], 0,
745                        msg, auth_type, auth_realm, username, password);
746 }
747
748
749 static void
750 authorize_handler (SoupMessage *msg, gpointer user_data)
751 {
752         SoupSession *session = user_data;
753         const GSList *headers;
754         gboolean proxy;
755
756         if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
757                 headers = soup_message_get_header_list (msg->response_headers,
758                                                         "Proxy-Authenticate");
759                 proxy = TRUE;
760         } else {
761                 headers = soup_message_get_header_list (msg->response_headers,
762                                                         "WWW-Authenticate");
763                 proxy = FALSE;
764         }
765         if (!headers)
766                 return;
767
768         if (update_auth_internal (session, msg, headers, proxy, TRUE))
769                 soup_session_requeue_message (session, msg);
770 }
771
772 static void
773 redirect_handler (SoupMessage *msg, gpointer user_data)
774 {
775         SoupSession *session = user_data;
776         const char *new_loc;
777         SoupUri *new_uri;
778
779         new_loc = soup_message_get_header (msg->response_headers, "Location");
780         if (!new_loc)
781                 return;
782         new_uri = soup_uri_new (new_loc);
783         if (!new_uri) {
784                 soup_message_set_status_full (msg,
785                                               SOUP_STATUS_MALFORMED,
786                                               "Invalid Redirect URL");
787                 return;
788         }
789
790         soup_message_set_uri (msg, new_uri);
791         soup_uri_free (new_uri);
792
793         soup_session_requeue_message (session, msg);
794 }
795
796 static void
797 add_auth (SoupSession *session, SoupMessage *msg, gboolean proxy)
798 {
799         const char *header = proxy ? "Proxy-Authorization" : "Authorization";
800         SoupAuth *auth;
801         char *token;
802
803         auth = lookup_auth (session, msg, proxy);
804         if (!auth)
805                 return;
806         if (!soup_auth_is_authenticated (auth) &&
807             !authenticate_auth (session, auth, msg, FALSE, proxy))
808                 return;
809
810         token = soup_auth_get_authorization (auth, msg);
811         if (token) {
812                 soup_message_remove_header (msg->request_headers, header);
813                 soup_message_add_header (msg->request_headers, header, token);
814                 g_free (token);
815         }
816 }
817
818 static void
819 setup_message (SoupMessageFilter *filter, SoupMessage *msg)
820 {
821         SoupSession *session = SOUP_SESSION (filter);
822         GSList *f;
823
824         for (f = session->priv->filters; f; f = f->next) {
825                 filter = f->data;
826                 soup_message_filter_setup_message (filter, msg);
827         }
828
829         add_auth (session, msg, FALSE);
830         soup_message_add_status_code_handler (
831                 msg, SOUP_STATUS_UNAUTHORIZED,
832                 SOUP_HANDLER_POST_BODY,
833                 authorize_handler, session);
834
835         if (session->priv->proxy_uri) {
836                 add_auth (session, msg, TRUE);
837                 soup_message_add_status_code_handler  (
838                         msg, SOUP_STATUS_PROXY_UNAUTHORIZED,
839                         SOUP_HANDLER_POST_BODY,
840                         authorize_handler, session);
841         }
842 }
843
844 static void
845 find_oldest_connection (gpointer key, gpointer host, gpointer data)
846 {
847         SoupConnection *conn = key, **oldest = data;
848
849         /* Don't prune a connection that is currently in use, or
850          * hasn't been used yet.
851          */
852         if (soup_connection_is_in_use (conn) ||
853             soup_connection_last_used (conn) == 0)
854                 return;
855
856         if (!*oldest || (soup_connection_last_used (conn) <
857                          soup_connection_last_used (*oldest)))
858                 *oldest = conn;
859 }
860
861 /**
862  * soup_session_try_prune_connection:
863  * @session: a #SoupSession
864  *
865  * Finds the least-recently-used idle connection in @session and closes
866  * it.
867  *
868  * Return value: %TRUE if a connection was closed, %FALSE if there are
869  * no idle connections.
870  **/
871 gboolean
872 soup_session_try_prune_connection (SoupSession *session)
873 {
874         SoupConnection *oldest = NULL;
875
876         g_mutex_lock (session->priv->host_lock);
877         g_hash_table_foreach (session->priv->conns, find_oldest_connection,
878                               &oldest);
879         if (oldest) {
880                 /* Ref the connection before unlocking the mutex in
881                  * case someone else tries to prune it too.
882                  */
883                 g_object_ref (oldest);
884                 g_mutex_unlock (session->priv->host_lock);
885                 soup_connection_disconnect (oldest);
886                 g_object_unref (oldest);
887                 return TRUE;
888         } else {
889                 g_mutex_unlock (session->priv->host_lock);
890                 return FALSE;
891         }
892 }
893
894 static void
895 connection_disconnected (SoupConnection *conn, gpointer user_data)
896 {
897         SoupSession *session = user_data;
898         SoupSessionHost *host;
899
900         g_mutex_lock (session->priv->host_lock);
901
902         host = g_hash_table_lookup (session->priv->conns, conn);
903         if (host) {
904                 g_hash_table_remove (session->priv->conns, conn);
905                 host->connections = g_slist_remove (host->connections, conn);
906                 host->num_conns--;
907         }
908
909         g_signal_handlers_disconnect_by_func (conn, connection_disconnected, session);
910         session->priv->num_conns--;
911
912         g_mutex_unlock (session->priv->host_lock);
913         g_object_unref (conn);
914 }
915
916 static void
917 connect_result (SoupConnection *conn, guint status, gpointer user_data)
918 {
919         SoupSession *session = user_data;
920         SoupSessionHost *host;
921         SoupMessageQueueIter iter;
922         SoupMessage *msg;
923
924         g_mutex_lock (session->priv->host_lock);
925
926         host = g_hash_table_lookup (session->priv->conns, conn);
927         if (!host) {
928                 g_mutex_unlock (session->priv->host_lock);
929                 return;
930         }
931
932         if (status == SOUP_STATUS_OK) {
933                 host->connections = g_slist_prepend (host->connections, conn);
934                 g_mutex_unlock (session->priv->host_lock);
935                 return;
936         }
937
938         /* The connection failed. */
939         g_mutex_unlock (session->priv->host_lock);
940         connection_disconnected (conn, session);
941
942         if (host->connections) {
943                 /* Something went wrong this time, but we have at
944                  * least one open connection to this host. So just
945                  * leave the message in the queue so it can use that
946                  * connection once it's free.
947                  */
948                 return;
949         }
950
951         /* There are two possibilities: either status is
952          * SOUP_STATUS_TRY_AGAIN, in which case the session implementation
953          * will create a new connection (and all we need to do here
954          * is downgrade the message from CONNECTING to QUEUED); or
955          * status is something else, probably CANT_CONNECT or
956          * CANT_RESOLVE or the like, in which case we need to cancel
957          * any messages waiting for this host, since they're out
958          * of luck.
959          */
960         for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
961                 if (get_host_for_message (session, msg) == host) {
962                         if (status == SOUP_STATUS_TRY_AGAIN) {
963                                 if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING)
964                                         msg->status = SOUP_MESSAGE_STATUS_QUEUED;
965                         } else {
966                                 soup_message_set_status (msg, status);
967                                 soup_session_cancel_message (session, msg);
968                         }
969                 }
970         }
971 }
972
973 /**
974  * soup_session_get_connection:
975  * @session: a #SoupSession
976  * @msg: a #SoupMessage
977  * @try_pruning: on return, whether or not to try pruning a connection
978  * @is_new: on return, %TRUE if the returned connection is new and not
979  * yet connected
980  * 
981  * Tries to find or create a connection for @msg. If there is an idle
982  * connection to the relevant host available, then it will be returned
983  * (with *@is_new set to %FALSE). Otherwise, if it is possible to
984  * create a new connection, one will be created and returned, with
985  * *@is_new set to %TRUE.
986  *
987  * If no connection can be made, it will return %NULL. If @session has
988  * the maximum number of open connections open, but does not have the
989  * maximum number of per-host connections open to the relevant host, then
990  * *@try_pruning will be set to %TRUE. In this case, the caller can
991  * call soup_session_try_prune_connection() to close an idle connection,
992  * and then try soup_session_get_connection() again. (If calling
993  * soup_session_try_prune_connection() wouldn't help, then *@try_pruning
994  * is left untouched; it is NOT set to %FALSE.)
995  *
996  * Return value: a #SoupConnection, or %NULL
997  **/
998 SoupConnection *
999 soup_session_get_connection (SoupSession *session, SoupMessage *msg,
1000                              gboolean *try_pruning, gboolean *is_new)
1001 {
1002         SoupConnection *conn;
1003         SoupSessionHost *host;
1004         GSList *conns;
1005
1006         g_mutex_lock (session->priv->host_lock);
1007
1008         host = get_host_for_message (session, msg);
1009         for (conns = host->connections; conns; conns = conns->next) {
1010                 if (!soup_connection_is_in_use (conns->data)) {
1011                         soup_connection_reserve (conns->data);
1012                         g_mutex_unlock (session->priv->host_lock);
1013                         *is_new = FALSE;
1014                         return conns->data;
1015                 }
1016         }
1017
1018         if (msg->status == SOUP_MESSAGE_STATUS_CONNECTING) {
1019                 /* We already started a connection for this
1020                  * message, so don't start another one.
1021                  */
1022                 g_mutex_unlock (session->priv->host_lock);
1023                 return NULL;
1024         }
1025
1026         if (host->num_conns >= session->priv->max_conns_per_host) {
1027                 g_mutex_unlock (session->priv->host_lock);
1028                 return NULL;
1029         }
1030
1031         if (session->priv->num_conns >= session->priv->max_conns) {
1032                 *try_pruning = TRUE;
1033                 g_mutex_unlock (session->priv->host_lock);
1034                 return NULL;
1035         }
1036
1037         /* Make sure session->priv->proxy_host gets set now while
1038          * we have the host_lock.
1039          */
1040         if (session->priv->proxy_uri)
1041                 get_proxy_host (session);
1042
1043         conn = g_object_new (
1044                 (session->priv->use_ntlm ?
1045                  SOUP_TYPE_CONNECTION_NTLM : SOUP_TYPE_CONNECTION),
1046                 SOUP_CONNECTION_ORIGIN_URI, host->root_uri,
1047                 SOUP_CONNECTION_PROXY_URI, session->priv->proxy_uri,
1048                 SOUP_CONNECTION_SSL_CREDENTIALS, session->priv->ssl_creds,
1049                 SOUP_CONNECTION_MESSAGE_FILTER, session,
1050                 NULL);
1051         g_signal_connect (conn, "connect_result",
1052                           G_CALLBACK (connect_result),
1053                           session);
1054         g_signal_connect (conn, "disconnected",
1055                           G_CALLBACK (connection_disconnected),
1056                           session);
1057         g_signal_connect (conn, "authenticate",
1058                           G_CALLBACK (connection_authenticate),
1059                           session);
1060         g_signal_connect (conn, "reauthenticate",
1061                           G_CALLBACK (connection_reauthenticate),
1062                           session);
1063
1064         g_hash_table_insert (session->priv->conns, conn, host);
1065
1066         /* We increment the connection counts so it counts against the
1067          * totals, but we don't add it to the host's connection list
1068          * yet, since it's not ready for use.
1069          */
1070         session->priv->num_conns++;
1071         host->num_conns++;
1072
1073         /* Mark the request as connecting, so we don't try to open
1074          * another new connection for it while waiting for this one.
1075          */
1076         msg->status = SOUP_MESSAGE_STATUS_CONNECTING;
1077
1078         g_mutex_unlock (session->priv->host_lock);
1079         *is_new = TRUE;
1080         return conn;
1081 }
1082
1083 static void
1084 message_finished (SoupMessage *msg, gpointer user_data)
1085 {
1086         SoupSession *session = user_data;
1087
1088         if (!SOUP_MESSAGE_IS_STARTING (msg)) {
1089                 soup_message_queue_remove_message (session->queue, msg);
1090                 g_signal_handlers_disconnect_by_func (msg, message_finished, session);
1091         }
1092 }
1093
1094 static void
1095 queue_message (SoupSession *session, SoupMessage *msg,
1096                SoupMessageCallbackFn callback, gpointer user_data)
1097 {
1098         g_signal_connect_after (msg, "finished",
1099                                 G_CALLBACK (message_finished), session);
1100
1101         if (!(soup_message_get_flags (msg) & SOUP_MESSAGE_NO_REDIRECT)) {
1102                 soup_message_add_status_class_handler (
1103                         msg, SOUP_STATUS_CLASS_REDIRECT,
1104                         SOUP_HANDLER_POST_BODY,
1105                         redirect_handler, session);
1106         }
1107
1108         msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1109         soup_message_queue_append (session->queue, msg);
1110 }
1111
1112 /**
1113  * soup_session_queue_message:
1114  * @session: a #SoupSession
1115  * @msg: the message to queue
1116  * @callback: a #SoupMessageCallbackFn which will be called after the
1117  * message completes or when an unrecoverable error occurs.
1118  * @user_data: a pointer passed to @callback.
1119  * 
1120  * Queues the message @msg for sending. All messages are processed
1121  * while the glib main loop runs. If @msg has been processed before,
1122  * any resources related to the time it was last sent are freed.
1123  *
1124  * Upon message completion, the callback specified in @callback will
1125  * be invoked. If after returning from this callback the message has
1126  * not been requeued, @msg will be unreffed.
1127  */
1128 void
1129 soup_session_queue_message (SoupSession *session, SoupMessage *msg,
1130                             SoupMessageCallbackFn callback, gpointer user_data)
1131 {
1132         g_return_if_fail (SOUP_IS_SESSION (session));
1133         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1134
1135         SOUP_SESSION_GET_CLASS (session)->queue_message (session, msg,
1136                                                          callback, user_data);
1137 }
1138
1139 static void
1140 requeue_message (SoupSession *session, SoupMessage *msg)
1141 {
1142         msg->status = SOUP_MESSAGE_STATUS_QUEUED;
1143 }
1144
1145 /**
1146  * soup_session_requeue_message:
1147  * @session: a #SoupSession
1148  * @msg: the message to requeue
1149  *
1150  * This causes @msg to be placed back on the queue to be attempted
1151  * again.
1152  **/
1153 void
1154 soup_session_requeue_message (SoupSession *session, SoupMessage *msg)
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)->requeue_message (session, msg);
1160 }
1161
1162
1163 /**
1164  * soup_session_send_message:
1165  * @session: a #SoupSession
1166  * @msg: the message to send
1167  * 
1168  * Synchronously send @msg. This call will not return until the
1169  * transfer is finished successfully or there is an unrecoverable
1170  * error.
1171  *
1172  * @msg is not freed upon return.
1173  *
1174  * Return value: the HTTP status code of the response
1175  */
1176 guint
1177 soup_session_send_message (SoupSession *session, SoupMessage *msg)
1178 {
1179         g_return_val_if_fail (SOUP_IS_SESSION (session), SOUP_STATUS_MALFORMED);
1180         g_return_val_if_fail (SOUP_IS_MESSAGE (msg), SOUP_STATUS_MALFORMED);
1181
1182         return SOUP_SESSION_GET_CLASS (session)->send_message (session, msg);
1183 }
1184
1185
1186 static void
1187 cancel_message (SoupSession *session, SoupMessage *msg)
1188 {
1189         soup_message_queue_remove_message (session->queue, msg);
1190         soup_message_finished (msg);
1191 }
1192
1193 /**
1194  * soup_session_cancel_message:
1195  * @session: a #SoupSession
1196  * @msg: the message to cancel
1197  *
1198  * Causes @session to immediately finish processing @msg. You should
1199  * set a status code on @msg with soup_message_set_status() before
1200  * calling this function.
1201  **/
1202 void
1203 soup_session_cancel_message (SoupSession *session, SoupMessage *msg)
1204 {
1205         g_return_if_fail (SOUP_IS_SESSION (session));
1206         g_return_if_fail (SOUP_IS_MESSAGE (msg));
1207
1208         SOUP_SESSION_GET_CLASS (session)->cancel_message (session, msg);
1209 }
1210
1211 /**
1212  * soup_session_abort:
1213  * @session: the session
1214  *
1215  * Cancels all pending requests in @session.
1216  **/
1217 void
1218 soup_session_abort (SoupSession *session)
1219 {
1220         SoupMessageQueueIter iter;
1221         SoupMessage *msg;
1222
1223         g_return_if_fail (SOUP_IS_SESSION (session));
1224
1225         for (msg = soup_message_queue_first (session->queue, &iter); msg; msg = soup_message_queue_next (session->queue, &iter)) {
1226                 soup_message_set_status (msg, SOUP_STATUS_CANCELLED);
1227                 soup_session_cancel_message (session, msg);
1228         }
1229 }