summaryrefslogtreecommitdiffstats
path: root/demos/tunala/tunala.c
blob: 445940fabd5badc9b9631ed08fb74fbc73160fab (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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#if defined(NO_BUFFER) || defined(NO_IP) || defined(NO_OPENSSL)
#error "Badness, NO_BUFFER, NO_IP or NO_OPENSSL is defined, turn them *off*"
#endif

/* Include our bits'n'pieces */
#include "tunala.h"


/********************************************/
/* Our local types that specify our "world" */
/********************************************/

/* These represent running "tunnels". Eg. if you wanted to do SSL in a
 * "message-passing" scanario, the "int" file-descriptors might be replaced by
 * thread or process IDs, and the "select" code might be replaced by message
 * handling code. Whatever. */
typedef struct _tunala_item_t {
	/* The underlying SSL state machine. This is a data-only processing unit
	 * and we communicate with it by talking to its four "buffers". */
	state_machine_t sm;
	/* The file-descriptors for the "dirty" (encrypted) side of the SSL
	 * setup. In actuality, this is typically a socket and both values are
	 * identical. */
	int dirty_read, dirty_send;
	/* The file-descriptors for the "clean" (unencrypted) side of the SSL
	 * setup. These could be stdin/stdout, a socket (both values the same),
	 * or whatever you like. */
	int clean_read, clean_send;
} tunala_item_t;

/* This structure is used as the data for running the main loop. Namely, in a
 * network format such as this, it is stuff for select() - but as pointed out,
 * when moving the real-world to somewhere else, this might be replaced by
 * something entirely different. It's basically the stuff that controls when
 * it's time to do some "work". */
typedef struct _select_sets_t {
	int max; /* As required as the first argument to select() */
	fd_set reads, sends, excepts; /* As passed to select() */
} select_sets_t;
typedef struct _tunala_selector_t {
	select_sets_t last_selected; /* Results of the last select() */
	select_sets_t next_select; /* What we'll next select on */
} tunala_selector_t;

/* This structure is *everything*. We do it to avoid the use of globals so that,
 * for example, it would be easier to shift things around between async-IO,
 * thread-based, or multi-fork()ed (or combinations thereof). */
typedef struct _tunala_world_t {
	/* The file-descriptor we "listen" on for new connections */
	int listen_fd;
	/* The array of tunnels */
	tunala_item_t *tunnels;
	/* the number of tunnels in use and allocated, respectively */
	unsigned int tunnels_used, tunnels_size;
	/* Our outside "loop" context stuff */
	tunala_selector_t selector;
	/* Our SSL_CTX, which is configured as the SSL client or server and has
	 * the various cert-settings and callbacks configured. */
	SSL_CTX *ssl_ctx;
	/* Simple flag with complex logic :-) Indicates whether we're an SSL
	 * server or an SSL client. */
	int server_mode;
} tunala_world_t;

/*****************************/
/* Internal static functions */
/*****************************/

static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
		const char *CAfile, const char *cert, const char *key);
static void selector_init(tunala_selector_t *selector);
static void selector_add_listener(tunala_selector_t *selector, int fd);
static void selector_add_tunala(tunala_selector_t *selector, tunala_item_t *t);
static int selector_select(tunala_selector_t *selector);
/* This returns -1 for error, 0 for no new connections, or 1 for success, in
 * which case *newfd is populated. */
static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd);
static int tunala_world_new_item(tunala_world_t *world, int fd,
		const unsigned char *ip, unsigned short port);
static void tunala_world_del_item(tunala_world_t *world, unsigned int idx);
static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item);

/*********************************************/
/* MAIN FUNCTION (and its utility functions) */
/*********************************************/

/* For now, hard-coded as follows;
 * (a) We're like "tunala -listen 127.0.0.1:9001 -proxy 127.0.0.1:9002"
 * (b) We max out at 50 simultaneous tunnels, listening will stop while we have
 *     that many tunnels operating and will recommence as/when tunnels close.
 * (c) We are an SSL client proxy
 * (d) We use the "openssl" ENGINE
 * (e) We use the CA cert file "cacert.pem"
 * */

