summaryrefslogtreecommitdiff
path: root/src/charon/kernel/kernel_interface.c
blob: 4770c75382482b83b8aadac51af59328bf0c34cb (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
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
/**
 * @file kernel_interface.c
 *
 * @brief Implementation of kernel_interface_t.
 *
 */

/*
 * Copyright (C) 2005-2007 Martin Willi
 * Copyright (C) 2006-2007 Tobias Brunner
 * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser
 * Copyright (C) 2006 Daniel Roethlisberger
 * Copyright (C) 2005 Jan Hutter
 * Hochschule fuer Technik Rapperswil
 * Copyright (C) 2003 Herbert Xu.
 * 
 * Based on xfrm code from pluto.
 *
 * 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.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/xfrm.h>
#include <linux/udp.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>

#include "kernel_interface.h"

#include <daemon.h>
#include <utils/linked_list.h>
#include <processing/jobs/delete_child_sa_job.h>
#include <processing/jobs/rekey_child_sa_job.h>
#include <processing/jobs/acquire_job.h>
#include <processing/jobs/callback_job.h>
#include <processing/jobs/roam_job.h>

/** kernel level protocol identifiers */
#define KERNEL_ESP 50
#define KERNEL_AH 51

/** default priority of installed policies */
#define PRIO_LOW 3000
#define PRIO_HIGH 2000

#define BUFFER_SIZE 1024

/**
 * returns a pointer to the first rtattr following the nlmsghdr *nlh and the 
 * 'usual' netlink data x like 'struct xfrm_usersa_info' 
 */
#define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + NLMSG_ALIGN(sizeof(x))))
/**
 * returns a pointer to the next rtattr following rta.
 * !!! do not use this to parse messages. use RTA_NEXT and RTA_OK instead !!!
 */
#define XFRM_RTA_NEXT(rta) ((struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len)))
/**
 * returns the total size of attached rta data 
 * (after 'usual' netlink data x like 'struct xfrm_usersa_info') 
 */
#define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x))

typedef struct kernel_algorithm_t kernel_algorithm_t;

/**
 * Mapping from the algorithms defined in IKEv2 to
 * kernel level algorithm names and their key length
 */
struct kernel_algorithm_t {
	/**
	 * Identifier specified in IKEv2
	 */
	int ikev2_id;
	
	/**
	 * Name of the algorithm, as used as kernel identifier
	 */
	char *name;
	
	/**
	 * Key length in bits, if fixed size
	 */
	u_int key_size;
};
#define END_OF_LIST -1

/**
 * Algorithms for encryption
 */
kernel_algorithm_t encryption_algs[] = {
/*	{ENCR_DES_IV64, 	"***", 			0}, */
	{ENCR_DES, 			"des", 			64},
	{ENCR_3DES, 		"des3_ede",		192},
/*	{ENCR_RC5, 			"***", 			0}, */
/*	{ENCR_IDEA, 		"***",			0}, */
	{ENCR_CAST, 		"cast128",		0},
	{ENCR_BLOWFISH, 	"blowfish",		0},
/*	{ENCR_3IDEA, 		"***",			0}, */
/*	{ENCR_DES_IV32, 	"***",			0}, */
	{ENCR_NULL, 		"cipher_null",	0},
	{ENCR_AES_CBC, 		"aes",			0},
/*	{ENCR_AES_CTR, 		"***",			0}, */
	{END_OF_LIST, 		NULL,			0},
};

/**
 * Algorithms for integrity protection
 */
kernel_algorithm_t integrity_algs[] = {
	{AUTH_HMAC_MD5_96, 			"md5",			128},
	{AUTH_HMAC_SHA1_96,			"sha1",			160},
	{AUTH_HMAC_SHA2_256_128,	"sha256",		256},
	{AUTH_HMAC_SHA2_384_192,	"sha384",		384},
	{AUTH_HMAC_SHA2_512_256,	"sha512",		512},
/*	{AUTH_DES_MAC,				"***",			0}, */
/*	{AUTH_KPDK_MD5,				"***",			0}, */
	{AUTH_AES_XCBC_96,			"xcbc(aes)",	128},
	{END_OF_LIST, 				NULL,			0},
};

/**
 * Look up a kernel algorithm name and its key size
 */
char* lookup_algorithm(kernel_algorithm_t *kernel_algo, 
					   algorithm_t *ikev2_algo, u_int *key_size)
{
	while (kernel_algo->ikev2_id != END_OF_LIST)
	{
		if (ikev2_algo->algorithm == kernel_algo->ikev2_id)
		{
			/* match, evaluate key length */
			if (ikev2_algo->key_size)
			{	/* variable length */
				*key_size = ikev2_algo->key_size;
			}
			else
			{	/* fixed length */
				*key_size = kernel_algo->key_size;
			}
			return kernel_algo->name;
		}
		kernel_algo++;
	}
	return NULL;
}

typedef struct route_entry_t route_entry_t;

/**
 * installed routing entry
 */
struct route_entry_t {

	/** Index of the interface the route is bound to */
	int if_index;

	/** Source ip of the route */
	host_t *src_ip;
	
	/** gateway for this route */
	host_t *gateway;

	/** Destination net */
	chunk_t dst_net;

	/** Destination net prefixlen */
	u_int8_t prefixlen;
};

/**
 * destroy an route_entry_t object
 */
static void route_entry_destroy(route_entry_t *this)
{
	this->src_ip->destroy(this->src_ip);
	this->gateway->destroy(this->gateway);
	chunk_free(&this->dst_net);
	free(this);
}

typedef struct policy_entry_t policy_entry_t;

/**
 * installed kernel policy.
 */
struct policy_entry_t {
	
	/** direction of this policy: in, out, forward */
	u_int8_t direction;
	
	/** reqid of the policy */
	u_int32_t reqid;
	
	/** parameters of installed policy */
	struct xfrm_selector sel;
	
	/** associated route installed for this policy */
	route_entry_t *route;
	
	/** by how many CHILD_SA's this policy is used */
	u_int refcount;
};

typedef struct addr_entry_t addr_entry_t;

/**
 * IP address in an inface_entry_t
 */
struct addr_entry_t {
	
	/** The ip address */
	host_t *ip;
	
	/** virtual IP managed by us */
	bool virtual;
	
	/** scope of the address */
	u_char scope;
	
	/** Number of times this IP is used, if virtual */
	u_int refcount;
};

/**
 * destroy a addr_entry_t object
 */
static void addr_entry_destroy(addr_entry_t *this)
{
	this->ip->destroy(this->ip);
	free(this);
}

typedef struct iface_entry_t iface_entry_t;

/**
 * A network interface on this system, containing addr_entry_t's
 */
struct iface_entry_t {
	
	/** interface index */
	int ifindex;
	
	/** name of the interface */
	char ifname[IFNAMSIZ];
	
	/** interface flags, as in netdevice(7) SIOCGIFFLAGS */
	u_int flags;
	
	/** list of addresses as host_t */
	linked_list_t *addrs;
};

/**
 * destroy an interface entry
 */
static void iface_entry_destroy(iface_entry_t *this)
{
	this->addrs->destroy_function(this->addrs, (void*)addr_entry_destroy);
	free(this);
}

typedef struct private_kernel_interface_t private_kernel_interface_t;

/**
 * Private variables and functions of kernel_interface class.
 */
struct private_kernel_interface_t {
	/**
	 * Public part of the kernel_interface_t object.
	 */
	kernel_interface_t public;
	
	/**
	 * mutex to lock access to the various lists
	 */
	pthread_mutex_t mutex;
	
	/**
	 * List of installed policies (policy_entry_t)
	 */
	linked_list_t *policies;
	
	/**
	 * Cached list of interfaces and its adresses (iface_entry_t)
	 */
	linked_list_t *ifaces;
	
	/**
	 * iterator used in hook()
	 */
	iterator_t *hiter;
	 
	/**
	 * job receiving netlink events
	 */
	callback_job_t *job;
	
	/**
	 * current sequence number for netlink request
	 */
	int seq;
	
	/**
	 * Netlink xfrm socket (IPsec)
	 */
	int socket_xfrm;
	
	/**
	 * netlink xfrm socket to receive acquire and expire events
	 */
	int socket_xfrm_events;
	
	/**
	 * Netlink rt socket (routing)
	 */
	int socket_rt;
	
	/**
	 * Netlink rt socket to receive address change events
	 */
	int socket_rt_events;
};

/**
 * convert a host_t to a struct xfrm_address
 */
static void host2xfrm(host_t *host, xfrm_address_t *xfrm)
{
	chunk_t chunk = host->get_address(host);
	memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t)));	
}

/**
 * convert a traffic selector address range to subnet and its mask.
 */
