summaryrefslogtreecommitdiff
path: root/libsoup/soup-context.c
blob: 28d2c5f34d86d7d0dc63068dd75c03583f255c0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * soup-context.c: Asyncronous Callback-based SOAP Request Queue.
 *
 * Authors:
 *      Alex Graveley (alex@helixcode.com)
 *
 * Copyright (C) 2000, Helix Code, Inc.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <string.h>
#include <stdlib.h>
#include <glib.h>

#include <fcntl.h>
#include <sys/types.h>

#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif

#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif

#include "soup-auth.h"
#include "soup-context.h"
#include "soup-private.h"
#include "soup-misc.h"
#include "soup-socket.h"
#include "soup-ssl.h"

GHashTable *soup_hosts;  /* KEY: hostname, VALUE: SoupHost */

static gint connection_count = 0;

static guint most_recently_used_id = 0;

/**
 * soup_context_get:
 * @uri: the stringified URI.
 *
 * Returns a pointer to the %SoupContext representing @uri. If a context
 * already exists for the URI, it is returned with an added reference.
 * Otherwise, a new context is created with a reference count of one.
 *
 * Return value: a %SoupContext representing @uri.
 */
SoupContext *
soup_context_get (const gchar *uri)
{
	SoupUri *suri;
	SoupContext *con;

	g_return_val_if_fail (uri != NULL, NULL);

	suri = soup_uri_new (uri);
	if (!suri) return NULL;

	con = soup_context_from_uri (suri);
	soup_uri_free (suri);

	return con;
}

/**
 * soup_context_uri_hash:
 * @key: a %SoupUri
 *
 * Return value: Hash value of the user, authmech, passwd, and path fields in
 * @key.
 **/
static guint
soup_context_uri_hash (gconstpointer key)
{
	const SoupUri *uri = key;
	guint ret = 0;

	ret += uri->protocol;
	ret += g_str_hash (uri->path ? uri->path : "");
	ret += g_str_hash (uri->querystring ? uri->querystring : "");
	ret += g_str_hash (uri->user ? uri->user : "");
	ret += g_str_hash (uri->passwd ? uri->passwd : "");

	return ret;
}

/**
 * soup_context_uri_equal:
 * @v1: a %SoupUri
 * @v2: a %SoupUri
 *
 * Return value: TRUE if @v1 and @v2 match in user, authmech, passwd, and
 * path. Otherwise, FALSE.
 **/
static gboolean
soup_context_uri_equal (gconstpointer v1, gconstpointer v2)
{
	const SoupUri *one = v1;
	const SoupUri *two = v2;

	if (one->protocol == two->protocol &&
	    !strcmp (one->path ? one->path : "",
		     two->path ? two->path : "") &&
	    !strcmp (one->querystring ? one->querystring : "",
		     two->querystring ? two->querystring : "") &&
	    !strcmp (one->user ? one->user : "",
		     two->user ? two->user : "") &&
	    !strcmp (one->passwd ? one->passwd : "",
		     two->passwd ? two->passwd : ""))
		return TRUE;

	return FALSE;
}

/**
 * soup_context_from_uri:
 * @suri: a %SoupUri.
 *
 * Returns a pointer to the %SoupContext representing @suri. If a context
 * already exists for the URI, it is returned with an added reference.
 * Otherwise, a new context is created with a reference count of one.
 *
 * Return value: a %SoupContext representing @uri.
 */
SoupContext *
soup_context_from_uri (SoupUri *suri)
{
	SoupHost *serv = NULL;
	SoupContext *ret = NULL;

	g_return_val_if_fail (suri != NULL, NULL);
	g_return_val_if_fail (suri->protocol != 0, NULL);

	if (!soup_hosts)
		soup_hosts = g_hash_table_new (soup_str_case_hash,
					       soup_str_case_equal);
	else
		serv = g_hash_table_lookup (soup_hosts, suri->host);

	if (!serv) {
		serv = g_new0 (SoupHost, 1);
		serv->host = g_strdup (suri->host);
		g_hash_table_insert (soup_hosts, serv->host, serv);
	}

	if (!serv->contexts)
		serv->contexts = g_hash_table_new (soup_context_uri_hash,
						   soup_context_uri_equal);
	else
		ret = g_hash_table_lookup (serv->contexts, suri);

	if (!ret) {
		ret = g_new0 (SoupContext, 1);
		ret->server = serv;
		ret->uri = soup_uri_copy (suri);
		ret->refcnt = 0;

		g_hash_table_insert (serv->contexts, ret->uri, ret);
	}

	soup_context_ref (ret);

	return ret;
}