static const char *def_proxyhost = "127.0.0.1:443";
static const char *def_listenhost = "127.0.0.1:8080";
static int def_max_tunnels = 50;
static const char *def_cacert = NULL;
static const char *def_cert = NULL;
static const char *def_key = NULL;
static const char *def_engine_id = NULL;
static int def_server_mode = 0;

static const char *helpstring =
	"\n'Tunala' (A tunneler with a New Zealand accent)\n"
	"Usage: tunala [options], where options are from;\n"
	"    -listen [host:]<port>  (default = 127.0.0.1:8080)\n"
	"    -proxy <host>:<port>   (default = 127.0.0.1:443)\n"
	"    -maxtunnels <num>      (default = 50)\n"
	"    -cacert <path|NULL>    (default = NULL)\n"
	"    -cert <path|NULL>      (default = NULL)\n"
	"    -key <path|NULL>       (default = whatever '-cert' is)\n"
	"    -engine <id|NULL>      (default = NULL)\n"
	"    -server <0|1>          (default = 0, ie. an SSL client)\n"
	"    -<h|help|?>            (displays this help screen)\n"
	"NB: It is recommended to specify a cert+key when operating as an\n"
	"SSL server. If you only specify '-cert', the same file must\n"
	"contain a matching private key.\n";

static int usage(const char *errstr, int isunknownarg)
{
	if(isunknownarg)
		fprintf(stderr, "Error: unknown argument '%s'\n", errstr);
	else
		fprintf(stderr, "Error: %s\n", errstr);
	fprintf(stderr, "%s\n", helpstring);
	return 1;
}

static int err_str0(const char *str0)
{
	fprintf(stderr, str0);
	fprintf(stderr, "\n");
	return 1;
}

static int err_str1(const char *str0, const char *str1)
{
	fprintf(stderr, str0, str1);
	fprintf(stderr, "\n");
	return 1;
}

static int parse_max_tunnels(const char *s, unsigned int *maxtunnels)
{
	unsigned long l;
	char *temp;
	l = strtoul(s, &temp, 10);
	if((temp == s) || (*temp != '\0') || (l < 1) || (l > 1024)) {
		fprintf(stderr, "Error, '%s' is an invalid value for "
				"maxtunnels\n", s);
		return 0;
	}
	*maxtunnels = (unsigned int)l;
	return 1;
}

static int parse_server_mode(const char *s, int *servermode)
{
	unsigned long l;
	char *temp;
	l = strtoul(s, &temp, 10);
	if((temp == s) || (*temp != '\0') || (l > 1)) {
		fprintf(stderr, "Error, '%s' is an invalid value for the "
				"server mode\n", s);
		return 0;
	}
	*servermode = (int)l;
	return 1;
}