static void ts2subnet(traffic_selector_t* ts, 
					  xfrm_address_t *net, u_int8_t *mask)
{
	/* there is no way to do this cleanly, as the address range may
	 * be anything else but a subnet. We use from_addr as subnet 
	 * and try to calculate a usable subnet mask.
	 */
	int byte, bit;
	bool found = FALSE;
	chunk_t from, to;
	size_t size = (ts->get_type(ts) == TS_IPV4_ADDR_RANGE) ? 4 : 16;
	
	from = ts->get_from_address(ts);
	to = ts->get_to_address(ts);
	
	*mask = (size * 8);
	/* go trough all bits of the addresses, beginning in the front.
	 * as long as they are equal, the subnet gets larger
	 */
	for (byte = 0; byte < size; byte++)
	{
		for (bit = 7; bit >= 0; bit--)
		{
			if ((1<<bit & from.ptr[byte]) != (1<<bit & to.ptr[byte]))
			{
				*mask = ((7 - bit) + (byte * 8));
				found = TRUE;
				break;
			}
		}
		if (found)
		{
			break;
		}
	}
	memcpy(net, from.ptr, from.len);
	chunk_free(&from);
	chunk_free(&to);
}

/**
 * convert a traffic selector port range to port/portmask
 */
static void ts2ports(traffic_selector_t* ts, 
					 u_int16_t *port, u_int16_t *mask)
{
	/* linux does not seem to accept complex portmasks. Only
	 * any or a specific port is allowed. We set to any, if we have
	 * a port range, or to a specific, if we have one port only.
	 */
	u_int16_t from, to;
	
	from = ts->get_from_port(ts);
	to = ts->get_to_port(ts);
	
	if (from == to)
	{
		*port = htons(from);
		*mask = ~0;
	}
	else
	{
		*port = 0;
		*mask = 0;
	}
}

/**
 * convert a pair of traffic_selectors to a xfrm_selector
 */
static struct xfrm_selector ts2selector(traffic_selector_t *src, 
										traffic_selector_t *dst)
{
	struct xfrm_selector sel;

	memset(&sel, 0, sizeof(sel));
	sel.family = src->get_type(src) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6;
	/* src or dest proto may be "any" (0), use more restrictive one */
	sel.proto = max(src->get_protocol(src), dst->get_protocol(dst));
	ts2subnet(dst, &sel.daddr, &sel.prefixlen_d);
	ts2subnet(src, &sel.saddr, &sel.prefixlen_s);
	ts2ports(dst, &sel.dport, &sel.dport_mask);
	ts2ports(src, &sel.sport, &sel.sport_mask);
	sel.ifindex = 0;
	sel.user = 0;
	
	return sel;
}

/**
 * Creates an rtattr and adds it to the netlink message
 */
static void add_attribute(struct nlmsghdr *hdr, int rta_type, chunk_t data,
						  size_t buflen)
{
	struct rtattr *rta;
	
	if (NLMSG_ALIGN(hdr->nlmsg_len) + RTA_ALIGN(data.len) > buflen)
	{
		DBG1(DBG_KNL, "unable to add attribute, buffer too small");
		return;
	}
	
	rta = (struct rtattr*)(((char*)hdr) + NLMSG_ALIGN(hdr->nlmsg_len));
	rta->rta_type = rta_type;
	rta->rta_len = RTA_LENGTH(data.len);
	memcpy(RTA_DATA(rta), data.ptr, data.len);
	hdr->nlmsg_len = NLMSG_ALIGN(hdr->nlmsg_len) + rta->rta_len;
}

/**
 * process a XFRM_MSG_ACQUIRE from kernel
 */
static void process_acquire(private_kernel_interface_t *this, struct nlmsghdr *hdr)
{
	u_int32_t reqid = 0;
	job_t *job;
	struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_user_acquire);
	size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_user_tmpl);
	
	if (RTA_OK(rtattr, rtsize))
	{
		if (rtattr->rta_type == XFRMA_TMPL)
		{
			struct xfrm_user_tmpl* tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rtattr);
			reqid = tmpl->reqid;
		}
	}
	if (reqid == 0)
	{
		DBG1(DBG_KNL, "received a XFRM_MSG_ACQUIRE, but no reqid found");
		return;
	}
	DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE");
	DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid %d", reqid);
	job = (job_t*)acquire_job_create(reqid);
	charon->processor->queue_job(charon->processor, job);
}

/**
 * process a XFRM_MSG_EXPIRE from kernel
 */
static void process_expire(private_kernel_interface_t *this, struct nlmsghdr *hdr)
{
	job_t *job;
	protocol_id_t protocol;
	u_int32_t spi, reqid;
	struct xfrm_user_expire *expire;
	
	expire = (struct xfrm_user_expire*)NLMSG_DATA(hdr);
	protocol = expire->state.id.proto == KERNEL_ESP ? PROTO_ESP : PROTO_AH;
	spi = expire->state.id.spi;
	reqid = expire->state.reqid;
	
	DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE");
	DBG1(DBG_KNL, "creating %s job for %N CHILD_SA 0x%x (reqid %d)",
		 expire->hard ? "delete" : "rekey",  protocol_id_names,
		 protocol, ntohl(spi), reqid);
	if (expire->hard)
	{
		job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
	}
	else
	{
		job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
	}
	charon->processor->queue_job(charon->processor, job);
}

/**
 * process RTM_NEWLINK/RTM_DELLINK from kernel
 */
static void process_link(private_kernel_interface_t *this,
						 struct nlmsghdr *hdr, bool event)
{
	struct ifinfomsg* msg = (struct ifinfomsg*)(NLMSG_DATA(hdr));
	struct rtattr *rta = IFLA_RTA(msg);
	size_t rtasize = IFLA_PAYLOAD (hdr);
	iterator_t *iterator;
	iface_entry_t *current, *entry = NULL;
	char *name = NULL;
	bool update = FALSE;
	
	while(RTA_OK(rta, rtasize))
	{
		switch (rta->rta_type)
		{
			case IFLA_IFNAME:
				name = RTA_DATA(rta);
				break;
		}
		rta = RTA_NEXT(rta, rtasize);
	}
	if (!name)
	{
		name = "(unknown)";
	}
	
	switch (hdr->nlmsg_type)
	{
		case RTM_NEWLINK:
		{
			if (msg->ifi_flags & IFF_LOOPBACK)
			{	/* ignore loopback interfaces */
				break;
			}
			iterator = this->ifaces->create_iterator_locked(this->ifaces,
															&this->mutex);
			while (iterator->iterate(iterator, (void**)&current))
			{
				if (current->ifindex == msg->ifi_index)
				{
					entry = current;
					break;
				}
			}
			if (!entry)
			{
				entry = malloc_thing(iface_entry_t);
				entry->ifindex = msg->ifi_index;
				entry->flags = 0;
				entry->addrs = linked_list_create();
				this->ifaces->insert_last(this->ifaces, entry);
			}
			memcpy(entry->ifname, name, IFNAMSIZ);
			entry->ifname[IFNAMSIZ-1] = '\0';
			if (event)
			{
				if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
				{
					update = TRUE;
					DBG1(DBG_KNL, "interface %s activated", name);
				}
				if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
				{
					update = TRUE;
					DBG1(DBG_KNL, "interface %s deactivated", name);
				}
			}
			entry->flags = msg->ifi_flags;
			iterator->destroy(iterator);
			break;
		}
		case RTM_DELLINK:
		{
			iterator = this->ifaces->create_iterator_locked(this->ifaces,
															&this->mutex);
			while (iterator->iterate(iterator, (void**)&current))
			{
				if (current->ifindex == msg->ifi_index)
				{
					/* we do not remove it, as an address may be added to a 
					 * "down" interface and we wan't to know that. */
					current->flags = msg->ifi_flags;
					break;
				}
			}
			iterator->destroy(iterator);
			break;
		}
	}
	
	/* send an update to all IKE_SAs */
	if (update && event)
	{
		charon->processor->queue_job(charon->processor,
									 (job_t*)roam_job_create(TRUE));
	}
}

/**
 * process RTM_NEWADDR/RTM_DELADDR from kernel
 */
static void process_addr(private_kernel_interface_t *this,
						 struct nlmsghdr *hdr, bool event)
{
	struct ifaddrmsg* msg = (struct ifaddrmsg*)(NLMSG_DATA(hdr));
	struct rtattr *rta = IFA_RTA(msg);
	size_t rtasize = IFA_PAYLOAD (hdr);
	host_t *host = NULL;
	iterator_t *ifaces, *addrs;
	iface_entry_t *iface;
	addr_entry_t *addr;
	chunk_t local = chunk_empty, address = chunk_empty;
	bool update = FALSE, found = FALSE, changed = FALSE;
	
