aboutsummaryrefslogtreecommitdiffstats
path: root/src/charon/sa/ike_sa_manager.c
blob: 311b18c8ca1786dfd5fbb3825f0d476bfab42a62 (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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
/*
 * Copyright (C) 2008 Tobias Brunner
 * Copyright (C) 2005-2008 Martin Willi
 * Copyright (C) 2005 Jan Hutter
 * Hochschule fuer Technik Rapperswil
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * $Id$
 */

#include <string.h>

#include "ike_sa_manager.h"

#include <daemon.h>
#include <sa/ike_sa_id.h>
#include <bus/bus.h>
#include <utils/mutex.h>
#include <utils/linked_list.h>
#include <crypto/hashers/hasher.h>

/* the default size of the hash table (MUST be a power of 2) */
#define DEFAULT_HASHTABLE_SIZE 1

/* the maximum size of the hash table (MUST be a power of 2) */
#define MAX_HASHTABLE_SIZE (1 << 30)

/* the default number of segments (MUST be a power of 2) */
#define DEFAULT_SEGMENT_COUNT 1

typedef struct entry_t entry_t;

/**
 * An entry in the linked list, contains IKE_SA, locking and lookup data.
 */
struct entry_t {
	
	/**
	 * Number of threads waiting for this ike_sa_t object.
	 */
	int waiting_threads;
	
	/**
	 * Condvar where threads can wait until ike_sa_t object is free for use again.
	 */
	condvar_t *condvar;
	
	/**
	 * Is this ike_sa currently checked out?
	 */
	bool checked_out;
	
	/**
	 * Does this SA drives out new threads?
	 */
	bool driveout_new_threads;
	
	/**
	 * Does this SA drives out waiting threads?
	 */
	bool driveout_waiting_threads;
	
	/**
	 * Identification of an IKE_SA (SPIs).
	 */
	ike_sa_id_t *ike_sa_id;
	
	/**
	 * The contained ike_sa_t object.
	 */
	ike_sa_t *ike_sa;
	
	/**
	 * hash of the IKE_SA_INIT message, used to detect retransmissions
	 */
	chunk_t init_hash;
	
	/**
	 * remote host address, required for DoS detection
	 */
	host_t *other;
	
	/**
	 * As responder: Is this SA half-open?
	 */
	bool half_open;
		
	/**
	 * own identity, required for duplicate checking
	 */
	identification_t *my_id;
	
	/**
	 * remote identity, required for duplicate checking
	 */
	identification_t *other_id;
	
	/**
	 * message ID currently processing, if any
	 */
	u_int32_t message_id;
};

/**
 * Implementation of entry_t.destroy.
 */
static status_t entry_destroy(entry_t *this)
{
	/* also destroy IKE SA */
	this->ike_sa->destroy(this->ike_sa);
	this->ike_sa_id->destroy(this->ike_sa_id);
	chunk_free(&this->init_hash);
	DESTROY_IF(this->other);
	DESTROY_IF(this->my_id);
	DESTROY_IF(this->other_id);
	this->condvar->destroy(this->condvar);
	free(this);
	return SUCCESS;
}

/**
 * Creates a new entry for the ike_sa_t list.
 */
static entry_t *entry_create()
{
	entry_t *this = malloc_thing(entry_t);
	
	this->waiting_threads = 0;
	this->condvar = condvar_create(CONDVAR_DEFAULT);
	
	/* we set checkout flag when we really give it out */
	this->checked_out = FALSE;
	this->driveout_new_threads = FALSE;
	this->driveout_waiting_threads = FALSE;
	this->message_id = -1;
	this->init_hash = chunk_empty;
	this->other = NULL;
	this->half_open = FALSE;
	this->my_id = NULL;
	this->other_id = NULL;
	this->ike_sa_id = NULL;
	this->ike_sa = NULL;
	
	return this;
}

/**
 * Function that matches entry_t objects by initiator SPI and the hash of the
 * IKE_SA_INIT message.
 */
static bool entry_match_by_hash(entry_t *entry, ike_sa_id_t *id, chunk_t *hash)
{
	return id->get_responder_spi(id) == 0 &&
		id->is_initiator(id) == entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
		id->get_initiator_spi(id) == entry->ike_sa_id->get_initiator_spi(entry->ike_sa_id) &&
		chunk_equals(*hash, entry->init_hash);
}

/**
 * Function that matches entry_t objects by ike_sa_id_t.
 */
static bool entry_match_by_id(entry_t *entry, ike_sa_id_t *id)
{
	if (id->equals(id, entry->ike_sa_id))
	{
		return TRUE;
	}	
	if ((id->get_responder_spi(id) == 0 ||
		 entry->ike_sa_id->get_responder_spi(entry->ike_sa_id) == 0) &&
		id->is_initiator(id) == entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
		id->get_initiator_spi(id) == entry->ike_sa_id->get_initiator_spi(entry->ike_sa_id))
	{
		/* this is TRUE for IKE_SAs that we initiated but have not yet received a response */
		return TRUE;
	}
	return FALSE;
}

/**
 * Function that matches entry_t objects by ike_sa_t pointers.
 */
static bool entry_match_by_sa(entry_t *entry, ike_sa_t *ike_sa)
{
	return entry->ike_sa == ike_sa;
}

/**
 * Hash function for ike_sa_id_t objects.
 */
static u_int ike_sa_id_hash(ike_sa_id_t *ike_sa_id)
{
	/* we always use initiator spi as key */
	return ike_sa_id->get_initiator_spi(ike_sa_id);
}

typedef struct half_open_t half_open_t;

/**
 * Struct to manage half-open IKE_SAs per peer.
 */
struct half_open_t {
	/** chunk of remote host address */
	chunk_t other;
	
	/** the number of half-open IKE_SAs with that host */
	u_int count;
};

/**
 * Destroys a half_open_t object.
 */
static void half_open_destroy(half_open_t *this)
{
	chunk_free(&this->other);
	free(this);
}

/**
 * Function that matches half_open_t objects by the given IP address chunk.
 */
static bool half_open_match(half_open_t *half_open, chunk_t *addr)
{
	return chunk_equals(*addr, half_open->other);
}

typedef struct connected_peers_t connected_peers_t;

struct connected_peers_t {
	/** own identity */
	identification_t *my_id;
	
	/** remote identity */
	identification_t *other_id;
	
	/** list of ike_sa_id_t objects of IKE_SAs between the two identities */
	linked_list_t *sas;
};

static void connected_peers_destroy(connected_peers_t *this)
{
	this->my_id->destroy(this->my_id);
	this->other_id->destroy(this->other_id);
	this->sas->destroy(this->sas);
	free(this);
}

/**
 * Function that matches connected_peers_t objects by the given ids.
 */
static bool connected_peers_match(connected_peers_t *connected_peers,
							identification_t *my_id, identification_t *other_id)
{
	return my_id->equals(my_id, connected_peers->my_id) &&
		   other_id->equals(other_id, connected_peers->other_id);
}

typedef struct segment_t segment_t;

/**
 * Struct to manage segments of the hash table.
 */
struct segment_t {
	/** mutex to access a segment exclusively */
	mutex_t *mutex;
	
	/** the number of entries in this segment */
	u_int count;
};

typedef struct shareable_segment_t shareable_segment_t;

/**
 * Struct to manage segments of the "half-open" and "connected peers" hash tables.
 */
struct shareable_segment_t {
	/** rwlock to access a segment non-/exclusively */
	rwlock_t *lock;
	
	/** the number of entries in this segment - in case of the "half-open table"
	 * it's the sum of all half_open_t.count in a segment. */
	u_int count;
};

typedef struct private_ike_sa_manager_t private_ike_sa_manager_t;

/**
 * Additional private members of ike_sa_manager_t.
 */
struct private_ike_sa_manager_t {
	/**
	 * Public interface of ike_sa_manager_t.
	 */
	 ike_sa_manager_t public;
	
	 /**
	  * Hash table with entries for the ike_sa_t objects.
	  */
	 linked_list_t **ike_sa_table;
	 
	 /**
	  * The size of the hash table.
	  */
	 u_int table_size;
	 
	 /**
	  * Mask to map the hashes to table rows.
	  */
	 u_int table_mask;
	 
	 /**
	  * Segments of the hash table.
	  */
	 segment_t *segments;
	 
	 /**
	  * The number of segments.
	  */
	 u_int segment_count;
	 
	 /**
	  * Mask to map a table row to a segment.
	  */
	 u_int segment_mask;
	 
	 /**
	  * Hash table with half_open_t objects.
	  */
	 linked_list_t **half_open_table;
	 
	 /**
	  * Segments of the "half-open" hash table.
	  */
	 shareable_segment_t *half_open_segments;
	 
	 /**
	  * Hash table with connected_peers_t objects.
	  */
	 linked_list_t **connected_peers_table;
	 
	 /**
	  * Segments of the "connected peers" hash table.
	  */
	 shareable_segment_t *connected_peers_segments;
	 
	 /**
	  * RNG to get random SPIs for our side
	  */
	 rng_t *rng;
	 
	 /**
	  * SHA1 hasher for IKE_SA_INIT retransmit detection
	  */
	 hasher_t *hasher;
	
	/**
	 * reuse existing IKE_SAs in checkout_by_config
	 */
	 bool reuse_ikesa;
};

/**
 * Acquire a lock to access the segment of the table row with the given index.
 * It also works with the segment index directly.
 */
static void lock_single_segment(private_ike_sa_manager_t *this, u_int index)
{
	mutex_t *lock = this->segments[index & this->segment_mask].mutex;
	
	lock->lock(lock);
}

/**
 * Release the lock required to access the segment of the table row with the given index.
 * It also works with the segment index directly.
 */
static void unlock_single_segment(private_ike_sa_manager_t *this, u_int index)
{
	mutex_t *lock = this->segments[index & this->segment_mask].mutex;
	
	lock->unlock(lock);
}

/**
 * Lock all segments
 */
static void lock_all_segments(private_ike_sa_manager_t *this)
{
	u_int i;
	
	for (i = 0; i < this->segment_count; ++i)
	{
		this->segments[i].mutex->lock(this->segments[i].mutex);
	}
}

/**
 * Unlock all segments
 */
static void unlock_all_segments(private_ike_sa_manager_t *this)
{
	u_int i;
	
	for (i = 0; i < this->segment_count; ++i)
	{
		this->segments[i].mutex->unlock(this->segments[i].mutex);
	}
}

typedef struct private_enumerator_t private_enumerator_t;

/**
 * hash table enumerator implementation
 */
struct private_enumerator_t {

	/**
	 * implements enumerator interface
	 */
	enumerator_t enumerator;
	
	/**
	 * associated ike_sa_manager_t
	 */
	private_ike_sa_manager_t *manager;
	
	/**
	 * current segment index
	 */
	u_int segment;
	
	/**
	 * currently enumerating entry
	 */
	entry_t *entry;
	
	/**
	 * current table row index
	 */
	u_int row;
	
	/**
	 * enumerator for the current table row
	 */
	enumerator_t *current;
};

/**
 * Implementation of private_enumerator_t.enumerator.enumerate.
 */
static bool enumerate(private_enumerator_t *this, entry_t **entry, u_int *segment)
{
	if (this->entry)
	{
		this->entry->condvar->signal(this->entry->condvar);
		this->entry = NULL;
	}
	while (this->segment < this->manager->segment_count)
	{
		while (this->row < this->manager->table_size)
		{
			if (this->current)
			{
				entry_t *item;
				
				if (this->current->enumerate(this->current, &item))
				{
					*entry = this->entry = item;
					*segment = this->segment;
					return TRUE;
				}
				this->current->destroy(this->current);
				this->current = NULL;
				unlock_single_segment(this->manager, this->segment);
			}
			else
			{
				linked_list_t *list;
				
				lock_single_segment(this->manager, this->segment);
				if ((list = this->manager->ike_sa_table[this->row]) != NULL &&
					 list->get_count(list))
				{
					this->current = list->create_enumerator(list);
					continue;
				}
				unlock_single_segment(this->manager, this->segment);
			}
			this->row += this->manager->segment_count;
		}
		this->segment++;
		this->row = this->segment;
	}
	return FALSE;
}

/**
 * Implementation of private_enumerator_t.enumerator.destroy.
 */
static void enumerator_destroy(private_enumerator_t *this)
{
	if (this->entry)
	{
		this->entry->condvar->signal(this->entry->condvar);
	}
	if (this->current)
	{
		this->current->destroy(this->current);
		unlock_single_segment(this->manager, this->segment);
	}
	free(this);
}

/**
 * Creates an enumerator to enumerate the entries in the hash table.
 */
static enumerator_t* create_table_enumerator(private_ike_sa_manager_t *this)
{
	private_enumerator_t *enumerator = malloc_thing(private_enumerator_t);
	
	enumerator->enumerator.enumerate = (void*)enumerate;
	enumerator->enumerator.destroy = (void*)enumerator_destroy;
	enumerator->manager = this;
	enumerator->segment = 0;
	enumerator->entry = NULL;
	enumerator->row = 0;
	enumerator->current = NULL;
	
	return &enumerator->enumerator;
}

/**
 * Put an entry into the hash table.
 * Note: The caller has to unlock the returned segment.
 */
static u_int put_entry(private_ike_sa_manager_t *this, entry_t *entry)
{
	linked_list_t *list;
	u_int row = ike_sa_id_hash(entry->ike_sa_id) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	lock_single_segment(this, segment);
	if ((list = this->ike_sa_table[row]) == NULL)
	{
		list = this->ike_sa_table[row] = linked_list_create();
	}
	list->insert_last(list, entry);
	this->segments[segment].count++;
	return segment;
}

/**
 * Remove an entry from the hash table.
 * Note: The caller MUST have a lock on the segment of this entry.
 */
static void remove_entry(private_ike_sa_manager_t *this, entry_t *entry)
{
	linked_list_t *list;
	u_int row = ike_sa_id_hash(entry->ike_sa_id) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	if ((list = this->ike_sa_table[row]) != NULL)
	{
		entry_t *current;

		enumerator_t *enumerator = list->create_enumerator(list);
		while (enumerator->enumerate(enumerator, &current))
		{
			if (current == entry)
			{
				list->remove_at(list, enumerator);
				this->segments[segment].count--;
				break;
			}
		}
		enumerator->destroy(enumerator);
	}
}

/**
 * Remove the entry at the current enumerator position.
 */
static void remove_entry_at(private_enumerator_t *this)
{
	this->entry = NULL;
	if (this->current)
	{
		linked_list_t *list = this->manager->ike_sa_table[this->row];
		list->remove_at(list, this->current);
		this->manager->segments[this->segment].count--;
	}
}

/**
 * Find an entry using the provided match function to compare the entries for
 * equality.
 */
static status_t get_entry_by_match_function(private_ike_sa_manager_t *this,
					ike_sa_id_t *ike_sa_id, entry_t **entry, u_int *segment,
					linked_list_match_t match, void *p1, void *p2)
{
	entry_t *current;
	linked_list_t *list;
	u_int row = ike_sa_id_hash(ike_sa_id) & this->table_mask;
	u_int seg = row & this->segment_mask;
	
	lock_single_segment(this, seg);
	if ((list = this->ike_sa_table[row]) != NULL)
	{
		if (list->find_first(list, match, (void**)&current, p1, p2) == SUCCESS)
		{
			*entry = current;
			*segment = seg;
			/* the locked segment has to be unlocked by the caller */
			return SUCCESS;
		}
	}
	unlock_single_segment(this, seg);
	return NOT_FOUND;
}

/**
 * Find an entry by ike_sa_id_t.
 * Note: On SUCCESS, the caller has to unlock the segment.
 */
static status_t get_entry_by_id(private_ike_sa_manager_t *this,
						ike_sa_id_t *ike_sa_id, entry_t **entry, u_int *segment)
{
	return get_entry_by_match_function(this, ike_sa_id, entry, segment, 
				(linked_list_match_t)entry_match_by_id, ike_sa_id, NULL);
}

/**
 * Find an entry by initiator SPI and IKE_SA_INIT hash.
 * Note: On SUCCESS, the caller has to unlock the segment.
 */
static status_t get_entry_by_hash(private_ike_sa_manager_t *this,
			ike_sa_id_t *ike_sa_id, chunk_t hash, entry_t **entry, u_int *segment)
{
	return get_entry_by_match_function(this, ike_sa_id, entry, segment,
				(linked_list_match_t)entry_match_by_hash, ike_sa_id, &hash);
}

/**
 * Find an entry by IKE_SA pointer.
 * Note: On SUCCESS, the caller has to unlock the segment.
 */
static status_t get_entry_by_sa(private_ike_sa_manager_t *this,
			ike_sa_id_t *ike_sa_id, ike_sa_t *ike_sa, entry_t **entry, u_int *segment)
{
	return get_entry_by_match_function(this, ike_sa_id, entry, segment,
				(linked_list_match_t)entry_match_by_sa, ike_sa, NULL);
}

/**
 * Wait until no other thread is using an IKE_SA, return FALSE if entry not
 * acquirable.
 */
static bool wait_for_entry(private_ike_sa_manager_t *this, entry_t *entry,
						   u_int segment)
{
	if (entry->driveout_new_threads)
	{
		/* we are not allowed to get this */
		return FALSE;
	}
	while (entry->checked_out && !entry->driveout_waiting_threads)	
	{
		/* so wait until we can get it for us.
		 * we register us as waiting. */
		entry->waiting_threads++;
		entry->condvar->wait(entry->condvar, this->segments[segment].mutex);
		entry->waiting_threads--;
	}
	/* hm, a deletion request forbids us to get this SA, get next one */
	if (entry->driveout_waiting_threads)
	{
		/* we must signal here, others may be waiting on it, too */
		entry->condvar->signal(entry->condvar);
		return FALSE;
	}
	return TRUE;
}

/**
 * Put a half-open SA into the hash table.
 */
static void put_half_open(private_ike_sa_manager_t *this, entry_t *entry)
{
	half_open_t *half_open = NULL;
	linked_list_t *list;
	chunk_t addr = entry->other->get_address(entry->other);
	u_int row = chunk_hash(addr) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	rwlock_t *lock = this->half_open_segments[segment].lock;
	lock->write_lock(lock);
	if ((list = this->half_open_table[row]) == NULL)
	{
		list = this->half_open_table[row] = linked_list_create();
	}
	else
	{
		half_open_t *current;
		if (list->find_first(list, (linked_list_match_t)half_open_match,
							 (void**)&current, &addr) == SUCCESS)
		{
			half_open = current;
			half_open->count++;
			this->half_open_segments[segment].count++;
		}
	}
	
	if (!half_open)
	{
		half_open = malloc_thing(half_open_t);
		half_open->other = chunk_clone(addr);
		half_open->count = 1;
		list->insert_last(list, half_open);
		this->half_open_segments[segment].count++;
	}
	lock->unlock(lock);
}

/**
 * Remove a half-open SA from the hash table.
 */
static void remove_half_open(private_ike_sa_manager_t *this, entry_t *entry)
{
	linked_list_t *list;
	chunk_t addr = entry->other->get_address(entry->other);
	u_int row = chunk_hash(addr) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	rwlock_t *lock = this->half_open_segments[segment].lock;
	lock->write_lock(lock);
	if ((list = this->half_open_table[row]) != NULL)
	{
		half_open_t *current;
		enumerator_t *enumerator = list->create_enumerator(list);
		while (enumerator->enumerate(enumerator, &current))
		{
			if (half_open_match(current, &addr))
			{
				if (--current->count == 0)
				{
					list->remove_at(list, enumerator);
					half_open_destroy(current);
				}
				this->half_open_segments[segment].count--;
				break;
			}
		}
		enumerator->destroy(enumerator);
	}
	lock->unlock(lock);
}

/**
 * Put an SA between two peers into the hash table.
 */
static void put_connected_peers(private_ike_sa_manager_t *this, entry_t *entry)
{
	linked_list_t *list;
	connected_peers_t *connected_peers = NULL;
	chunk_t my_id = entry->my_id->get_encoding(entry->my_id),
			other_id = entry->other_id->get_encoding(entry->other_id);
	u_int row = chunk_hash_inc(other_id, chunk_hash(my_id)) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	rwlock_t *lock = this->connected_peers_segments[segment].lock;
	lock->write_lock(lock);
	if ((list = this->connected_peers_table[row]) == NULL)
	{
		list = this->connected_peers_table[row] = linked_list_create();
	}
	else
	{
		connected_peers_t *current;
		if (list->find_first(list, (linked_list_match_t)connected_peers_match,
					(void**)&current, entry->my_id, entry->other_id) == SUCCESS)
		{
			connected_peers = current;
			if (connected_peers->sas->find_first(connected_peers->sas,
					(linked_list_match_t)entry->ike_sa_id->equals,
					NULL, entry->ike_sa_id) == SUCCESS)
			{
				lock->unlock(lock);
				return;
			}
		}
	}
	
	if (!connected_peers)
	{
		connected_peers = malloc_thing(connected_peers_t);
		connected_peers->my_id = entry->my_id->clone(entry->my_id);
		connected_peers->other_id = entry->other_id->clone(entry->other_id);
		connected_peers->sas = linked_list_create();
		list->insert_last(list, connected_peers);
	}
	connected_peers->sas->insert_last(connected_peers->sas,
									  entry->ike_sa_id->clone(entry->ike_sa_id));
	this->connected_peers_segments[segment].count++;
	lock->unlock(lock);
}

/**
 * Remove an SA between two peers from the hash table.
 */
static void remove_connected_peers(private_ike_sa_manager_t *this, entry_t *entry)
{
	linked_list_t *list;
	chunk_t my_id = entry->my_id->get_encoding(entry->my_id),
			other_id = entry->other_id->get_encoding(entry->other_id);
	u_int row = chunk_hash_inc(other_id, chunk_hash(my_id)) & this->table_mask;
	u_int segment = row & this->segment_mask;
	
	rwlock_t *lock = this->connected_peers_segments[segment].lock;
	lock->write_lock(lock);
	if ((list = this->connected_peers_table[row]) != NULL)
	{
		connected_peers_t *current;
		enumerator_t *enumerator = list->create_enumerator(list);
		while (enumerator->enumerate(enumerator, &current))
		{
			if (connected_peers_match(current, entry->my_id, entry->other_id))
			{
				ike_sa_id_t *ike_sa_id;
				enumerator_t *inner = current->sas->create_enumerator(current->sas);
				while (inner->enumerate(inner, &ike_sa_id))
				{
					if (ike_sa_id->equals(ike_sa_id, entry->ike_sa_id))
					{
						current->sas->remove_at(current->sas, inner);
						ike_sa_id->destroy(ike_sa_id);
						this->connected_peers_segments[segment].count--;
						break;
					}
				}
				inner->destroy(inner);
				if (current->sas->get_count(current->sas) == 0)
				{
					list->remove_at(list, enumerator);
					connected_peers_destroy(current);
				}
				break;
			}
		}
		enumerator->destroy(enumerator);
	}
	lock->unlock(lock);
}

/**
 * Implementation of private_ike_sa_manager_t.get_next_spi.
 */
static u_int64_t get_next_spi(private_ike_sa_manager_t *this)
{
	u_int64_t spi;
	
	this->rng->get_bytes(this->rng, sizeof(spi), (u_int8_t*)&spi);
	return spi;
}

/**
 * Implementation of of ike_sa_manager.checkout.
 */
static ike_sa_t* checkout(private_ike_sa_manager_t *this, ike_sa_id_t *ike_sa_id)
{
	ike_sa_t *ike_sa = NULL;
	entry_t *entry;
	u_int segment;
	
	DBG2(DBG_MGR, "checkout IKE_SA");
	
	if (get_entry_by_id(this, ike_sa_id, &entry, &segment) == SUCCESS)
	{
		if (wait_for_entry(this, entry, segment))
		{
			DBG2(DBG_MGR, "IKE_SA successfully checked out");
			entry->checked_out = TRUE;
			ike_sa = entry->ike_sa;
		}
		unlock_single_segment(this, segment);
	}
	charon->bus->set_sa(charon->bus, ike_sa);
	return ike_sa;
}

/**
 * Implementation of of ike_sa_manager.checkout_new.
 */
static ike_sa_t *checkout_new(private_ike_sa_manager_t* this, bool initiator)
{
	ike_sa_id_t *ike_sa_id;
	ike_sa_t *ike_sa;
	entry_t *entry;
	u_int segment;
	
	if (initiator)
	{
		ike_sa_id = ike_sa_id_create(get_next_spi(this), 0, TRUE);
	}
	else
	{
		ike_sa_id = ike_sa_id_create(0, get_next_spi(this), FALSE);
	}
	ike_sa = ike_sa_create(ike_sa_id);
	
	DBG2(DBG_MGR, "created IKE_SA");
	
	if (!initiator)
	{
		ike_sa_id->destroy(ike_sa_id);
		return ike_sa;
	}
	
	entry = entry_create();
	entry->ike_sa_id = ike_sa_id;
	entry->ike_sa = ike_sa;
	segment = put_entry(this, entry);
	entry->checked_out = TRUE;
	unlock_single_segment(this, segment);
	return entry->ike_sa;
}

/**
 * Implementation of of ike_sa_manager.checkout_by_message.
 */
static ike_sa_t* checkout_by_message(private_ike_sa_manager_t* this,
									 message_t *message)
{
	u_int segment;
	entry_t *entry;
	ike_sa_t *ike_sa = NULL;
	ike_sa_id_t *id = message->get_ike_sa_id(message);

	id = id->clone(id);
	id->switch_initiator(id);
	
	DBG2(DBG_MGR, "checkout IKE_SA by message");
	
	if (message->get_request(message) &&
		message->get_exchange_type(message) == IKE_SA_INIT)
	{
		/* IKE_SA_INIT request. Check for an IKE_SA with such a message hash. */
		chunk_t data, hash;
			
		data = message->get_packet_data(message);
		this->hasher->allocate_hash(this->hasher, data, &hash);
		chunk_free(&data);
		
		if (get_entry_by_hash(this, id, hash, &entry, &segment) == SUCCESS)
		{
			if (entry->message_id == 0)
			{
				unlock_single_segment(this, segment);
				chunk_free(&hash);
				id->destroy(id);
				DBG1(DBG_MGR, "ignoring IKE_SA_INIT, already processing");
				return NULL;
			}
			else if (wait_for_entry(this, entry, segment))
			{
				DBG2(DBG_MGR, "IKE_SA checked out by hash");
				entry->checked_out = TRUE;
				entry->message_id = message->get_message_id(message);
				ike_sa = entry->ike_sa;
			}
			unlock_single_segment(this, segment);
		}
		
		if (ike_sa == NULL)
		{
			if (id->get_responder_spi(id) == 0 &&
				message->get_exchange_type(message) == IKE_SA_INIT)
			{
				/* no IKE_SA found, create a new one */
				id->set_responder_spi(id, get_next_spi(this));
				entry = entry_create();
				entry->ike_sa = ike_sa_create(id);
				entry->ike_sa_id = id->clone(id);
				
				segment = put_entry(this, entry);
				entry->checked_out = TRUE;
				unlock_single_segment(this, segment);
				
				entry->message_id = message->get_message_id(message);				
				entry->init_hash = hash;
				ike_sa = entry->ike_sa;
				
				DBG2(DBG_MGR, "created IKE_SA");
			}
			else
			{
				chunk_free(&hash);
				DBG1(DBG_MGR, "ignoring message, no such IKE_SA");
			}
		}
		else
		{
			chunk_free(&hash);
		}
		id->destroy(id);
		charon->bus->set_sa(charon->bus, ike_sa);
		return ike_sa;
	}
	
	if (get_entry_by_id(this, id, &entry, &segment) == SUCCESS)
	{
		/* only check out if we are not processing this request */
		if (message->get_request(message) &&
			message->get_message_id(message) == entry->message_id)
		{
			DBG1(DBG_MGR, "ignoring request with ID %d, already processing",
				 entry->message_id);
		}
		else if (wait_for_entry(this, entry, segment))
		{
			ike_sa_id_t *ike_id = entry->ike_sa->get_id(entry->ike_sa);
			DBG2(DBG_MGR, "IKE_SA successfully checked out");
			entry->checked_out = TRUE;
			entry->message_id = message->get_message_id(message);
			if (ike_id->get_responder_spi(ike_id) == 0)
			{
				ike_id->set_responder_spi(ike_id, id->get_responder_spi(id));
			}
			ike_sa = entry->ike_sa;
		}
		unlock_single_segment(this, segment);
	}
	id->destroy(id);
	charon->bus->set_sa(charon->bus, ike_sa);
	return ike_sa;
}

/**
 * Implementation of of ike_sa_manager.checkout_by_config.
 */
static ike_sa_t* checkout_by_config(private_ike_sa_manager_t *this,
									peer_cfg_t *peer_cfg)
{
	enumerator_t *enumerator;
	entry_t *entry;
	ike_sa_t *ike_sa = NULL;
	peer_cfg_t *current_cfg;
	u_int segment;
	
	if (!this->reuse_ikesa)
	{	/* IKE_SA reuse disable by config */
		ike_sa = checkout_new(this, TRUE);	
		charon->bus->set_sa(charon->bus, ike_sa);
		return ike_sa;
	}
	
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		if (!wait_for_entry(this, entry, segment))
		{
			continue;
		}
		if (entry->ike_sa->get_state(entry->ike_sa) == IKE_DELETING)
		{	/* skip IKE_SAs which are not usable */
			continue;
		}
		
		current_cfg = entry->ike_sa->get_peer_cfg(entry->ike_sa);
		if (current_cfg && current_cfg->equals(current_cfg, peer_cfg))
		{
			DBG2(DBG_MGR, "found an existing IKE_SA with a '%s' config",
				 current_cfg->get_name(current_cfg));
			entry->checked_out = TRUE;
			ike_sa = entry->ike_sa;
			break;
		}
	}
	enumerator->destroy(enumerator);
	
	if (!ike_sa)
	{	/* no IKE_SA using such a config, hand out a new */
		ike_sa = checkout_new(this, TRUE);	
	}
	charon->bus->set_sa(charon->bus, ike_sa);
	return ike_sa;
}