int main(int argc, char *argv[])
{
	unsigned int loop;
	int newfd;
	tunala_world_t world;
	tunala_item_t *t_item;
	unsigned char *proxy_ip;
	unsigned short proxy_port;
	/* Overridables */
	const char *proxyhost = def_proxyhost;
	const char *listenhost = def_listenhost;
	unsigned int max_tunnels = def_max_tunnels;
	const char *cacert = def_cacert;
	const char *cert = def_cert;
	const char *key = def_key;
	const char *engine_id = def_engine_id;
	int server_mode = def_server_mode;

/* Parse command-line arguments */
next_arg:
	argc--; argv++;
	if(argc > 0) {
		if(strcmp(*argv, "-listen") == 0) {
			if(argc < 2)
				return usage("-listen requires an argument", 0);
			argc--; argv++;
			listenhost = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-proxy") == 0) {
			if(argc < 2)
				return usage("-proxy requires an argument", 0);
			argc--; argv++;
			proxyhost = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-maxtunnels") == 0) {
			if(argc < 2)
				return usage("-maxtunnels requires an argument", 0);
			argc--; argv++;
			if(!parse_max_tunnels(*argv, &max_tunnels))
				return 1;
			goto next_arg;
		} else if(strcmp(*argv, "-cacert") == 0) {
			if(argc < 2)
				return usage("-cacert requires an argument", 0);
			argc--; argv++;
			if(strcmp(*argv, "NULL") == 0)
				cacert = NULL;
			else
				cacert = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-cert") == 0) {
			if(argc < 2)
				return usage("-cert requires an argument", 0);
			argc--; argv++;
			if(strcmp(*argv, "NULL") == 0)
				cert = NULL;
			else
				cert = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-key") == 0) {
			if(argc < 2)
				return usage("-key requires an argument", 0);
			argc--; argv++;
			if(strcmp(*argv, "NULL") == 0)
				key = NULL;
			else
				key = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-engine") == 0) {
			if(argc < 2)
				return usage("-engine requires an argument", 0);
			argc--; argv++;
			engine_id = *argv;
			goto next_arg;
		} else if(strcmp(*argv, "-server") == 0) {
			if(argc < 2)
				return usage("-server requires an argument", 0);
			argc--; argv++;
			if(!parse_server_mode(*argv, &server_mode))
				return 1;
			goto next_arg;
		} else if((strcmp(*argv, "-h") == 0) ||
				(strcmp(*argv, "-help") == 0) ||
				(strcmp(*argv, "-?") == 0)) {
			fprintf(stderr, "%s\n", helpstring);
			return 0;
		} else
			return usage(*argv, 1);
	}

	/* Initialise network stuff */
	if(!ip_initialise())
		return err_str0("ip_initialise failed");
	err_str0("ip_initialise succeeded");
	/* Create the SSL_CTX */
	if((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id,
			cacert, cert, key)) == NULL)
		return err_str1("initialise_ssl_ctx(engine_id=%s) failed",
			(engine_id == NULL) ? "NULL" : engine_id);
	err_str1("initialise_ssl_ctx(engine_id=%s) succeeded",
			(engine_id == NULL) ? "NULL" : engine_id);
	/* Create the listener */
	if((world.listen_fd = ip_create_listener(listenhost)) == -1)
		return err_str1("ip_create_listener(%s) failed", listenhost);
	err_str1("ip_create_listener(%s) succeeded", listenhost);
	if(!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0))
		return err_str1("ip_parse_address(%s) failed", proxyhost);
	err_str1("ip_parse_address(%s) succeeded", proxyhost);
	fprintf(stderr, "Info - proxying to %d.%d.%d.%d:%d\n",
			(int)proxy_ip[0], (int)proxy_ip[1],
			(int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port);
	fprintf(stderr, "Info - set maxtunnels to %d\n", (int)max_tunnels);
	fprintf(stderr, "Info - set to operate as an SSL %s\n",
			(server_mode ? "server" : "client"));
	/* Initialise the rest of the stuff */
	world.tunnels_used = world.tunnels_size = 0;
	world.tunnels = NULL;
	world.server_mode = server_mode;
	selector_init(&world.selector);

/* We're ready to loop */
main_loop:
	/* Should we listen for *new* tunnels? */
	if(world.tunnels_used < max_tunnels)
		selector_add_listener(&world.selector, world.listen_fd);
	/* We should add in our existing tunnels */
	for(loop = 0; loop < world.tunnels_used; loop++)
		selector_add_tunala(&world.selector, world.tunnels + loop);
	/* Now do the select */
	switch(selector_select(&world.selector)) {
	case -1:
		fprintf(stderr, "selector_select returned a badness error.\n");
		abort();
	case 0:
		fprintf(stderr, "Warn, selector_select return 0 - signal??\n");
		goto main_loop;
	default:
		break;
	}
	/* Accept new connection if we should and can */
	if((world.tunnels_used < max_tunnels) && (selector_get_listener(
					&world.selector, world.listen_fd,
					&newfd) == 1)) {
		/* We have a new connection */
		if(!tunala_world_new_item(&world, newfd,
					proxy_ip, proxy_port)) {
			fprintf(stderr, "tunala_world_new_item failed\n");
			abort();
		}
		fprintf(stderr, "Info, new tunnel opened, now up to %d\n",
				world.tunnels_used);
	}
	/* Give each tunnel its moment, note the while loop is because it makes
	 * the logic easier than with "for" to deal with an array that may shift
	 * because of deletes. */
	loop = 0;
	t_item = world.tunnels;
	while(loop < world.tunnels_used) {
		if(!tunala_item_io(&world.selector, t_item)) {
			/* We're closing whether for reasons of an error or a
			 * natural close. Don't increment loop or t_item because
			 * the next item is moving to us! */
			tunala_world_del_item(&world, loop);
			fprintf(stderr, "Info, tunnel closed, down to %d\n",
					world.tunnels_used);
		}
		else {
			/* Move to the next item */
			loop++;
			t_item++;
		}
	}
	goto main_loop;
	/* Should never get here */
	abort();
	return 1;
}