	while(RTA_OK(rta, rtasize))
	{
		switch (rta->rta_type)
		{
			case IFA_LOCAL:
				local.ptr = RTA_DATA(rta);
				local.len = RTA_PAYLOAD(rta);
				break;
			case IFA_ADDRESS:
				address.ptr = RTA_DATA(rta);
				address.len = RTA_PAYLOAD(rta);
				break;
		}
		rta = RTA_NEXT(rta, rtasize);
	}
	
	/* For PPP interfaces, we need the IFA_LOCAL address,
	 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
	 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
	if (local.ptr)
	{
		host = host_create_from_chunk(msg->ifa_family, local, 0);
	}
	else if (address.ptr)
	{
		host = host_create_from_chunk(msg->ifa_family, address, 0);
	}
	
	if (host == NULL)
	{	/* bad family? */
		return;
	}
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		if (iface->ifindex == msg->ifa_index)
		{
			addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
			while (addrs->iterate(addrs, (void**)&addr))
			{
				if (host->ip_equals(host, addr->ip))
				{
					found = TRUE;
					if (hdr->nlmsg_type == RTM_DELADDR)
					{
						changed = TRUE;
						addrs->remove(addrs);
						addr_entry_destroy(addr);
						DBG1(DBG_KNL, "%H disappeared from %s", host, iface->ifname);
					}
				}
			}
			addrs->destroy(addrs);
		
			if (hdr->nlmsg_type == RTM_NEWADDR)
			{
				if (!found)
				{
					found = TRUE;
					changed = TRUE;
					addr = malloc_thing(addr_entry_t);
					addr->ip = host->clone(host);
					addr->virtual = FALSE;
					addr->refcount = 1;
					addr->scope = msg->ifa_scope;
					
					iface->addrs->insert_last(iface->addrs, addr);
					if (event)
					{
						DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
					}
				}
			}
			if (found && (iface->flags & IFF_UP))
			{
				update = TRUE;
			}
			break;
		}
	}
	ifaces->destroy(ifaces);
	host->destroy(host);
	
	/* send an update to all IKE_SAs */
	if (update && event && changed)
	{
		charon->processor->queue_job(charon->processor,
									 (job_t*)roam_job_create(TRUE));
	}
}

/**
 * Receives events from kernel
 */
static job_requeue_t receive_events(private_kernel_interface_t *this)
{
	char response[1024];
	struct nlmsghdr *hdr = (struct nlmsghdr*)response;
	struct sockaddr_nl addr;
	socklen_t addr_len = sizeof(addr);
	int len, oldstate, maxfd, selected;
	fd_set rfds;

	FD_ZERO(&rfds);
	FD_SET(this->socket_xfrm_events, &rfds);
	FD_SET(this->socket_rt_events, &rfds);
	maxfd = max(this->socket_xfrm_events, this->socket_rt_events);
	
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
	selected = select(maxfd + 1, &rfds, NULL, NULL, NULL);
	pthread_setcancelstate(oldstate, NULL);
	if (selected <= 0)
	{
		DBG1(DBG_KNL, "selecting on sockets failed: %s", strerror(errno));
		return JOB_REQUEUE_FAIR;
	}
	if (FD_ISSET(this->socket_xfrm_events, &rfds))
	{
		selected = this->socket_xfrm_events;
	}
	else if (FD_ISSET(this->socket_rt_events, &rfds))
	{
		selected = this->socket_rt_events;
	}
	else
	{
		return JOB_REQUEUE_DIRECT;
	}
	
	len = recvfrom(selected, response, sizeof(response), MSG_DONTWAIT,
				   (struct sockaddr*)&addr, &addr_len);
	if (len < 0)
	{
		switch (errno)
		{
			case EINTR:
				/* interrupted, try again */
				return JOB_REQUEUE_DIRECT;
			case EAGAIN:
				/* no data ready, select again */
				return JOB_REQUEUE_DIRECT;
			default:
				DBG1(DBG_KNL, "unable to receive from xfrm event socket");
				sleep(1);
				return JOB_REQUEUE_FAIR;
		}
	}
	if (addr.nl_pid != 0)
	{	/* not from kernel. not interested, try another one */
		return JOB_REQUEUE_DIRECT;
	}
	
	while (NLMSG_OK(hdr, len))
	{
		/* looks good so far, dispatch netlink message */
		if (selected == this->socket_xfrm_events)
		{
			switch (hdr->nlmsg_type)
			{
				case XFRM_MSG_ACQUIRE:
					process_acquire(this, hdr);
					break;
				case XFRM_MSG_EXPIRE:
					process_expire(this, hdr);
					break;
				default:
					break;
			}
		}
		else if (selected == this->socket_rt_events)
		{
			switch (hdr->nlmsg_type)
			{
				case RTM_NEWADDR:
				case RTM_DELADDR:
					process_addr(this, hdr, TRUE);
					break;
				case RTM_NEWLINK:
				case RTM_DELLINK:
					process_link(this, hdr, TRUE);
					break;
				case RTM_NEWROUTE:
				case RTM_DELROUTE:
					charon->processor->queue_job(charon->processor,
												 (job_t*)roam_job_create(FALSE));
					break;
				default:
					break;
			}
		}
		hdr = NLMSG_NEXT(hdr, len);
	}
	return JOB_REQUEUE_DIRECT;
}

/**
 * send a netlink message and wait for a reply
 */
static status_t netlink_send(private_kernel_interface_t *this,
							 int socket, struct nlmsghdr *in,
							 struct nlmsghdr **out, size_t *out_len)
{
	int len, addr_len;
	struct sockaddr_nl addr;
	chunk_t result = chunk_empty, tmp;
	struct nlmsghdr *msg, peek;
	
	pthread_mutex_lock(&this->mutex);
	
	in->nlmsg_seq = ++this->seq;
	in->nlmsg_pid = getpid();
	
	memset(&addr, 0, sizeof(addr));
	addr.nl_family = AF_NETLINK;
	addr.nl_pid = 0;
	addr.nl_groups = 0;

	while (TRUE)
	{
		len = sendto(socket, in, in->nlmsg_len, 0, 
					 (struct sockaddr*)&addr, sizeof(addr));
		
		if (len != in->nlmsg_len)
		{	
			if (errno == EINTR)
			{
				/* interrupted, try again */
				continue;
			}
			pthread_mutex_unlock(&this->mutex);
			DBG1(DBG_KNL, "error sending to netlink socket: %s", strerror(errno));
			return FAILED;
		}
		break;
	}
	
	while (TRUE)
	{	
		char buf[4096];
		tmp.len = sizeof(buf);
		tmp.ptr = buf;
		msg = (struct nlmsghdr*)tmp.ptr;
		
		memset(&addr, 0, sizeof(addr));
		addr.nl_family = AF_NETLINK;
		addr.nl_pid = getpid();
		addr.nl_groups = 0;
		addr_len = sizeof(addr);
		
		len = recvfrom(socket, tmp.ptr, tmp.len, 0,
					   (struct sockaddr*)&addr, &addr_len);
		
		if (len < 0)
		{
			if (errno == EINTR)
			{
				DBG1(DBG_KNL, "got interrupted");
				/* interrupted, try again */
				continue;
			}
			DBG1(DBG_KNL, "error reading from netlink socket: %s", strerror(errno));
			pthread_mutex_unlock(&this->mutex);
			return FAILED;
		}
		if (!NLMSG_OK(msg, len))
		{
			DBG1(DBG_KNL, "received corrupted netlink message");
			pthread_mutex_unlock(&this->mutex);
			return FAILED;
		}
		if (msg->nlmsg_seq != this->seq)
		{
			DBG1(DBG_KNL, "received invalid netlink sequence number");
			if (msg->nlmsg_seq < this->seq)
			{
				continue;
			}
			pthread_mutex_unlock(&this->mutex);
			return FAILED;
		}
		
		tmp.len = len;
		result = chunk_cata("cc", result, tmp);
		
		/* NLM_F_MULTI flag does not seem to be set correctly, we use sequence
		 * numbers to detect multi header messages */
		len = recvfrom(socket, &peek, sizeof(peek), MSG_PEEK | MSG_DONTWAIT,
					   (struct sockaddr*)&addr, &addr_len);
		
		if (len == sizeof(peek) && peek.nlmsg_seq == this->seq)
		{
			/* seems to be multipart */
			continue;
		}
		break;
	}
	
	*out_len = result.len;
	*out = (struct nlmsghdr*)clalloc(result.ptr, result.len);
	
	pthread_mutex_unlock(&this->mutex);
	
	return SUCCESS;
}

/**
 * send a netlink message and wait for its acknowlegde
 */