/**
 * Implementation of of ike_sa_manager.checkout_by_id.
 */
static ike_sa_t* checkout_by_id(private_ike_sa_manager_t *this, u_int32_t id,
								bool child)
{
	enumerator_t *enumerator;
	iterator_t *children;
	entry_t *entry;
	ike_sa_t *ike_sa = NULL;
	child_sa_t *child_sa;
	u_int segment;
	
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		if (wait_for_entry(this, entry, segment))
		{
			/* look for a child with such a reqid ... */
			if (child)
			{
				children = entry->ike_sa->create_child_sa_iterator(entry->ike_sa);
				while (children->iterate(children, (void**)&child_sa))
				{
					if (child_sa->get_reqid(child_sa) == id)
					{
						ike_sa = entry->ike_sa;
						break;
					}		
				}
				children->destroy(children);
			}
			else /* ... or for a IKE_SA with such a unique id */
			{
				if (entry->ike_sa->get_unique_id(entry->ike_sa) == id)
				{
					ike_sa = entry->ike_sa;
				}
			}
			/* got one, return */
			if (ike_sa)
			{
				entry->checked_out = TRUE;
				break;
			}
		}
	}
	enumerator->destroy(enumerator);
	
	charon->bus->set_sa(charon->bus, ike_sa);
	return ike_sa;
}