/****************/
/* OpenSSL bits */
/****************/

static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
		const char *CAfile, const char *cert, const char *key)
{
	SSL_CTX *ctx, *ret = NULL;
	SSL_METHOD *meth;
	ENGINE *e = NULL;
	FILE *fp = NULL;
	X509 *x509 = NULL;
	EVP_PKEY *pkey = NULL;

        OpenSSL_add_ssl_algorithms();
        SSL_load_error_strings();

	meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method());
	if(meth == NULL)
		goto err;
	if(engine_id) {
		if((e = ENGINE_by_id(engine_id)) == NULL) {
			fprintf(stderr, "Error obtaining '%s' engine, openssl "
					"errors follow\n", engine_id);
			goto err;
		}
		if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
			fprintf(stderr, "Error assigning '%s' engine, openssl "
					"errors follow\n", engine_id);
			goto err;
		}
		ENGINE_free(e);
	}
	if((ctx = SSL_CTX_new(meth)) == NULL)
		goto err;
	/* cacert */
	if(CAfile) {
		if(!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx),
					CAfile, NULL)) {
			fprintf(stderr, "Error loading CA cert(s) in '%s'\n",
					CAfile);
			goto err;
		}
		fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n",
				CAfile);
	} else
		fprintf(stderr, "Info, operating without a CA cert(-list)\n");
	if(!SSL_CTX_set_default_verify_paths(ctx)) {
		fprintf(stderr, "Error setting default verify paths\n");
		goto err;
	}
	/* cert */
	if(cert) {
		if((fp = fopen(cert, "r")) == NULL) {
			fprintf(stderr, "Error opening cert file '%s'\n", cert);
			goto err;
		}
		if(!PEM_read_X509(fp, &x509, NULL, NULL)) {
			fprintf(stderr, "Error reading PEM cert from '%s'\n",
					cert);
			goto err;
		}
		if(!SSL_CTX_use_certificate(ctx, x509)) {
			fprintf(stderr, "Error, cert in '%s' can not be used\n",
					cert);
			goto err;
		}
		fprintf(stderr, "Info, operating with cert in '%s'\n", cert);
		fclose(fp);
		fp = NULL;
		/* If a cert was given without matching key, we assume the same
		 * file contains the required key. */
		if(!key)
			key = cert;
	} else
		if(key) {
			fprintf(stderr, "Error, can't specify a key without a "
					"corresponding certificate\n");
			goto err;
		}
	/* key */
	if(key) {
		if((fp = fopen(key, "r")) == NULL) {
			fprintf(stderr, "Error opening key file '%s'\n", key);
			goto err;
		}
		if(!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) {
			fprintf(stderr, "Error reading PEM key from '%s'\n",
					key);
			goto err;
		}
		if(!SSL_CTX_use_PrivateKey(ctx, pkey)) {
			fprintf(stderr, "Error, key in '%s' can not be used\n",
					key);
			goto err;
		}
		fprintf(stderr, "Info, operating with key in '%s'\n", key);
	} else
		fprintf(stderr, "Info, operating without a cert or key\n");

	/* Success! */
	ret = ctx;
err:
	if(!ret) {
		ERR_print_errors_fp(stderr);
		if(ctx)
			SSL_CTX_free(ctx);
	}
	if(fp)
		fclose(fp);
	if(x509)
		X509_free(x509);
	if(pkey)
		EVP_PKEY_free(pkey);
	return ret;
}

/*****************/
/* Selector bits */
/*****************/

static void selector_sets_init(select_sets_t *s)
{
	s->max = 0;
	FD_ZERO(&s->reads);
	FD_ZERO(&s->sends);
	FD_ZERO(&s->excepts);
}
static void selector_init(tunala_selector_t *selector)
{
	selector_sets_init(&selector->last_selected);
	selector_sets_init(&selector->next_select);
}

#define SEL_EXCEPTS 0x00
#define SEL_READS   0x01
#define SEL_SENDS   0x02
static void selector_add_raw_fd(tunala_selector_t *s, int fd, int flags)
{
	FD_SET(fd, &s->next_select.excepts);
	if(flags & SEL_READS)
		FD_SET(fd, &s->next_select.reads);
	if(flags & SEL_SENDS)
		FD_SET(fd, &s->next_select.sends);
	/* Adjust "max" */
	if(s->next_select.max < (fd + 1))
		s->next_select.max = fd + 1;
}