static status_t netlink_send_ack(private_kernel_interface_t *this,
								 int socket, struct nlmsghdr *in)
{
	struct nlmsghdr *out, *hdr;
	size_t len;

	if (netlink_send(this, socket, in, &out, &len) != SUCCESS)
	{
		return FAILED;
	}
	hdr = out;
	while (NLMSG_OK(hdr, len))
	{
		switch (hdr->nlmsg_type)
		{
			case NLMSG_ERROR:
			{
				struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(hdr);
				
				if (err->error)
				{
					DBG1(DBG_KNL, "received netlink error: %s (%d)",
						 strerror(-err->error), -err->error);
					free(out);
					return FAILED;
				}
				free(out);
				return SUCCESS;
			}
			default:
				hdr = NLMSG_NEXT(hdr, len);
				continue;
			case NLMSG_DONE:
				break;
		}
		break;
	}
	DBG1(DBG_KNL, "netlink request not acknowlegded");
	free(out);
	return FAILED;
}
	
/**
 * Initialize a list of local addresses.
 */
static status_t init_address_list(private_kernel_interface_t *this)
{
	char request[BUFFER_SIZE];
	struct nlmsghdr *out, *current, *in;
	struct rtgenmsg *msg;
	size_t len;
	iterator_t *ifaces, *addrs;
	iface_entry_t *iface;
	addr_entry_t *addr;
	
	DBG1(DBG_KNL, "listening on interfaces:");
	
	memset(&request, 0, sizeof(request));

	in = (struct nlmsghdr*)&request;
	in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
	in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
	msg = (struct rtgenmsg*)NLMSG_DATA(in);
	msg->rtgen_family = AF_UNSPEC;
	
	/* get all links */
	in->nlmsg_type = RTM_GETLINK;
	if (netlink_send(this, this->socket_rt, in, &out, &len) != SUCCESS)
	{
		return FAILED;
	}
	current = out;
	while (NLMSG_OK(current, len))
	{
		switch (current->nlmsg_type)
		{
			case NLMSG_DONE:
				break;
			case RTM_NEWLINK:
				process_link(this, current, FALSE);
				/* fall through */
			default:
				current = NLMSG_NEXT(current, len);
				continue;
		}
		break;
	}
	free(out);
	
	/* get all interface addresses */
	in->nlmsg_type = RTM_GETADDR;
	if (netlink_send(this, this->socket_rt, in, &out, &len) != SUCCESS)
	{
		return FAILED;
	}
	current = out;
	while (NLMSG_OK(current, len))
	{
		switch (current->nlmsg_type)
		{
			case NLMSG_DONE:
				break;
			case RTM_NEWADDR:
				process_addr(this, current, FALSE);
				/* fall through */
			default:
				current = NLMSG_NEXT(current, len);
				continue;
		}
		break;
	}
	free(out);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		if (iface->flags & IFF_UP)
		{
			DBG1(DBG_KNL, "  %s", iface->ifname);
			addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
			while (addrs->iterate(addrs, (void**)&addr))
			{
				DBG1(DBG_KNL, "    %H", addr->ip);
			}
			addrs->destroy(addrs);
		}
	}
	ifaces->destroy(ifaces);
	return SUCCESS;
}

/**
 * iterator hook to iterate over addrs
 */
static hook_result_t addr_hook(private_kernel_interface_t *this,
							   addr_entry_t *in, host_t **out)
{
	if (in->virtual)
	{	/* skip virtual interfaces added by us */
		return HOOK_SKIP;
	}
	if (in->scope >= RT_SCOPE_LINK)
	{	/* skip addresses with a unusable scope */
		return HOOK_SKIP;
	}
	*out = in->ip;
	return HOOK_NEXT;
}
								
/**
 * iterator hook to iterate over ifaces
 */
static hook_result_t iface_hook(private_kernel_interface_t *this,
								iface_entry_t *in, host_t **out)
{
	if (!(in->flags & IFF_UP))
	{	/* skip interfaces not up */
		return HOOK_SKIP;
	}

	if (this->hiter == NULL)
	{
		this->hiter = in->addrs->create_iterator(in->addrs, TRUE);
		this->hiter->set_iterator_hook(this->hiter,
									   (iterator_hook_t*)addr_hook, this);
	}
	while (this->hiter->iterate(this->hiter, (void**)out))
	{
		return HOOK_AGAIN;
	}
	this->hiter->destroy(this->hiter);
	this->hiter = NULL;
	return HOOK_SKIP;
}

/**
 * Implements kernel_interface_t.create_address_iterator.
 */
static iterator_t *create_address_iterator(private_kernel_interface_t *this)
{
	iterator_t *iterator;
	
	/* This iterator is not only hooked, is is double-hooked. As we have stored
	 * our addresses in iface_entry->addr_entry->ip, we need to iterate the
	 * entries in each interface we iterate. This does the iface_hook. The
	 * addr_hook returns the ip instead of the addr_entry. */
	
	iterator = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	iterator->set_iterator_hook(iterator, (iterator_hook_t*)iface_hook, this);
	return iterator;
}

/**
 * implementation of kernel_interface_t.get_interface_name
 */
static char *get_interface_name(private_kernel_interface_t *this, host_t* ip)
{
	iterator_t *ifaces, *addrs;
	iface_entry_t *iface;
	addr_entry_t *addr;
	char *name = NULL;
	
	DBG2(DBG_KNL, "getting interface name for %H", ip);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
		while (addrs->iterate(addrs, (void**)&addr))
		{
			if (ip->ip_equals(ip, addr->ip))
			{
				name = strdup(iface->ifname);
				break;
			}
		}
		addrs->destroy(addrs);
		if (name)
		{
			break;
		}
	}
	ifaces->destroy(ifaces);
	
	if (name)
	{
		DBG2(DBG_KNL, "%H is on interface %s", ip, name);
	}
	else
	{
		DBG2(DBG_KNL, "%H is not a local address", ip);
	}
	return name;
}

/**
 * Tries to find an ip address of a local interface that is included in the
 * supplied traffic selector.
 */
static status_t get_address_by_ts(private_kernel_interface_t *this,
								  traffic_selector_t *ts, host_t **ip)
{
	iterator_t *ifaces, *addrs;
	iface_entry_t *iface;
	addr_entry_t *addr;
	host_t *host;
	int family;
	bool found = FALSE;
	
	DBG2(DBG_KNL, "getting a local address in traffic selector %R", ts);
	
	/* if we have a family which includes localhost, we do not
	 * search for an IP, we use the default */
	family = ts->get_type(ts) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6;
	
	if (family == AF_INET)
	{
		host = host_create_from_string("127.0.0.1", 0);
	}
	else
	{
		host = host_create_from_string("::1", 0);
	}
	
	if (ts->includes(ts, host))
	{
		*ip = host_create_any(family);
		host->destroy(host);
		DBG2(DBG_KNL, "using host %H", *ip);
		return SUCCESS;
	}
	host->destroy(host);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces,	&this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
		while (addrs->iterate(addrs, (void**)&addr))
		{
			if (ts->includes(ts, addr->ip))
			{
				found = TRUE;
				*ip = addr->ip->clone(addr->ip);
				break;
			}
		}
		addrs->destroy(addrs);
		if (found)
		{
			break;
		}
	}
	ifaces->destroy(ifaces);
	
	if (!found)
	{
		DBG1(DBG_KNL, "no local address found in traffic selector %R", ts);
		return FAILED;
	}
	DBG2(DBG_KNL, "using host %H", *ip);
	return SUCCESS;
}

/**
 * get the interface of a local address
 */
static int get_interface_index(private_kernel_interface_t *this, host_t* ip)
{
	iterator_t *ifaces, *addrs;
	iface_entry_t *iface;
	addr_entry_t *addr;
	int ifindex = 0;
	
	DBG2(DBG_KNL, "getting iface for %H", ip);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces,	&this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
		while (addrs->iterate(addrs, (void**)&addr))
		{
			if (ip->ip_equals(ip, addr->ip))
			{
				ifindex = iface->ifindex;
				break;
			}
		}
		addrs->destroy(addrs);
		if (ifindex)
		{
			break;
		}
	}
	ifaces->destroy(ifaces);

	if (ifindex == 0)
	{
		DBG1(DBG_KNL, "unable to get interface for %H", ip);
	}
	return ifindex;
}

/**
 * Manages the creation and deletion of ip addresses on an interface.
 * By setting the appropriate nlmsg_type, the ip will be set or unset.
 */