/**
 * Implementation of of ike_sa_manager.checkout_by_name.
 */
static ike_sa_t* checkout_by_name(private_ike_sa_manager_t *this, char *name,
								  bool child)
{
	enumerator_t *enumerator;
	iterator_t *children;
	entry_t *entry;
	ike_sa_t *ike_sa = NULL;
	child_sa_t *child_sa;
	u_int segment;
	
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		if (wait_for_entry(this, entry, segment))
		{
			/* look for a child with such a policy name ... */
			if (child)
			{
				children = entry->ike_sa->create_child_sa_iterator(entry->ike_sa);
				while (children->iterate(children, (void**)&child_sa))
				{
					if (streq(child_sa->get_name(child_sa), name))
					{
						ike_sa = entry->ike_sa;
						break;
					}		
				}
				children->destroy(children);
			}
			else /* ... or for a IKE_SA with such a connection name */
			{
				if (streq(entry->ike_sa->get_name(entry->ike_sa), name))
				{
					ike_sa = entry->ike_sa;
				}
			}
			/* got one, return */
			if (ike_sa)
			{
				entry->checked_out = TRUE;
				break;
			}
		}
	}
	enumerator->destroy(enumerator);
	
	charon->bus->set_sa(charon->bus, ike_sa);
	return ike_sa;
}