/**
 * soup_context_ref:
 * @ctx: a %SoupContext.
 *
 * Adds a reference to @ctx.
 */
void
soup_context_ref (SoupContext *ctx)
{
	g_return_if_fail (ctx != NULL);

	ctx->refcnt++;
}

static gboolean
remove_auth (gchar *path, SoupAuth *auth)
{
	g_free (path);
	soup_auth_free (auth);

	return TRUE;
}

/**
 * soup_context_unref:
 * @ctx: a %SoupContext.
 *
 * Decrement the reference count on @ctx. If the reference count reaches
 * zero, the %SoupContext is freed. If this is the last context for a
 * given server address, any open connections are closed.
 */
void
soup_context_unref (SoupContext *ctx)
{
	g_return_if_fail (ctx != NULL);

	--ctx->refcnt;

	if (ctx->refcnt == 0) {
		SoupHost *serv = ctx->server;

		g_hash_table_remove (serv->contexts, ctx->uri);

		if (g_hash_table_size (serv->contexts) == 0) {
			/*
			 * Remove this host from the active hosts hash
			 */
			g_hash_table_remove (soup_hosts, serv->host);

			/* 
			 * Free all cached SoupAuths
			 */
			if (serv->valid_auths) {
				g_hash_table_foreach_remove (
					serv->valid_auths,
					(GHRFunc) remove_auth,
					NULL);
				g_hash_table_destroy (serv->valid_auths);
			}

			g_hash_table_destroy (serv->contexts);
			g_free (serv->host);
			g_free (serv);
		}

		soup_uri_free (ctx->uri);
		g_free (ctx);
	}
}

static void
connection_free (SoupConnection *conn)
{
	g_return_if_fail (conn != NULL);

	conn->server->connections =
		g_slist_remove (conn->server->connections, conn);

	soup_context_unref (conn->context);
	soup_socket_unref (conn->socket);
	g_source_remove (conn->death_tag);
	g_free (conn);

	connection_count--;
}

static gboolean 
connection_death (GIOChannel*     iochannel,
		  GIOCondition    condition,
		  SoupConnection *conn)
{
	if (!conn->in_use) {
		connection_free (conn);
		return FALSE;
	}

	return TRUE;
}

struct SoupConnectData {
	SoupContext           *ctx;
	SoupConnectCallbackFn  cb;
	gpointer               user_data;

	guint                  timeout_tag;
	gpointer               connect_tag;
};

static void
prune_connection_foreach (gchar               *hostname,
			  SoupHost            *serv,
			  SoupConnection     **last)
{
	GSList *conns = serv->connections;

	while (conns) {
		SoupConnection *conn = conns->data;

		if (!conn->in_use) {
			if (*last == NULL ||
			    (*last)->last_used_id > conn->last_used_id)
				*last = conn;
		}

		conns = conns->next;
	}
}

static gboolean
prune_least_used_connection (void)
{
	SoupConnection *last = NULL;

	g_hash_table_foreach (soup_hosts, 
			      (GHFunc) prune_connection_foreach, 
			      &last);
	if (last) {
		connection_free (last);
		return TRUE;
	}

	return FALSE;
}

static gboolean retry_connect_timeout_cb (struct SoupConnectData *data);

static void
soup_context_connect_cb (SoupSocket              *socket,
			 SoupSocketConnectStatus  status,
			 gpointer                 user_data)
{
	struct SoupConnectData *data = user_data;
	SoupContext            *ctx = data->ctx;
	SoupConnection         *new_conn;
	GIOChannel             *chan;

	switch (status) {
	case SOUP_SOCKET_CONNECT_ERROR_NONE:
		new_conn = g_new0 (SoupConnection, 1);
		new_conn->server = ctx->server;
		new_conn->socket = socket;
		new_conn->port = ctx->uri->port;
		new_conn->keep_alive = TRUE;
		new_conn->in_use = TRUE;
		new_conn->last_used_id = 0;

		new_conn->context = ctx;
		soup_context_ref (ctx);

		chan = soup_connection_get_iochannel (new_conn);
		new_conn->death_tag = 
			g_io_add_watch (chan,
					G_IO_ERR | G_IO_HUP | G_IO_NVAL,
					(GIOFunc) connection_death,
					new_conn);
		g_io_channel_unref (chan);

		ctx->server->connections =
			g_slist_prepend (ctx->server->connections, new_conn);

		(*data->cb) (ctx, 
			     SOUP_CONNECT_ERROR_NONE, 
			     new_conn, 
			     data->user_data);
		break;
	case SOUP_SOCKET_CONNECT_ERROR_ADDR_RESOLVE:
		connection_count--;

		(*data->cb) (ctx, 
			     SOUP_CONNECT_ERROR_ADDR_RESOLVE, 
			     NULL, 
			     data->user_data);
		break;
	case SOUP_SOCKET_CONNECT_ERROR_NETWORK:
		connection_count--;

		/*
		 * Check if another connection exists to this server
		 * before reporting error. 
		 */
		if (ctx->server->connections) {
			data->timeout_tag =
				g_timeout_add (
					150,
					(GSourceFunc) retry_connect_timeout_cb,
					data);
			return;
		}

		(*data->cb) (ctx, 
			     SOUP_CONNECT_ERROR_NETWORK, 
			     NULL, 
			     data->user_data);
		break;
	}

	soup_context_unref (ctx);
	g_free (data);
}