static status_t manage_ipaddr(private_kernel_interface_t *this, int nlmsg_type,
							  int flags, int if_index, host_t *ip)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr;
	struct ifaddrmsg *msg;
	chunk_t chunk;
	
	memset(&request, 0, sizeof(request));
	
	chunk = ip->get_address(ip);
    
    hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
	hdr->nlmsg_type = nlmsg_type; 
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
	
	msg = (struct ifaddrmsg*)NLMSG_DATA(hdr);
    msg->ifa_family = ip->get_family(ip);
    msg->ifa_flags = 0;
    msg->ifa_prefixlen = 8 * chunk.len;
    msg->ifa_scope = RT_SCOPE_UNIVERSE;
    msg->ifa_index = if_index;
	
	add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));

	return netlink_send_ack(this, this->socket_rt, hdr);
}

/**
 * Manages source routes in the routing table.
 * By setting the appropriate nlmsg_type, the route added or r.
 */
static status_t manage_srcroute(private_kernel_interface_t *this, int nlmsg_type,
								int flags, route_entry_t *route)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr;
	struct rtmsg *msg;
	chunk_t chunk;
	
	/* if route is 0.0.0.0/0, we can't install it, as it would
	 * overwrite the default route. Instead, we add two routes:
	 * 0.0.0.0/1 and 128.0.0.0/1 
	 * TODO: use metrics instead */
	if (route->prefixlen == 0)
	{
		route_entry_t half;
		status_t status;
		
		half.dst_net = chunk_alloca(route->dst_net.len);
		memset(half.dst_net.ptr, 0, half.dst_net.len);
		half.src_ip = route->src_ip;
		half.gateway = route->gateway;
		half.if_index = route->if_index;
		half.prefixlen = 1;
		
		status = manage_srcroute(this, nlmsg_type, flags, &half);
		half.dst_net.ptr[0] |= 0x80;
		status = manage_srcroute(this, nlmsg_type, flags, &half);
		return status;
	}
	
	memset(&request, 0, sizeof(request));

	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
	hdr->nlmsg_type = nlmsg_type;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));

	msg = (struct rtmsg*)NLMSG_DATA(hdr);
	msg->rtm_family = route->src_ip->get_family(route->src_ip);
	msg->rtm_dst_len = route->prefixlen;
	msg->rtm_table = RT_TABLE_MAIN;
	msg->rtm_protocol = RTPROT_STATIC;
	msg->rtm_type = RTN_UNICAST;
	msg->rtm_scope = RT_SCOPE_UNIVERSE;
	
	add_attribute(hdr, RTA_DST, route->dst_net, sizeof(request));
	chunk = route->src_ip->get_address(route->src_ip);
	add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
	chunk = route->gateway->get_address(route->gateway);
	add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
	chunk.ptr = (char*)&route->if_index;
	chunk.len = sizeof(route->if_index);
	add_attribute(hdr, RTA_OIF, chunk, sizeof(request));

	return netlink_send_ack(this, this->socket_rt, hdr);
}

/**
 * Get the nexthop gateway for dest; or the source addr if gateway = FALSE
 */
static host_t* get_addr(private_kernel_interface_t *this,
						host_t *dest, bool gateway)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr, *out, *current;
	struct rtmsg *msg;
	chunk_t chunk;
	size_t len;
	host_t *addr = NULL;
	
	DBG2(DBG_KNL, "getting address to reach %H", dest);
	
	memset(&request, 0, sizeof(request));

	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST;
	hdr->nlmsg_type = RTM_GETROUTE;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));

	msg = (struct rtmsg*)NLMSG_DATA(hdr);
	msg->rtm_family = dest->get_family(dest);
	msg->rtm_dst_len = msg->rtm_family == AF_INET ? 32 : 128;
	msg->rtm_table = RT_TABLE_MAIN;
	msg->rtm_protocol = RTPROT_STATIC;
	msg->rtm_type = RTN_UNICAST;
	msg->rtm_scope = RT_SCOPE_UNIVERSE;
	
	chunk = dest->get_address(dest);
	add_attribute(hdr, RTA_DST, chunk, sizeof(request));
			
	if (netlink_send(this, this->socket_rt, hdr, &out, &len) != SUCCESS)
	{
		DBG1(DBG_KNL, "getting address to %H failed", dest);
		return NULL;
	}
	current = out;
	while (NLMSG_OK(current, len))
	{
		switch (current->nlmsg_type)
		{
			case NLMSG_DONE:
				break;
			case RTM_NEWROUTE:
			{
				struct rtattr *rta;
				size_t rtasize;
				
				msg = (struct rtmsg*)(NLMSG_DATA(current));
				rta = RTM_RTA(msg);
				rtasize = RTM_PAYLOAD(current);
				while(RTA_OK(rta, rtasize))
				{
					if ((rta->rta_type == RTA_PREFSRC && !gateway) ||
						(rta->rta_type == RTA_GATEWAY && gateway))
					{
						chunk.ptr = RTA_DATA(rta);
						chunk.len = RTA_PAYLOAD(rta);
						addr = host_create_from_chunk(msg->rtm_family, 
													  chunk, 0);
						break;
					}
					rta = RTA_NEXT(rta, rtasize);
				}
				break;
			}
			default:
				current = NLMSG_NEXT(current, len);
				continue;
		}
		break;
	}
	free(out);
	if (addr == NULL)
	{
		DBG2(DBG_KNL, "no route found to %H", dest);
	}
	return addr;
}

/**
 * Implementation of kernel_interface_t.get_source_addr.
 */
static host_t* get_source_addr(private_kernel_interface_t *this, host_t *dest)
{
	return get_addr(this, dest, FALSE);
}

/**
 * Implementation of kernel_interface_t.add_ip.
 */
static status_t add_ip(private_kernel_interface_t *this, 
						host_t *virtual_ip, host_t *iface_ip)
{
	iface_entry_t *iface;
	addr_entry_t *addr;
	iterator_t *addrs, *ifaces;

	DBG2(DBG_KNL, "adding virtual IP %H", virtual_ip);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		bool iface_found = FALSE;
	
		addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
		while (addrs->iterate(addrs, (void**)&addr))
		{
			if (iface_ip->ip_equals(iface_ip, addr->ip))
			{
				iface_found = TRUE;
			}
			else if (virtual_ip->ip_equals(virtual_ip, addr->ip))
			{
				addr->refcount++;
				DBG2(DBG_KNL, "virtual IP %H already installed on %s",
					 virtual_ip, iface->ifname);
				addrs->destroy(addrs);
				ifaces->destroy(ifaces);
				return SUCCESS;
			}
		}
		addrs->destroy(addrs);
		
		if (iface_found)
		{
			int ifindex = iface->ifindex;
			ifaces->destroy(ifaces);
			if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
							  ifindex, virtual_ip) == SUCCESS)
			{
				addr = malloc_thing(addr_entry_t);
				addr->ip = virtual_ip->clone(virtual_ip);
				addr->refcount = 1;
				addr->virtual = TRUE;
				addr->scope = RT_SCOPE_UNIVERSE;
				pthread_mutex_lock(&this->mutex);
				iface->addrs->insert_last(iface->addrs, addr);
				pthread_mutex_unlock(&this->mutex);
				return SUCCESS;
			}
			DBG2(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
			return FAILED;
			
		}
		
	}
	ifaces->destroy(ifaces);
	
	DBG2(DBG_KNL, "interface address %H not found, unable to install"
		 "virtual IP %H", iface_ip, virtual_ip);
	return FAILED;
}

/**
 * Implementation of kernel_interface_t.del_ip.
 */
static status_t del_ip(private_kernel_interface_t *this, host_t *virtual_ip)
{
	iface_entry_t *iface;
	addr_entry_t *addr;
	iterator_t *addrs, *ifaces;

	DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
	
	ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
	while (ifaces->iterate(ifaces, (void**)&iface))
	{
		addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
		while (addrs->iterate(addrs, (void**)&addr))
		{
			if (virtual_ip->ip_equals(virtual_ip, addr->ip))
			{
				int ifindex = iface->ifindex;
				addr->refcount--;
				if (addr->refcount == 0)
				{
					addrs->remove(addrs);
					addrs->destroy(addrs);
					ifaces->destroy(ifaces);
					addr_entry_destroy(addr);
					return manage_ipaddr(this, RTM_DELADDR, 0,
										 ifindex, virtual_ip);
				}
				DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
					 virtual_ip);
				addrs->destroy(addrs);
				ifaces->destroy(ifaces);
				return SUCCESS;
			}
		}
		addrs->destroy(addrs);
	}
	ifaces->destroy(ifaces);
	
	DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
	return FAILED;
}

/**
 * Implementation of kernel_interface_t.get_spi.
 */