/**
 * enumerator filter function 
 */
static bool enumerator_filter(private_ike_sa_manager_t *this,
							  entry_t **in, ike_sa_t **out, u_int *segment)
{
	if (wait_for_entry(this, *in, *segment))
	{
		*out = (*in)->ike_sa;
		return TRUE;
	}
	return FALSE;
}

/**
 * Implementation of ike_sa_manager_t.create_enumerator.
 */
static enumerator_t *create_enumerator(private_ike_sa_manager_t* this)
{
	return enumerator_create_filter(
						create_table_enumerator(this),
						(void*)enumerator_filter, this, NULL);
}

/**
 * Implementation of ike_sa_manager_t.checkin.
 */
static void checkin(private_ike_sa_manager_t *this, ike_sa_t *ike_sa)
{
	/* to check the SA back in, we look for the pointer of the ike_sa
	 * in all entries.
	 * The lookup is done by initiator SPI, so even if the SPI has changed (e.g.
	 * on reception of a IKE_SA_INIT response) the lookup will work but
	 * updating of the SPI MAY be necessary...
	 */
	entry_t *entry;
	ike_sa_id_t *ike_sa_id;
	host_t *other;
	identification_t *my_id, *other_id;
	u_int segment;
	
	ike_sa_id = ike_sa->get_id(ike_sa);
	my_id = ike_sa->get_my_id(ike_sa);
	other_id = ike_sa->get_other_id(ike_sa);
	other = ike_sa->get_other_host(ike_sa);
	
	DBG2(DBG_MGR, "checkin IKE_SA");
	
	/* look for the entry */
	if (get_entry_by_sa(this, ike_sa_id, ike_sa, &entry, &segment) == SUCCESS)
	{
		/* ike_sa_id must be updated */
		entry->ike_sa_id->replace_values(entry->ike_sa_id, ike_sa->get_id(ike_sa));
		/* signal waiting threads */
		entry->checked_out = FALSE;
		entry->message_id = -1;
		/* check if this SA is half-open */
		if (entry->half_open && ike_sa->get_state(ike_sa) != IKE_CONNECTING)
		{
			/* not half open anymore */
			entry->half_open = FALSE;
			remove_half_open(this, entry);
		}
		else if (entry->half_open && !other->ip_equals(other, entry->other))
		{
			/* the other host's IP has changed, we must update the hash table */
			remove_half_open(this, entry);
			DESTROY_IF(entry->other);
			entry->other = other->clone(other);
			put_half_open(this, entry);
		}
		else if (!entry->half_open &&
				 !entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
				 ike_sa->get_state(ike_sa) == IKE_CONNECTING)
		{
			/* this is a new half-open SA */
			entry->half_open = TRUE;
			entry->other = other->clone(other);
			put_half_open(this, entry);
		}
		DBG2(DBG_MGR, "check-in of IKE_SA successful.");
		entry->condvar->signal(entry->condvar);
	}
	else
	{
		entry = entry_create();
		entry->ike_sa_id = ike_sa_id->clone(ike_sa_id);
		entry->ike_sa = ike_sa;
		segment = put_entry(this, entry);
	}
	
	/* apply identities for duplicate test (only as responder) */
	if (!entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
		ike_sa->get_state(ike_sa) == IKE_ESTABLISHED &&
		entry->my_id == NULL && entry->other_id == NULL)
	{
		entry->my_id = my_id->clone(my_id);
		entry->other_id = other_id->clone(other_id);
		put_connected_peers(this, entry);
	}
	
	unlock_single_segment(this, segment);
	
	charon->bus->set_sa(charon->bus, NULL);
}

