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