static status_t get_spi(private_kernel_interface_t *this, 
						host_t *src, host_t *dst, 
						protocol_id_t protocol, u_int32_t reqid,
						u_int32_t *spi)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr, *out;
	struct xfrm_userspi_info *userspi;
	u_int32_t received_spi = 0;
	size_t len;
	
	memset(&request, 0, sizeof(request));
	
	DBG2(DBG_KNL, "getting SPI for reqid %d", reqid);
	
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST;
	hdr->nlmsg_type = XFRM_MSG_ALLOCSPI;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info));

	userspi = (struct xfrm_userspi_info*)NLMSG_DATA(hdr);
	host2xfrm(src, &userspi->info.saddr);
	host2xfrm(dst, &userspi->info.id.daddr);
	userspi->info.id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
	userspi->info.mode = TRUE; /* tunnel mode */
	userspi->info.reqid = reqid;
	userspi->info.family = src->get_family(src);
	userspi->min = 0xc0000000;
	userspi->max = 0xcFFFFFFF;
	
	if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
	{
		hdr = out;
		while (NLMSG_OK(hdr, len))
		{
			switch (hdr->nlmsg_type)
			{
				case XFRM_MSG_NEWSA:
				{
					struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr);
					received_spi = usersa->id.spi;
					break;
				}
				case NLMSG_ERROR:
				{
					struct nlmsgerr *err = NLMSG_DATA(hdr);
					
					DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
						 strerror(-err->error), -err->error);
					break;
				}
				default:
					hdr = NLMSG_NEXT(hdr, len);
					continue;
				case NLMSG_DONE:
					break;
			}
			break;
		}
		free(out);
	}
	
	if (received_spi == 0)
	{
		DBG1(DBG_KNL, "unable to get SPI for reqid %d", reqid);
		return FAILED;
	}
	
	DBG2(DBG_KNL, "got SPI 0x%x for reqid %d", received_spi, reqid);
	
	*spi = received_spi;
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.add_sa.
 */
static status_t add_sa(private_kernel_interface_t *this,
					   host_t *src, host_t *dst, u_int32_t spi,
					   protocol_id_t protocol, u_int32_t reqid,
					   u_int64_t expire_soft, u_int64_t expire_hard,
					   algorithm_t *enc_alg, algorithm_t *int_alg,
					   prf_plus_t *prf_plus, mode_t mode, bool encap,
					   bool replace)
{
	unsigned char request[BUFFER_SIZE];
	char *alg_name;
	u_int key_size;
	struct nlmsghdr *hdr;
	struct xfrm_usersa_info *sa;
	
	memset(&request, 0, sizeof(request));
	
	DBG2(DBG_KNL, "adding SAD entry with SPI 0x%x", spi);

	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
	hdr->nlmsg_type = replace ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
	
	sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
	host2xfrm(src, &sa->saddr);
	host2xfrm(dst, &sa->id.daddr);
	sa->id.spi = spi;
	sa->id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
	sa->family = src->get_family(src);
	sa->mode = mode;
	sa->replay_window = 32;
	sa->reqid = reqid;
	/* we currently do not expire SAs by volume/packet count */
	sa->lft.soft_byte_limit = XFRM_INF;
	sa->lft.hard_byte_limit = XFRM_INF;
	sa->lft.soft_packet_limit = XFRM_INF;
	sa->lft.hard_packet_limit = XFRM_INF;
	/* we use lifetimes since added, not since used */
	sa->lft.soft_add_expires_seconds = expire_soft;
	sa->lft.hard_add_expires_seconds = expire_hard;
	sa->lft.soft_use_expires_seconds = 0;
	sa->lft.hard_use_expires_seconds = 0;
	
	struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_info);
	
	if (enc_alg->algorithm != ENCR_UNDEFINED)
	{
		rthdr->rta_type = XFRMA_ALG_CRYPT;
		alg_name = lookup_algorithm(encryption_algs, enc_alg, &key_size);
		if (alg_name == NULL)
		{
			DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
				 encryption_algorithm_names, enc_alg->algorithm);
			return FAILED;
		}
		DBG2(DBG_KNL, "  using encryption algorithm %N with key size %d",
			 encryption_algorithm_names, enc_alg->algorithm, key_size);
		
		rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size);
		hdr->nlmsg_len += rthdr->rta_len;
		if (hdr->nlmsg_len > sizeof(request))
		{
			return FAILED;
		}
		
		struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
		algo->alg_key_len = key_size;
		strcpy(algo->alg_name, alg_name);
		prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key);
		
		rthdr = XFRM_RTA_NEXT(rthdr);
	}
	
	if (int_alg->algorithm  != AUTH_UNDEFINED)
	{
		rthdr->rta_type = XFRMA_ALG_AUTH;
		alg_name = lookup_algorithm(integrity_algs, int_alg, &key_size);
		if (alg_name == NULL)
		{
			DBG1(DBG_KNL, "algorithm %N not supported by kernel!", 
				 integrity_algorithm_names, int_alg->algorithm);
			return FAILED;
		}
		DBG2(DBG_KNL, "  using integrity algorithm %N with key size %d",
			 integrity_algorithm_names, int_alg->algorithm, key_size);
		
		rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size);
		hdr->nlmsg_len += rthdr->rta_len;
		if (hdr->nlmsg_len > sizeof(request))
		{
			return FAILED;
		}
		
		struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
		algo->alg_key_len = key_size;
		strcpy(algo->alg_name, alg_name);
		prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key);
		
		rthdr = XFRM_RTA_NEXT(rthdr);
	}
	
	/* TODO: add IPComp here */
	
	if (encap)
	{
		rthdr->rta_type = XFRMA_ENCAP;
		rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));

		hdr->nlmsg_len += rthdr->rta_len;
		if (hdr->nlmsg_len > sizeof(request))
		{
			return FAILED;
		}

		struct xfrm_encap_tmpl* tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rthdr);
		tmpl->encap_type = UDP_ENCAP_ESPINUDP;
		tmpl->encap_sport = htons(src->get_port(src));
		tmpl->encap_dport = htons(dst->get_port(dst));
		memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
		/* encap_oa could probably be derived from the 
		 * traffic selectors [rfc4306, p39]. In the netlink kernel implementation 
		 * pluto does the same as we do here but it uses encap_oa in the 
		 * pfkey implementation. BUT as /usr/src/linux/net/key/af_key.c indicates 
		 * the kernel ignores it anyway
		 *   -> does that mean that NAT-T encap doesn't work in transport mode?
		 * No. The reason the kernel ignores NAT-OA is that it recomputes 
		 * (or, rather, just ignores) the checksum. If packets pass
		 * the IPsec checks it marks them "checksum ok" so OA isn't needed. */
		rthdr = XFRM_RTA_NEXT(rthdr);
	}
	
	if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to add SAD entry with SPI 0x%x", spi);
		return FAILED;
	}
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.update_sa.
 */
static status_t update_sa(private_kernel_interface_t *this,
						  u_int32_t spi, protocol_id_t protocol,
						  host_t *src, host_t *dst,
						  host_t *new_src, host_t *new_dst, bool encap)
{
	unsigned char request[BUFFER_SIZE], *pos;
	struct nlmsghdr *hdr, *out = NULL;
	struct xfrm_usersa_id *sa_id;
	struct xfrm_usersa_info *out_sa = NULL, *sa;
	size_t len;
	struct rtattr *rta;
	size_t rtasize;
	struct xfrm_encap_tmpl* tmpl = NULL;
	
	memset(&request, 0, sizeof(request));
	
	DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x for update", spi);

	/* query the exisiting SA first */
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST;
	hdr->nlmsg_type = XFRM_MSG_GETSA;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));

	sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
	host2xfrm(dst, &sa_id->daddr);
	sa_id->spi = spi;
	sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
	sa_id->family = dst->get_family(dst);
	
	if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
	{
		hdr = out;
		while (NLMSG_OK(hdr, len))
		{
			switch (hdr->nlmsg_type)
			{
				case XFRM_MSG_NEWSA:
				{
					out_sa = NLMSG_DATA(hdr);
					break;
				}
				case NLMSG_ERROR:
				{
					struct nlmsgerr *err = NLMSG_DATA(hdr);
					DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
						 strerror(-err->error), -err->error);
					break;
				}
				default:
					hdr = NLMSG_NEXT(hdr, len);
					continue;
				case NLMSG_DONE:
					break;
			}
			break;
		}
	}
	if (out_sa == NULL ||
		this->public.del_sa(&this->public, dst, spi, protocol) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to update SAD entry with SPI 0x%x", spi);
		free(out);
		return FAILED;
	}
	
	DBG2(DBG_KNL, "updating SAD entry with SPI 0x%x from %#H..%#H to %#H..%#H",
		 spi, src, dst, new_src, new_dst);
	
	/* copy over the SA from out to request */
	hdr = (struct nlmsghdr*)request;
	memcpy(hdr, out, min(out->nlmsg_len, sizeof(request)));
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;	
	hdr->nlmsg_type = XFRM_MSG_NEWSA;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
	sa = NLMSG_DATA(hdr);
	sa->family = new_dst->get_family(new_dst);
	
	if (!src->ip_equals(src, new_src))
	{
		host2xfrm(new_src, &sa->saddr);
	}
	if (!dst->ip_equals(dst, new_dst))
	{
		host2xfrm(new_dst, &sa->id.daddr);
	}
	
	rta = XFRM_RTA(out, struct xfrm_usersa_info);
	rtasize = XFRM_PAYLOAD(out, struct xfrm_usersa_info);
	pos = (u_char*)XFRM_RTA(hdr, struct xfrm_usersa_info);
	while(RTA_OK(rta, rtasize))
	{
		/* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
		if (rta->rta_type != XFRMA_ENCAP || encap)
		{
			if (rta->rta_type == XFRMA_ENCAP)
			{	/* update encap tmpl */
				tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
				tmpl->encap_sport = ntohs(new_src->get_port(new_src));
				tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
			}	
			memcpy(pos, rta, rta->rta_len);
			pos += rta->rta_len;
			hdr->nlmsg_len += rta->rta_len;
		}
		rta = RTA_NEXT(rta, rtasize);
	}
	if (tmpl == NULL && encap)
	{	/* add tmpl if we are enabling it */
		rta = (struct rtattr*)pos;
		rta->rta_type = XFRMA_ENCAP;
		rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));
		hdr->nlmsg_len += rta->rta_len;
		tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
		tmpl->encap_type = UDP_ENCAP_ESPINUDP;
		tmpl->encap_sport = ntohs(new_src->get_port(new_src));
		tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
		memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
	}
	
	if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to update SAD entry with SPI 0x%x", spi);
		free(out);
		return FAILED;
	}
	free(out);
	
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.query_sa.
 */