static void selector_add_listener(tunala_selector_t *selector, int fd)
{
	selector_add_raw_fd(selector, fd, SEL_READS);
}

static void selector_add_tunala(tunala_selector_t *s, tunala_item_t *t)
{
	/* Set clean read if sm.clean_in is not full */
	if(t->clean_read != -1) {
		selector_add_raw_fd(s, t->clean_read,
			(buffer_full(state_machine_get_buffer(&t->sm,
				SM_CLEAN_IN)) ? SEL_EXCEPTS : SEL_READS));
	}
	/* Set clean send if sm.clean_out is not empty */
	if(t->clean_send != -1) {
		selector_add_raw_fd(s, t->clean_send,
			(buffer_empty(state_machine_get_buffer(&t->sm,
				SM_CLEAN_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
	}
	/* Set dirty read if sm.dirty_in is not full */
	if(t->dirty_read != -1) {
		selector_add_raw_fd(s, t->dirty_read,
			(buffer_full(state_machine_get_buffer(&t->sm,
				SM_DIRTY_IN)) ? SEL_EXCEPTS : SEL_READS));
	}
	/* Set dirty send if sm.dirty_out is not empty */
	if(t->dirty_send != -1) {
		selector_add_raw_fd(s, t->dirty_send,
			(buffer_empty(state_machine_get_buffer(&t->sm,
				SM_DIRTY_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
	}
}

static int selector_select(tunala_selector_t *selector)
{
	memcpy(&selector->last_selected, &selector->next_select,
			sizeof(select_sets_t));
	selector_sets_init(&selector->next_select);
	return select(selector->last_selected.max,
			&selector->last_selected.reads,
			&selector->last_selected.sends,
			&selector->last_selected.excepts, NULL);
}

/* This returns -1 for error, 0 for no new connections, or 1 for success, in
 * which case *newfd is populated. */
static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd)
{
	if(FD_ISSET(fd, &selector->last_selected.excepts))
		return -1;
	if(!FD_ISSET(fd, &selector->last_selected.reads))
		return 0;
	if((*newfd = ip_accept_connection(fd)) == -1)
		return -1;
	return 1;
}

/************************/
/* "Tunala" world stuff */
/************************/

static int tunala_world_make_room(tunala_world_t *world)
{
	unsigned int newsize;
	tunala_item_t *newarray;

	if(world->tunnels_used < world->tunnels_size)
		return 1;
	newsize = (world->tunnels_size == 0 ? 16 :
			((world->tunnels_size * 3) / 2));
	if((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL)
		return 0;
	memset(newarray, 0, newsize * sizeof(tunala_item_t));
	if(world->tunnels_used > 0)
		memcpy(newarray, world->tunnels,
			world->tunnels_used * sizeof(tunala_item_t));
	if(world->tunnels_size > 0)
		free(world->tunnels);
	/* migrate */
	world->tunnels = newarray;
	world->tunnels_size = newsize;
	return 1;
}

static int tunala_world_new_item(tunala_world_t *world, int fd,
		const unsigned char *ip, unsigned short port)
{
	tunala_item_t *item;
	int newfd;

	if(!tunala_world_make_room(world))
		return 0;
	item = world->tunnels + (world->tunnels_used++);
	state_machine_init(&item->sm);
	item->clean_read = item->clean_send =
		item->dirty_read = item->dirty_send = -1;
	if((newfd = ip_create_connection_split(ip, port)) == -1)
		goto err;
	/* Which way round? If we're a server, "fd" is the dirty side and the
	 * connection we open is the clean one. For a client, it's the other way
	 * around. */
	if(world->server_mode) {
		item->dirty_read = item->dirty_send = fd;
		item->clean_read = item->clean_send = newfd;
	} else {
		item->clean_read = item->clean_send = fd;
		item->dirty_read = item->dirty_send = newfd;
	}
	state_machine_set_SSL(&item->sm, SSL_new(world->ssl_ctx),
			world->server_mode);
	return 1;
err:
	state_machine_close(&item->sm);
	return 0;

}

static void tunala_world_del_item(tunala_world_t *world, unsigned int idx)
{
	tunala_item_t *item = world->tunnels + idx;
	if(item->clean_read != -1)
		close(item->clean_read);
	if(item->clean_send != item->clean_read)
		close(item->clean_send);
	item->clean_read = item->clean_send = -1;
	if(item->dirty_read != -1)
		close(item->dirty_read);
	if(item->dirty_send != item->dirty_read)
		close(item->dirty_send);
	item->dirty_read = item->dirty_send = -1;
	state_machine_close(&item->sm);
	/* OK, now we fix the item array */
	if(idx + 1 < world->tunnels_used)
		/* We need to scroll entries to the left */
		memmove(world->tunnels + idx,
				world->tunnels + (idx + 1),
				(world->tunnels_used - (idx + 1)) *
					sizeof(tunala_item_t));
	world->tunnels_used--;
}

static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item)
{
	int c_r, c_s, d_r, d_s; /* Four boolean flags */

	/* Take ourselves out of the gene-pool if there was an except */
	if((item->clean_read != -1) && FD_ISSET(item->clean_read,
				&selector->last_selected.excepts))
		return 0;
	if((item->clean_send != -1) && FD_ISSET(item->clean_send,
				&selector->last_selected.excepts))
		return 0;
	if((item->dirty_read != -1) && FD_ISSET(item->dirty_read,
				&selector->last_selected.excepts))
		return 0;
	if((item->dirty_send != -1) && FD_ISSET(item->dirty_send,
				&selector->last_selected.excepts))
		return 0;
	/* Grab our 4 IO flags */
	c_r = c_s = d_r = d_s = 0;
	if(item->clean_read != -1)
		c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads);
	if(item->clean_send != -1)
		c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends);
	if(item->dirty_read != -1)
		d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads);
	if(item->dirty_send != -1)
		d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends);
	/* If no IO has happened for us, skip needless data looping */
	if(!c_r && !c_s && !d_r && !d_s)
		return 1;
	if(c_r)
		c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
				SM_CLEAN_IN), item->clean_read) <= 0);
	if(c_s)
		c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
				SM_CLEAN_OUT), item->clean_send) <= 0);
	if(d_r)
		d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
				SM_DIRTY_IN), item->dirty_read) <= 0);
	if(d_s)
		d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
				SM_DIRTY_OUT), item->dirty_send) <= 0);
	/* If any of the flags is non-zero, that means they need closing */
	if(c_r) {
		close(item->clean_read);
		if(item->clean_send == item->clean_read)
			item->clean_send = -1;
		item->clean_read = -1;
	}
	if(c_s) {
		close(item->clean_send);
		if(item->clean_send == item->clean_read)
			item->clean_read = -1;
		item->clean_send = -1;
	}
	if(d_r) {
		close(item->dirty_read);
		if(item->dirty_send == item->dirty_read)
			item->dirty_send = -1;
		item->dirty_read = -1;
	}
	if(d_s) {
		close(item->dirty_send);
		if(item->dirty_send == item->dirty_read)
			item->dirty_read = -1;
		item->dirty_send = -1;
	}
	/* This function name is attributed to the term donated by David
	 * Schwartz on openssl-dev, message-ID:
	 * <NCBBLIEPOCNJOAEKBEAKEEDGLIAA.davids@webmaster.com>. :-) */
	if(!state_machine_churn(&item->sm))
		/* If the SSL closes, it will also zero-out the _in buffers
		 * and will in future process just outgoing data. As and
		 * when the outgoing data has gone, it will return zero
		 * here to tell us to bail out. */
		return 0;
	/* Otherwise, we return zero if both sides are dead. */
	if(((item->clean_read == -1) || (item->clean_send == -1)) &&
			((item->dirty_read == -1) || (item->dirty_send == -1)))
		return 0;
	/* If only one side closed, notify the SSL of this so it can take
	 * appropriate action. */
	if((item->clean_read == -1) || (item->clean_send == -1)) {
		if(!state_machine_close_clean(&item->sm))
			return 0;
	}
	if((item->dirty_read == -1) || (item->dirty_send == -1)) {
		if(state_machine_close_dirty(&item->sm))
			return 0;
	}
	return 1;
}