/**
 * Implementation of ike_sa_manager_t.checkin_and_destroy.
 */
static void checkin_and_destroy(private_ike_sa_manager_t *this, ike_sa_t *ike_sa)
{
	/* deletion is a bit complex, we must ensure that no thread is waiting for
	 * this SA.
	 * We take this SA from the table, and start signaling while threads
	 * are in the condvar.
	 */
	entry_t *entry;
	ike_sa_id_t *ike_sa_id;
	u_int segment;
	
	ike_sa_id = ike_sa->get_id(ike_sa);
	
	DBG2(DBG_MGR, "checkin and destroy IKE_SA");
	
	if (get_entry_by_sa(this, ike_sa_id, ike_sa, &entry, &segment) == SUCCESS)
	{
		/* drive out waiting threads, as we are in hurry */
		entry->driveout_waiting_threads = TRUE;
		/* mark it, so no new threads can get this entry */
		entry->driveout_new_threads = TRUE;
		/* wait until all workers have done their work */
		while (entry->waiting_threads)
		{
			/* wake up all */
			entry->condvar->broadcast(entry->condvar);
			/* they will wake us again when their work is done */
			entry->condvar->wait(entry->condvar, this->segments[segment].mutex);
		}
		remove_entry(this, entry);
		unlock_single_segment(this, segment);
		
		if (entry->half_open)
		{
			remove_half_open(this, entry);
		}
		if (!entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
			entry->my_id && entry->other_id)
		{
			remove_connected_peers(this, entry);
		}
		
		entry_destroy(entry);
		
		DBG2(DBG_MGR, "check-in and destroy of IKE_SA successful");
	}
	else
	{
		DBG1(DBG_MGR, "tried to check-in and delete nonexisting IKE_SA");
		ike_sa->destroy(ike_sa);
	}
	charon->bus->set_sa(charon->bus, NULL);
}

	
/**
 * Implementation of ike_sa_manager_t.check_uniqueness.
 */