static status_t query_sa(private_kernel_interface_t *this, host_t *dst,
						 u_int32_t spi, protocol_id_t protocol,
						 u_int32_t *use_time)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *out = NULL, *hdr;
	struct xfrm_usersa_id *sa_id;
	struct xfrm_usersa_info *sa = NULL;
	size_t len;
	
	DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x", spi);
	memset(&request, 0, sizeof(request));
	
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST;
	hdr->nlmsg_type = XFRM_MSG_GETSA;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));

	sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
	host2xfrm(dst, &sa_id->daddr);
	sa_id->spi = spi;
	sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
	sa_id->family = dst->get_family(dst);
	
	if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
	{
		hdr = out;
		while (NLMSG_OK(hdr, len))
		{
			switch (hdr->nlmsg_type)
			{
				case XFRM_MSG_NEWSA:
				{
					sa = NLMSG_DATA(hdr);
					break;
				}
				case NLMSG_ERROR:
				{
					struct nlmsgerr *err = NLMSG_DATA(hdr);
					DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
						 strerror(-err->error), -err->error);
					break;
				}
				default:
					hdr = NLMSG_NEXT(hdr, len);
					continue;
				case NLMSG_DONE:
					break;
			}
			break;
		}
	}
	
	if (sa == NULL)
	{
		DBG1(DBG_KNL, "unable to query SAD entry with SPI 0x%x", spi);
		free(out);
		return FAILED;
	}
	
	*use_time = sa->curlft.use_time;
	free (out);
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.del_sa.
 */
static status_t del_sa(private_kernel_interface_t *this, host_t *dst,
					   u_int32_t spi, protocol_id_t protocol)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr;
	struct xfrm_usersa_id *sa_id;
	
	memset(&request, 0, sizeof(request));
	
	DBG2(DBG_KNL, "deleting SAD entry with SPI 0x%x", spi);
	
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
	hdr->nlmsg_type = XFRM_MSG_DELSA;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
	
	sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
	host2xfrm(dst, &sa_id->daddr);
	sa_id->spi = spi;
	sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
	sa_id->family = dst->get_family(dst);
	
	if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to delete SAD entry with SPI 0x%x", spi);
		return FAILED;
	}
	DBG2(DBG_KNL, "deleted SAD entry with SPI 0x%x", spi);
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.add_policy.
 */
static status_t add_policy(private_kernel_interface_t *this, 
						   host_t *src, host_t *dst,
						   traffic_selector_t *src_ts,
						   traffic_selector_t *dst_ts,
						   policy_dir_t direction, protocol_id_t protocol,
						   u_int32_t reqid, bool high_prio, mode_t mode)
{
	iterator_t *iterator;
	policy_entry_t *current, *policy;
	bool found = FALSE;
	unsigned char request[BUFFER_SIZE];
	struct xfrm_userpolicy_info *policy_info;
	struct nlmsghdr *hdr;
	
	/* create a policy */
	policy = malloc_thing(policy_entry_t);
	memset(policy, 0, sizeof(policy_entry_t));
	policy->sel = ts2selector(src_ts, dst_ts);
	policy->direction = direction;
	
	/* find the policy, which matches EXACTLY */
	pthread_mutex_lock(&this->mutex);
	iterator = this->policies->create_iterator(this->policies, TRUE);
	while (iterator->iterate(iterator, (void**)&current))
	{
		if (memcmp(&current->sel, &policy->sel, sizeof(struct xfrm_selector)) == 0 &&
			policy->direction == current->direction)
		{
			/* use existing policy */
			current->refcount++;
			DBG2(DBG_KNL, "policy %R===%R already exists, increasing ",
				 "refcount", src_ts, dst_ts);
			free(policy);
			policy = current;
			found = TRUE;
			break;
		}
	}
	iterator->destroy(iterator);
	if (!found)
	{	/* apply the new one, if we have no such policy */
		this->policies->insert_last(this->policies, policy);
		policy->refcount = 1;
	}
	
	DBG2(DBG_KNL, "adding policy %R===%R", src_ts, dst_ts);
	
	memset(&request, 0, sizeof(request));
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
	hdr->nlmsg_type = XFRM_MSG_UPDPOLICY;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));

	policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
	policy_info->sel = policy->sel;
	policy_info->dir = policy->direction;
	/* calculate priority based on source selector size, small size = high prio */
	policy_info->priority = high_prio ? PRIO_HIGH : PRIO_LOW;
	policy_info->priority -= policy->sel.prefixlen_s * 10;
	policy_info->priority -= policy->sel.proto ? 2 : 0;
	policy_info->priority -= policy->sel.sport_mask ? 1 : 0;
	policy_info->action = XFRM_POLICY_ALLOW;
	policy_info->share = XFRM_SHARE_ANY;
	pthread_mutex_unlock(&this->mutex);
	
	/* policies don't expire */
	policy_info->lft.soft_byte_limit = XFRM_INF;
	policy_info->lft.soft_packet_limit = XFRM_INF;
	policy_info->lft.hard_byte_limit = XFRM_INF;
	policy_info->lft.hard_packet_limit = XFRM_INF;
	policy_info->lft.soft_add_expires_seconds = 0;
	policy_info->lft.hard_add_expires_seconds = 0;
	policy_info->lft.soft_use_expires_seconds = 0;
	policy_info->lft.hard_use_expires_seconds = 0;
	
	struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info);
	rthdr->rta_type = XFRMA_TMPL;

	rthdr->rta_len = sizeof(struct xfrm_user_tmpl);
	rthdr->rta_len = RTA_LENGTH(rthdr->rta_len);

	hdr->nlmsg_len += rthdr->rta_len;
	if (hdr->nlmsg_len > sizeof(request))
	{
		return FAILED;
	}
	
	struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr);
	tmpl->reqid = reqid;
	tmpl->id.proto = (protocol == PROTO_AH) ? KERNEL_AH : KERNEL_ESP;
	tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
	tmpl->mode = mode;
	tmpl->family = src->get_family(src);
	
	host2xfrm(src, &tmpl->saddr);
	host2xfrm(dst, &tmpl->id.daddr);
	
	if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to add policy %R===%R", src_ts, dst_ts);
		return FAILED;
	}
	
	/* install a route, if:
	 * - we are NOT updating a policy
	 * - this is a forward policy (to just get one for each child)
	 * - we are in tunnel mode
	 * - we are not using IPv6 (does not work correctly yet!)
	 */
	if (policy->route == NULL && direction == POLICY_FWD &&
		mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6)
	{
		policy->route = malloc_thing(route_entry_t);
		if (get_address_by_ts(this, dst_ts, &policy->route->src_ip) == SUCCESS)
		{
			/* if we have a gateway (via), we use it. If it's direct, we 
			 * use the peers address (which is src, as we are in POLICY_FWD).*/
			policy->route->gateway = get_addr(this, src, TRUE);
			if (policy->route->gateway == NULL)
			{
				policy->route->gateway = src->clone(src);
			}
			policy->route->if_index = get_interface_index(this, dst);
			policy->route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
			memcpy(policy->route->dst_net.ptr, &policy->sel.saddr, policy->route->dst_net.len);
			policy->route->prefixlen = policy->sel.prefixlen_s;
			
			if (manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
								policy->route) != SUCCESS)
			{
				DBG1(DBG_KNL, "unable to install source route for %H",
					 policy->route->src_ip);
				route_entry_destroy(policy->route);
				policy->route = NULL;
			}
		}
		else
		{
			free(policy->route);
			policy->route = NULL;
		}
	}

	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.query_policy.
 */