static gboolean
try_existing_connections (SoupContext           *ctx,
			  SoupConnectCallbackFn  cb,
			  gpointer               user_data)
{
	GSList *conns = ctx->server->connections;
	
	while (conns) {
		SoupConnection *conn = conns->data;

		if (conn->in_use == FALSE &&
		    conn->keep_alive == TRUE &&
		    conn->port == (guint) ctx->uri->port) {
			/* Set connection to in use */
			conn->in_use = TRUE;

			/* Reset connection context */
			soup_context_ref (ctx);
			soup_context_unref (conn->context);
			conn->context = ctx;

			/* Issue success callback */
			(*cb) (ctx, SOUP_CONNECT_ERROR_NONE, conn, user_data);
			return TRUE;
		}

		conns = conns->next;
	}

	return FALSE;
}

static gboolean
try_create_connection (struct SoupConnectData **dataptr)
{
	struct SoupConnectData *data = *dataptr;
	gint conn_limit = soup_get_connection_limit ();
	gpointer connect_tag;

	/* 
	 * Check if we are allowed to create a new connection, otherwise wait
	 * for next timeout.  
	 */
	if (conn_limit &&
	    connection_count >= conn_limit &&
	    !prune_least_used_connection ()) {
		data->connect_tag = 0;
		return FALSE;
	}

	connection_count++;

	data->timeout_tag = 0;
	connect_tag = soup_socket_connect (data->ctx->uri->host,
					   data->ctx->uri->port,
					   soup_context_connect_cb,
					   data);
	/* 
	 * NOTE: soup_socket_connect can fail immediately and call our
	 * callback which will delete the state.  
	 */
	if (connect_tag)
		data->connect_tag = connect_tag;
	else
		*dataptr = NULL;

	return TRUE;
}

static gboolean
retry_connect_timeout_cb (struct SoupConnectData *data)
{
	if (try_existing_connections (data->ctx, 
				      data->cb, 
				      data->user_data)) {
		soup_context_unref (data->ctx);
		g_free (data);
		return FALSE;
	}

	return try_create_connection (&data) == FALSE;
}

/**
 * soup_context_get_connection:
 * @ctx: a %SoupContext.
 * @cb: a %SoupConnectCallbackFn to be called when a valid connection is
 * available.
 * @user_data: the user_data passed to @cb.
 *
 * Initiates the process of establishing a network connection to the
 * server referenced in @ctx. If an existing connection is available and
 * not in use, @cb is called immediately, and a %SoupConnectId of 0 is
 * returned. Otherwise, a new connection is established. If the current
 * connection count exceeds that set in @soup_set_connection_limit, the
 * new connection is not created until an existing connection is closed.
 *
 * Once a network connection is successfully established, or an existing
 * connection becomes available for use, @cb is called, passing the
 * %SoupConnection representing it.
 *
 * Return value: a %SoupConnectId which can be used to cancel a connection
 * attempt using %soup_context_cancel_connect.
 */
SoupConnectId
soup_context_get_connection (SoupContext           *ctx,
			     SoupConnectCallbackFn  cb,
			     gpointer               user_data)
{
	struct SoupConnectData *data;

	g_return_val_if_fail (ctx != NULL, NULL);

	/* Look for an existing unused connection */
	if (try_existing_connections (ctx, cb, user_data))
		return NULL;

	data = g_new0 (struct SoupConnectData, 1);
	data->cb = cb;
	data->user_data = user_data;

	data->ctx = ctx;
	soup_context_ref (ctx);

	if (!try_create_connection (&data))
		data->timeout_tag =
			g_timeout_add (150,
				       (GSourceFunc) retry_connect_timeout_cb,
				       data);

	return data;
}