static bool check_uniqueness(private_ike_sa_manager_t *this, ike_sa_t *ike_sa)
{
	bool cancel = FALSE;
	peer_cfg_t *peer_cfg;
	unique_policy_t policy;
	linked_list_t *list, *duplicate_ids = NULL;
	enumerator_t *enumerator;
	ike_sa_id_t *duplicate_id = NULL;
	identification_t *me, *other;
	u_int row, segment;
	rwlock_t *lock;
	
	peer_cfg = ike_sa->get_peer_cfg(ike_sa);
	policy = peer_cfg->get_unique_policy(peer_cfg);
	if (policy == UNIQUE_NO)
	{
		return FALSE;
	}
	
	me = ike_sa->get_my_id(ike_sa);
	other = ike_sa->get_other_id(ike_sa);
	
	row = chunk_hash_inc(other->get_encoding(other),
						 chunk_hash(me->get_encoding(me))) & this->table_mask;
	segment = row & this->segment_mask;
	
	lock = this->connected_peers_segments[segment & this->segment_mask].lock;
	lock->read_lock(lock);
	if ((list = this->connected_peers_table[row]) != NULL)
	{
		connected_peers_t *current;
		
		if (list->find_first(list, (linked_list_match_t)connected_peers_match,
							 (void**)&current, me, other) == SUCCESS)
		{
			/* clone the list, so we can release the lock */
			duplicate_ids = current->sas->clone_offset(current->sas,
												offsetof(ike_sa_id_t, clone));
		}
	}
	lock->unlock(lock);
	
	if (!duplicate_ids)
	{
		return FALSE;
	}
	
	enumerator = duplicate_ids->create_enumerator(duplicate_ids);
	while (enumerator->enumerate(enumerator, &duplicate_id))
	{
		status_t status = SUCCESS;
		ike_sa_t *duplicate;
		
		duplicate = checkout(this, duplicate_id);
		if (!duplicate)
		{
			continue;
		}
		peer_cfg = duplicate->get_peer_cfg(duplicate);
		if (peer_cfg && peer_cfg->equals(peer_cfg, ike_sa->get_peer_cfg(ike_sa)))
		{
			switch (duplicate->get_state(duplicate))
			{
				case IKE_ESTABLISHED:
				case IKE_REKEYING:
					switch (policy)
					{
						case UNIQUE_REPLACE:
							DBG1(DBG_IKE, "deleting duplicate IKE_SA for peer "
									"'%Y' due to uniqueness policy", other);
							status = duplicate->delete(duplicate);
							break;
						case UNIQUE_KEEP:
							cancel = TRUE;
							/* we keep the first IKE_SA and delete all
							 * other duplicates that might exist */
							policy = UNIQUE_REPLACE;
							break;
						default:
							break;
					}
					break;
				default:
					break;
			}
		}
		if (status == DESTROY_ME)
		{
			checkin_and_destroy(this, duplicate);
		}
		else
		{
			checkin(this, duplicate);
		}
	}
	enumerator->destroy(enumerator);
	duplicate_ids->destroy_offset(duplicate_ids, offsetof(ike_sa_id_t, destroy));
	/* reset thread's current IKE_SA after checkin */
	charon->bus->set_sa(charon->bus, ike_sa);
	return cancel;
}