static status_t query_policy(private_kernel_interface_t *this,
							 traffic_selector_t *src_ts, 
							 traffic_selector_t *dst_ts,
							 policy_dir_t direction, u_int32_t *use_time)
{
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *out = NULL, *hdr;
	struct xfrm_userpolicy_id *policy_id;
	struct xfrm_userpolicy_info *policy = NULL;
	size_t len;
	
	memset(&request, 0, sizeof(request));
	
	DBG2(DBG_KNL, "querying policy %R===%R", src_ts, dst_ts);

	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST;
	hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));

	policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
	policy_id->sel = ts2selector(src_ts, dst_ts);
	policy_id->dir = direction;
	
	if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
	{
		hdr = out;
		while (NLMSG_OK(hdr, len))
		{
			switch (hdr->nlmsg_type)
			{
				case XFRM_MSG_NEWPOLICY:
				{
					policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
					break;
				}
				case NLMSG_ERROR:
				{
					struct nlmsgerr *err = NLMSG_DATA(hdr);
					DBG1(DBG_KNL, "querying policy failed: %s (%d)",
						 strerror(-err->error), -err->error);
					break;
				}
				default:
					hdr = NLMSG_NEXT(hdr, len);
					continue;
				case NLMSG_DONE:
					break;
			}
			break;
		}
	}
	
	if (policy == NULL)
	{
		DBG2(DBG_KNL, "unable to query policy %R===%R", src_ts, dst_ts);
		free(out);
		return FAILED;
	}
	*use_time = (time_t)policy->curlft.use_time;
	
	free(out);
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.del_policy.
 */
static status_t del_policy(private_kernel_interface_t *this,
						   traffic_selector_t *src_ts, 
						   traffic_selector_t *dst_ts,
						   policy_dir_t direction)
{
	policy_entry_t *current, policy, *to_delete = NULL;
	route_entry_t *route;
	unsigned char request[BUFFER_SIZE];
	struct nlmsghdr *hdr;
	struct xfrm_userpolicy_id *policy_id;
	iterator_t *iterator;
	
	DBG2(DBG_KNL, "deleting policy %R===%R", src_ts, dst_ts);
	
	/* create a policy */
	memset(&policy, 0, sizeof(policy_entry_t));
	policy.sel = ts2selector(src_ts, dst_ts);
	policy.direction = direction;
	
	/* find the policy */
	iterator = this->policies->create_iterator_locked(this->policies, &this->mutex);
	while (iterator->iterate(iterator, (void**)&current))
	{
		if (memcmp(&current->sel, &policy.sel, sizeof(struct xfrm_selector)) == 0 &&
			policy.direction == current->direction)
		{
			to_delete = current;
			if (--to_delete->refcount > 0)
			{
				/* is used by more SAs, keep in kernel */
				DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
				iterator->destroy(iterator);
				return SUCCESS;
			}
			/* remove if last reference */
			iterator->remove(iterator);
			break;
		}
	}
	iterator->destroy(iterator);
	if (!to_delete)
	{
		DBG1(DBG_KNL, "deleting policy %R===%R failed, not found", src_ts, dst_ts);
		return NOT_FOUND;
	}
	
	memset(&request, 0, sizeof(request));
	
	hdr = (struct nlmsghdr*)request;
	hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
	hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
	hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));

	policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
	policy_id->sel = to_delete->sel;
	policy_id->dir = direction;
	
	route = to_delete->route;
	free(to_delete);
	
	if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
	{
		DBG1(DBG_KNL, "unable to delete policy %R===%R", src_ts, dst_ts);
		return FAILED;
	}

	if (route)
	{
		if (manage_srcroute(this, RTM_DELROUTE, 0, route) != SUCCESS)
		{
			DBG1(DBG_KNL, "error uninstalling route installed with "
				 "policy %R===%R", src_ts, dst_ts);
		}		
		route_entry_destroy(route);
	}
	return SUCCESS;
}

/**
 * Implementation of kernel_interface_t.destroy.
 */
static void destroy(private_kernel_interface_t *this)
{
	this->job->cancel(this->job);
	close(this->socket_xfrm_events);
	close(this->socket_xfrm);
	close(this->socket_rt_events);
	close(this->socket_rt);
	this->policies->destroy(this->policies);
	this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
	free(this);
}

/*
 * Described in header.
 */
kernel_interface_t *kernel_interface_create()
{
	private_kernel_interface_t *this = malloc_thing(private_kernel_interface_t);
	struct sockaddr_nl addr;
	
	/* public functions */
	this->public.get_spi = (status_t(*)(kernel_interface_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi;
	this->public.add_sa  = (status_t(*)(kernel_interface_t *,host_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t,u_int64_t,u_int64_t,algorithm_t*,algorithm_t*,prf_plus_t*,mode_t,bool,bool))add_sa;
	this->public.update_sa = (status_t(*)(kernel_interface_t*,u_int32_t,protocol_id_t,host_t*,host_t*,host_t*,host_t*,bool))update_sa;
	this->public.query_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t*))query_sa;
	this->public.del_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t))del_sa;
	this->public.add_policy = (status_t(*)(kernel_interface_t*,host_t*,host_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,protocol_id_t,u_int32_t,bool,mode_t))add_policy;
	this->public.query_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy;
	this->public.del_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t))del_policy;
	this->public.get_interface = (char*(*)(kernel_interface_t*,host_t*))get_interface_name;
	this->public.create_address_iterator = (iterator_t*(*)(kernel_interface_t*))create_address_iterator;
	this->public.get_source_addr = (host_t*(*)(kernel_interface_t*, host_t *dest))get_source_addr;
	this->public.add_ip = (status_t(*)(kernel_interface_t*,host_t*,host_t*)) add_ip;
	this->public.del_ip = (status_t(*)(kernel_interface_t*,host_t*)) del_ip;
	this->public.destroy = (void(*)(kernel_interface_t*)) destroy;

	/* private members */
	this->policies = linked_list_create();
	this->ifaces = linked_list_create();
	this->hiter = NULL;
	this->seq = 200;
	pthread_mutex_init(&this->mutex,NULL);
	
	memset(&addr, 0, sizeof(addr));
	addr.nl_family = AF_NETLINK;
	
	/* create and bind RT socket */
	this->socket_rt = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
	if (this->socket_rt <= 0)
	{
		charon->kill(charon, "unable to create RT netlink socket");
	}
	addr.nl_groups = 0;
	if (bind(this->socket_rt, (struct sockaddr*)&addr, sizeof(addr)))
	{
		charon->kill(charon, "unable to bind RT netlink socket");
	}
	
	/* create and bind RT socket for events (address/interface/route changes) */
	this->socket_rt_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
	if (this->socket_rt_events <= 0)
	{
		charon->kill(charon, "unable to create RT event socket");
	}
	addr.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR | 
					 RTMGRP_IPV4_ROUTE | RTMGRP_IPV4_ROUTE | RTMGRP_LINK;
	if (bind(this->socket_rt_events, (struct sockaddr*)&addr, sizeof(addr)))
	{
		charon->kill(charon, "unable to bind RT event socket");
	}
	
	/* create and bind XFRM socket */ 
	this->socket_xfrm = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
	if (this->socket_xfrm <= 0)
	{
		charon->kill(charon, "unable to create XFRM netlink socket");
	}
	addr.nl_groups = 0;
	if (bind(this->socket_xfrm, (struct sockaddr*)&addr, sizeof(addr)))
	{
		charon->kill(charon, "unable to bind XFRM netlink socket");
	}
	
	/* create and bind XFRM socket for ACQUIRE & EXPIRE */
	this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
	if (this->socket_xfrm_events <= 0)
	{
		charon->kill(charon, "unable to create XFRM event socket");
	}
	addr.nl_groups = XFRMGRP_ACQUIRE | XFRMGRP_EXPIRE;
	if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr)))
	{
		charon->kill(charon, "unable to bind XFRM event socket");
	}
	
	this->job = callback_job_create((callback_job_cb_t)receive_events,
									this, NULL, NULL);
	charon->processor->queue_job(charon->processor, (job_t*)this->job);
	
	if (init_address_list(this) != SUCCESS)
	{
		charon->kill(charon, "unable to get interface list");
	}
	
	return &this->public;
}