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