/**
 * Implementation of ike_sa_manager_t.get_half_open_count.
 */
static int get_half_open_count(private_ike_sa_manager_t *this, host_t *ip)
{
	int count = 0;

	if (ip)
	{
		linked_list_t *list;
		chunk_t addr = ip->get_address(ip);
		u_int row = chunk_hash(addr) & this->table_mask;
		u_int segment = row & this->segment_mask;
		
		rwlock_t *lock = this->half_open_segments[segment & this->segment_mask].lock;
		lock->read_lock(lock);
		if ((list = this->half_open_table[row]) != NULL)
		{
			half_open_t *current;
			
			if (list->find_first(list, (linked_list_match_t)half_open_match,
								 (void**)&current, &addr) == SUCCESS)
			{
				count = current->count;
			}
		}
		lock->unlock(lock);
	}
	else
	{
		u_int segment;
		
		for (segment = 0; segment < this->segment_count; ++segment)
		{
			rwlock_t *lock;
			lock = this->half_open_segments[segment & this->segment_mask].lock;
			lock->read_lock(lock);
			count += this->half_open_segments[segment].count;
			lock->unlock(lock);
		}
	}
	
	return count;
}

/**
 * Implementation of ike_sa_manager_t.flush.
 */
static void flush(private_ike_sa_manager_t *this)
{
	/* destroy all list entries */
	enumerator_t *enumerator;
	entry_t *entry;
	u_int segment;
	
	lock_all_segments(this);
	DBG2(DBG_MGR, "going to destroy IKE_SA manager and all managed IKE_SA's");
	/* Step 1: drive out all waiting threads  */
	DBG2(DBG_MGR, "set driveout flags for all stored IKE_SA's");
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		/* do not accept new threads, drive out waiting threads */
		entry->driveout_new_threads = TRUE;
		entry->driveout_waiting_threads = TRUE;	
	}
	enumerator->destroy(enumerator);
	DBG2(DBG_MGR, "wait for all threads to leave IKE_SA's");
	/* Step 2: wait until all are gone */
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		while (entry->waiting_threads || entry->checked_out)
		{
			/* wake up all */
			entry->condvar->broadcast(entry->condvar);
			/* go sleeping until they are gone */
			entry->condvar->wait(entry->condvar, this->segments[segment].mutex);
		}
	}
	enumerator->destroy(enumerator);
	DBG2(DBG_MGR, "delete all IKE_SA's");
	/* Step 3: initiate deletion of all IKE_SAs */
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		charon->bus->set_sa(charon->bus, entry->ike_sa);
		entry->ike_sa->delete(entry->ike_sa);
	}
	enumerator->destroy(enumerator);
	
	DBG2(DBG_MGR, "destroy all entries");
	/* Step 4: destroy all entries */
	enumerator = create_table_enumerator(this);
	while (enumerator->enumerate(enumerator, &entry, &segment))
	{
		charon->bus->set_sa(charon->bus, entry->ike_sa);
		if (entry->half_open)
		{
			remove_half_open(this, entry);
		}
		if (!entry->ike_sa_id->is_initiator(entry->ike_sa_id) &&
			entry->my_id && entry->other_id)
		{
			remove_connected_peers(this, entry);
		}
		remove_entry_at((private_enumerator_t*)enumerator);
		entry_destroy(entry);
	}
	enumerator->destroy(enumerator);
	charon->bus->set_sa(charon->bus, NULL);
	unlock_all_segments(this);
}