/**
 * soup_context_cancel_connect:
 * @tag: a %SoupConnextId representing a connection in progress.
 *
 * Cancels the connection attempt represented by @tag. The
 * %SoupConnectCallbackFn passed in %soup_context_get_connection is not
 * called.
 */
void
soup_context_cancel_connect (SoupConnectId tag)
{
	struct SoupConnectData *data = tag;

	g_return_if_fail (data != NULL);

	if (data->timeout_tag)
		g_source_remove (data->timeout_tag);
	else if (data->connect_tag)
		soup_socket_connect_cancel (data->connect_tag);

	g_free (data);
}

/**
 * soup_context_get_uri:
 * @ctx: a %SoupContext.
 *
 * Returns a pointer to the %SoupUri represented by @ctx.
 *
 * Return value: the %SoupUri for @ctx.
 */
const SoupUri *
soup_context_get_uri (SoupContext *ctx)
{
	g_return_val_if_fail (ctx != NULL, NULL);
	return ctx->uri;
}

/**
 * soup_connection_release:
 * @conn: a %SoupConnection currently in use.
 *
 * Mark the connection represented by @conn as being unused. If the
 * keep-alive flag is not set on the connection, the connection is closed
 * and its resources freed, otherwise the connection is returned to the
 * unused connection pool for the server.
 */
void
soup_connection_release (SoupConnection *conn)
{
	g_return_if_fail (conn != NULL);

	if (conn->keep_alive) {
		conn->last_used_id = ++most_recently_used_id;
		conn->in_use = FALSE;		
	} else
		connection_free (conn);
}

static void
soup_connection_setup_socket (GIOChannel *channel)
{
#if TCP_NODELAY && !SOUP_WIN32
	int yes = 1, flags = 0, fd = g_io_channel_unix_get_fd (channel);

	setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));

	flags = fcntl(fd, F_GETFL, 0);
	fcntl (fd, F_SETFL, flags | O_NONBLOCK);
#endif
}

/**
 * soup_connection_get_iochannel:
 * @conn: a %SoupConnection.
 *
 * Returns a GIOChannel used for IO operations on the network connection
 * represented by @conn.
 *
 * Return value: a pointer to the GIOChannel used for IO on %conn.
 */
GIOChannel *
soup_connection_get_iochannel (SoupConnection *conn)
{
	g_return_val_if_fail (conn != NULL, NULL);

	if (!conn->channel) {
		conn->channel = soup_socket_get_iochannel (conn->socket);

		soup_connection_setup_socket (conn->channel);

		if (conn->context->uri->protocol == SOUP_PROTOCOL_HTTPS)
			conn->channel = soup_ssl_get_iochannel (conn->channel);
	} else
		g_io_channel_ref (conn->channel);

	return conn->channel;
}

/**
 * soup_connection_set_keepalive:
 * @conn: a %SoupConnection.
 * @keep_alive: boolean keep-alive value.
 *
 * Sets the keep-alive flag on the %SoupConnection pointed to by %conn.
 */
void
soup_connection_set_keep_alive (SoupConnection *conn, gboolean keep_alive)
{
	g_return_if_fail (conn != NULL);
	conn->keep_alive = keep_alive;
}

/**
 * soup_connection_set_keepalive:
 * @conn: a %SoupConnection.
 *
 * Returns the keep-alive flag for the %SoupConnection pointed to by
 * %conn. If this flag is TRUE, the connection will be returned to the pool
 * of unused connections when next %soup_connection_release is called,
 * otherwise the connection will be closed and resources freed.
 *
 * Return value: the keep-alive flag for @conn.
 */
gboolean
soup_connection_is_keep_alive (SoupConnection *conn)
{
	g_return_val_if_fail (conn != NULL, FALSE);
	return conn->keep_alive;
}

/**
 * soup_connection_get_context:
 * @conn: a %SoupConnection.
 *
 * Returns the %SoupContext from which @conn was created, with an added ref.
 *
 * Return value: the %SoupContext associated with @conn.  Unref when finished.
 */
SoupContext *
soup_connection_get_context (SoupConnection *conn)
{
	g_return_val_if_fail (conn != NULL, FALSE);
	
	soup_context_ref (conn->context);
	return conn->context;
}

/**
 * soup_connection_is_new:
 * @conn: a %SoupConnection.
 *
 * Returns TRUE if this is the first use of @conn
 * (I.E. %soup_connection_release has not yet been called on it).
 *
 * Return value: boolean representing whether this is the first time a
 * connection has been used.
 */
gboolean
soup_connection_is_new (SoupConnection *conn)
{
	g_return_val_if_fail (conn != NULL, FALSE);
	return conn->last_used_id == 0;
}