/**
 * Implementation of ike_sa_manager_t.destroy.
 */
static void destroy(private_ike_sa_manager_t *this)
{
	u_int i;

	for (i = 0; i < this->table_size; ++i)
	{
		linked_list_t *list;

		if ((list = this->ike_sa_table[i]) != NULL)
		{
			list->destroy(list);
		}
		if ((list = this->half_open_table[i]) != NULL)
		{
			list->destroy(list);
		}
		if ((list = this->connected_peers_table[i]) != NULL)
		{
			list->destroy(list);
		}
	}
	free(this->ike_sa_table);
	free(this->half_open_table);
	free(this->connected_peers_table);
	for (i = 0; i < this->segment_count; ++i)
	{
		this->segments[i].mutex->destroy(this->segments[i].mutex);
		this->half_open_segments[i].lock->destroy(this->half_open_segments[i].lock);
		this->connected_peers_segments[i].lock->destroy(this->connected_peers_segments[i].lock);
	}
	free(this->segments);
	free(this->half_open_segments);
	free(this->connected_peers_segments);
	
	this->rng->destroy(this->rng);
	this->hasher->destroy(this->hasher);
	free(this);
}

/**
 * This function returns the next-highest power of two for the given number.
 * The algorithm works by setting all bits on the right-hand side of the most
 * significant 1 to 1 and then increments the whole number so it rolls over
 * to the nearest power of two. Note: returns 0 for n == 0
 */
static u_int get_nearest_powerof2(u_int n)
{
	u_int i;
	
	--n;
	for (i = 1; i < sizeof(u_int) * 8; i <<= 1)
	{
		n |= n >> i;
	}
	return ++n;
}

/*
 * Described in header.
 */
ike_sa_manager_t *ike_sa_manager_create()
{
	u_int i;
	private_ike_sa_manager_t *this = malloc_thing(private_ike_sa_manager_t);

	/* assign public functions */
	this->public.flush = (void(*)(ike_sa_manager_t*))flush;
	this->public.destroy = (void(*)(ike_sa_manager_t*))destroy;
	this->public.checkout = (ike_sa_t*(*)(ike_sa_manager_t*, ike_sa_id_t*))checkout;
	this->public.checkout_new = (ike_sa_t*(*)(ike_sa_manager_t*,bool))checkout_new;
	this->public.checkout_by_message = (ike_sa_t*(*)(ike_sa_manager_t*,message_t*))checkout_by_message;
	this->public.checkout_by_config = (ike_sa_t*(*)(ike_sa_manager_t*,peer_cfg_t*))checkout_by_config;
	this->public.checkout_by_id = (ike_sa_t*(*)(ike_sa_manager_t*,u_int32_t,bool))checkout_by_id;
	this->public.checkout_by_name = (ike_sa_t*(*)(ike_sa_manager_t*,char*,bool))checkout_by_name;
	this->public.check_uniqueness = (bool(*)(ike_sa_manager_t*, ike_sa_t *ike_sa))check_uniqueness;
	this->public.create_enumerator = (enumerator_t*(*)(ike_sa_manager_t*))create_enumerator;
	this->public.checkin = (void(*)(ike_sa_manager_t*,ike_sa_t*))checkin;
	this->public.checkin_and_destroy = (void(*)(ike_sa_manager_t*,ike_sa_t*))checkin_and_destroy;
	this->public.get_half_open_count = (int(*)(ike_sa_manager_t*,host_t*))get_half_open_count;
	
	/* initialize private variables */
	this->hasher = lib->crypto->create_hasher(lib->crypto, HASH_PREFERRED);
	if (this->hasher == NULL)
	{
		DBG1(DBG_MGR, "manager initialization failed, no hasher supported");
		free(this);
		return NULL;
	}
	this->rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
	if (this->rng == NULL)
	{
		DBG1(DBG_MGR, "manager initialization failed, no RNG supported");
		this->hasher->destroy(this->hasher);
		free(this);
		return NULL;
	}
	this->table_size = get_nearest_powerof2(lib->settings->get_int(lib->settings,
						"charon.ikesa_table_size", DEFAULT_HASHTABLE_SIZE));
	this->table_size = max(1, min(this->table_size, MAX_HASHTABLE_SIZE));
	this->table_mask = this->table_size - 1;
	
	this->segment_count = get_nearest_powerof2(lib->settings->get_int(lib->settings,
						"charon.ikesa_table_segments", DEFAULT_SEGMENT_COUNT));
	this->segment_count = max(1, min(this->segment_count, this->table_size));
	this->segment_mask = this->segment_count - 1;
	
	this->ike_sa_table = calloc(this->table_size, sizeof(linked_list_t*));
	
	this->segments = (segment_t*)calloc(this->segment_count, sizeof(segment_t));
	for (i = 0; i < this->segment_count; ++i)
	{
		this->segments[i].mutex = mutex_create(MUTEX_RECURSIVE);
		this->segments[i].count = 0;
	}
	
	/* we use the same table parameters for the table to track half-open SAs */
	this->half_open_table = calloc(this->table_size, sizeof(linked_list_t*));
	this->half_open_segments = calloc(this->segment_count, sizeof(shareable_segment_t));
	for (i = 0; i < this->segment_count; ++i)
	{
		this->half_open_segments[i].lock = rwlock_create(RWLOCK_DEFAULT);
		this->half_open_segments[i].count = 0;
	}
	
	/* also for the hash table used for duplicate tests */
	this->connected_peers_table = calloc(this->table_size, sizeof(linked_list_t*));
	this->connected_peers_segments = calloc(this->segment_count, sizeof(shareable_segment_t));
	for (i = 0; i < this->segment_count; ++i)
	{
		this->connected_peers_segments[i].lock = rwlock_create(RWLOCK_DEFAULT);
		this->connected_peers_segments[i].count = 0;
	}
	
	this->reuse_ikesa = lib->settings->get_bool(lib->settings,
												"charon.reuse_ikesa", TRUE);
	return &this->public;
}