aboutsummaryrefslogtreecommitdiff
path: root/src/exit/gnunet-daemon-exit.c
blob: 61c719e5dd3b97abb22c7bf3cd730dc37d02b597 (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
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
/*
     This file is part of GNUnet.
     (C) 2010, 2012 Christian Grothoff

     GNUnet 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 3, or (at your
     option) any later version.

     GNUnet 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.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/

/**
 * @file exit/gnunet-daemon-exit.c
 * @brief tool to allow IP traffic exit from the GNUnet mesh to the Internet
 * @author Philipp Toelke
 * @author Christian Grothoff
 *
 * TODO:
 * - test
 *
 * Design:
 * - which code should advertise services? the service model is right
 *   now a bit odd, especially as this code DOES the exit and knows
 *   the DNS "name", but OTOH this is clearly NOT the place to advertise
 *   the service's existence; maybe the daemon should turn into a 
 *   service with an API to add local-exit services dynamically?
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_applications.h"
#include "gnunet_mesh_service.h"
#include "gnunet_statistics_service.h"
#include "gnunet_constants.h"
#include "gnunet_tun_lib.h"
#include "exit.h"

/**
 * Information about an address.
 */
struct SocketAddress
{
  /**
   * AF_INET or AF_INET6.
   */
  int af;

  /**
   * Remote address information.
   */
  union
  {
    /**
     * Address, if af is AF_INET.
     */
    struct in_addr ipv4;

    /**
     * Address, if af is AF_INET6.
     */
    struct in6_addr ipv6;
  } address;
  
  /**
   * IPPROTO_TCP or IPPROTO_UDP;
   */
  uint8_t proto;

  /**
   * Remote port, in host byte order!
   */
  uint16_t port;

};

/**
 * This struct is saved into the services-hashmap to represent
 * a service this peer is specifically offering an exit for
 * (for a specific domain name).
 */
struct LocalService
{

  /**
   * Remote address to use for the service.
   */
  struct SocketAddress address;

  /**
   * DNS name of the service.
   */
  char *name;

  /**
   * Port I am listening on within GNUnet for this service, in host
   * byte order.  (as we may redirect ports).
   */
  uint16_t my_port;

};

/**
 * Information we use to track a connection (the classical 6-tuple of
 * IP-version, protocol, source-IP, destination-IP, source-port and
 * destinatin-port.
 */
struct RedirectInformation 
{

  /**
   * Address information for the other party (equivalent of the
   * arguments one would give to "connect").
   */
  struct SocketAddress remote_address;

  /**
   * Address information we used locally (AF and proto must match
   * "remote_address").  Equivalent of the arguments one would give to
   * "bind".
   */
  struct SocketAddress local_address;

  /* 
     Note 1: additional information might be added here in the
     future to support protocols that require special handling,
     such as ftp/tftp 

     Note 2: we might also sometimes not match on all components
     of the tuple, to support protocols where things do not always
     fully map.
  */
};


/**
 * Queue of messages to a tunnel.
 */
struct TunnelMessageQueue
{
  /**
   * This is a doubly-linked list.
   */
  struct TunnelMessageQueue *next;

  /**
   * This is a doubly-linked list.
   */
  struct TunnelMessageQueue *prev;

  /**
   * Payload to send via the tunnel.
   */
  const void *payload;

  /**
   * Number of bytes in 'payload'.
   */
  size_t len;
};


/**
 * This struct is saved into connections_map to allow finding the
 * right tunnel given an IP packet from TUN.  It is also associated
 * with the tunnel's closure so we can find it again for the next
 * message from the tunnel.
 */
struct TunnelState
{
  /**
   * Mesh tunnel that is used for this connection.
   */
  struct GNUNET_MESH_Tunnel *tunnel;

  /**
   * Heap node for this state in the connections_heap.
   */
  struct GNUNET_CONTAINER_HeapNode *heap_node;

  /**
   * Key this state has in the connections_map.
   */
  GNUNET_HashCode state_key;

  /**
   * Associated service record, or NULL for no service.
   */
  struct LocalService *serv;

  /**
   * Head of DLL of messages for this tunnel.
   */
  struct TunnelMessageQueue *head;

  /**
   * Tail of DLL of messages for this tunnel.
   */
  struct TunnelMessageQueue *tail;

  /**
   * Active tunnel transmission request (or NULL).
   */
  struct GNUNET_MESH_TransmitHandle *th;

  /**
   * Primary redirection information for this connection.
   */
  struct RedirectInformation ri;

};


/**
 * The handle to the configuration used throughout the process
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * The handle to the helper
 */
static struct GNUNET_HELPER_Handle *helper_handle;

/**
 * Arguments to the exit helper.
 */
static char *exit_argv[8];

/**
 * IPv6 address of our TUN interface.
 */
static struct in6_addr exit_ipv6addr;

/**
 * IPv6 prefix (0..127) from configuration file.
 */
static unsigned long long ipv6prefix;

/**
 * IPv4 address of our TUN interface.
 */
static struct in_addr exit_ipv4addr;

/**
 * IPv4 netmask of our TUN interface.
 */
static struct in_addr exit_ipv4mask;


/**
 * Statistics.
 */
static struct GNUNET_STATISTICS_Handle *stats;

/**
 * The handle to mesh
 */
static struct GNUNET_MESH_Handle *mesh_handle;

/**
 * This hashmaps contains the mapping from peer, service-descriptor,
 * source-port and destination-port to a struct TunnelState
 */
static struct GNUNET_CONTAINER_MultiHashMap *connections_map;

/**
 * Heap so we can quickly find "old" connections.
 */
static struct GNUNET_CONTAINER_Heap *connections_heap;

/**
 * If there are at least this many connections, old ones will be removed
 */
static long long unsigned int max_connections;

/**
 * This hashmaps saves interesting things about the configured UDP services
 */
static struct GNUNET_CONTAINER_MultiHashMap *udp_services;

/**
 * This hashmaps saves interesting things about the configured TCP services
 */
static struct GNUNET_CONTAINER_MultiHashMap *tcp_services;

/**
 * Are we an IPv4-exit?
 */
static int ipv4_exit;

/**
 * Are we an IPv6-exit?
 */
static int ipv6_exit;

/**
 * Do we support IPv4 at all on the TUN interface?
 */
static int ipv4_enabled;

/**
 * Do we support IPv6 at all on the TUN interface?
 */
static int ipv6_enabled;


/**
 * Given IP information about a connection, calculate the respective
 * hash we would use for the 'connections_map'.
 *
 * @param hash resulting hash
 * @param ri information about the connection
 */
static void
hash_redirect_info (GNUNET_HashCode *hash, 
		    const struct RedirectInformation *ri)
{
  char *off;

  memset (hash, 0, sizeof (GNUNET_HashCode));
  /* the GNUnet hashmap only uses the first sizeof(unsigned int) of the hash,
     so we put the IP address in there (and hope for few collisions) */
  off = (char*) hash;
  switch (ri->remote_address.af)
  {
  case AF_INET:
    memcpy (off, &ri->remote_address.address.ipv4, sizeof (struct in_addr));
    off += sizeof (struct in_addr);
    break;
  case AF_INET6:
    memcpy (off, &ri->remote_address.address.ipv6, sizeof (struct in6_addr));
    off += sizeof (struct in_addr);
    break;
  default:
    GNUNET_assert (0);
  }
  memcpy (off, &ri->remote_address.port, sizeof (uint16_t));
  off += sizeof (uint16_t);
  switch (ri->local_address.af)
  {
  case AF_INET:
    memcpy (off, &ri->local_address.address.ipv4, sizeof (struct in_addr));
    off += sizeof (struct in_addr);
    break;
  case AF_INET6:
    memcpy (off, &ri->local_address.address.ipv6, sizeof (struct in6_addr));
    off += sizeof (struct in_addr);
    break;
  default:
    GNUNET_assert (0);
  }
  memcpy (off, &ri->local_address.port, sizeof (uint16_t));
  off += sizeof (uint16_t);
  memcpy (off, &ri->remote_address.proto, sizeof (uint8_t));
  off += sizeof (uint8_t);
}


/**
 * Get our connection tracking state.  Warns if it does not exists,
 * refreshes the timestamp if it does exist.
 *
 * @param af address family
 * @param protocol IPPROTO_UDP or IPPROTO_TCP
 * @param destination_ip target IP
 * @param destination_port target port
 * @param local_ip local IP
 * @param local_port local port
 * @param state_key set to hash's state if non-NULL
 * @return NULL if we have no tracking information for this tuple
 */
static struct TunnelState *
get_redirect_state (int af,
		    int protocol,		    
		    const void *destination_ip,
		    uint16_t destination_port,
		    const void *local_ip,
		    uint16_t local_port,
		    GNUNET_HashCode *state_key)
{
  struct RedirectInformation ri;
  GNUNET_HashCode key;
  struct TunnelState *state;

  if (protocol == IPPROTO_ICMP)
  {
    /* ignore ports */
    destination_port = 0;
    local_port = 0;
  }
  ri.remote_address.af = af;
  if (af == AF_INET)
    ri.remote_address.address.ipv4 = *((struct in_addr*) destination_ip);
  else
    ri.remote_address.address.ipv6 = * ((struct in6_addr*) destination_ip);
  ri.remote_address.port = destination_port;
  ri.remote_address.proto = protocol;
  ri.local_address.af = af;
  if (af == AF_INET)
    ri.local_address.address.ipv4 = *((struct in_addr*) local_ip);
  else
    ri.local_address.address.ipv6 = * ((struct in6_addr*) local_ip);
  ri.local_address.port = local_port;
  ri.local_address.proto = protocol;
  hash_redirect_info (&key, &ri);
  if (NULL != state_key)
    *state_key = key;
  state = GNUNET_CONTAINER_multihashmap_get (connections_map, &key);
  if (NULL == state)
    return NULL;
  /* Mark this connection as freshly used */
  if (NULL == state_key)
    GNUNET_CONTAINER_heap_update_cost (connections_heap, 
				       state->heap_node,
				       GNUNET_TIME_absolute_get ().abs_value);
  return state;
}


/**
 * Given a service descriptor and a destination port, find the
 * respective service entry.
 *
 * @param service_map map of services (TCP or UDP)
 * @param desc service descriptor
 * @param dpt destination port
 * @return NULL if we are not aware of such a service
 */
static struct LocalService *
find_service (struct GNUNET_CONTAINER_MultiHashMap *service_map,
	      const GNUNET_HashCode *desc,
	      uint16_t dpt)
{
  char key[sizeof (GNUNET_HashCode) + sizeof (uint16_t)];

  memcpy (&key[0], &dpt, sizeof (uint16_t));
  memcpy (&key[sizeof(uint16_t)], desc, sizeof (GNUNET_HashCode));
  return GNUNET_CONTAINER_multihashmap_get (service_map,
					    (GNUNET_HashCode *) key);
}


/**
 * Free memory associated with a service record.
 *
 * @param cls unused
 * @param key service descriptor
 * @param value service record to free
 * @return GNUNET_OK
 */
static int
free_service_record (void *cls,
		     const GNUNET_HashCode *key,
		     void *value)
{
  struct LocalService *service = value;

  GNUNET_free_non_null (service->name);
  GNUNET_free (service);
  return GNUNET_OK;
}


/**
 * Given a service descriptor and a destination port, find the
 * respective service entry.
 *
 * @param service_map map of services (TCP or UDP)
 * @param name name of the service 
 * @param dpt destination port
 * @param service service information record to store (service->name will be set).
 */
static void
store_service (struct GNUNET_CONTAINER_MultiHashMap *service_map,
	       const char *name,
	       uint16_t dpt,
	       struct LocalService *service)
{
  char key[sizeof (GNUNET_HashCode) + sizeof (uint16_t)];
  GNUNET_HashCode desc;

  GNUNET_CRYPTO_hash (name, strlen (name) + 1, &desc);
  service->name = GNUNET_strdup (name);
  memcpy (&key[0], &dpt, sizeof (uint16_t));
  memcpy (&key[sizeof(uint16_t)], &desc, sizeof (GNUNET_HashCode));
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (service_map,
					 (GNUNET_HashCode *) key,
					 service,
					 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    free_service_record (NULL, (GNUNET_HashCode *) key, service);
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		_("Got duplicate service records for `%s:%u'\n"),
		name,
		(unsigned int) dpt);
  }
}


/**
 * MESH is ready to receive a message for the tunnel.  Transmit it.
 *
 * @param cls the 'struct TunnelState'.
 * @param size number of bytes available in buf
 * @param buf where to copy the message
 * @return number of bytes copied to buf
 */
static size_t
send_to_peer_notify_callback (void *cls, size_t size, void *buf)
{
  struct TunnelState *s = cls;
  struct GNUNET_MESH_Tunnel *tunnel = s->tunnel;
  struct TunnelMessageQueue *tnq;

  s->th = NULL;
  tnq = s->head;
  if (NULL == tnq)
    return 0;
  if (0 == size)
  {
    s->th = GNUNET_MESH_notify_transmit_ready (tunnel, 
					       GNUNET_NO /* corking */, 
					       0 /* priority */,
					       GNUNET_TIME_UNIT_FOREVER_REL,
					       NULL,
					       tnq->len,
					       &send_to_peer_notify_callback,
					       s);
    return 0;
  }
  GNUNET_assert (size >= tnq->len);
  memcpy (buf, tnq->payload, tnq->len);
  size = tnq->len;
  GNUNET_CONTAINER_DLL_remove (s->head, 
			       s->tail,
			       tnq);  
  GNUNET_free (tnq);
  if (NULL != (tnq = s->head))
    s->th = GNUNET_MESH_notify_transmit_ready (tunnel, 
					       GNUNET_NO /* corking */, 
					       0 /* priority */,
					       GNUNET_TIME_UNIT_FOREVER_REL,
					       NULL,
					       tnq->len,
					       &send_to_peer_notify_callback,
					       s);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes transmitted via mesh tunnels"),
			    size, GNUNET_NO);
  return size;
}


/**
 * Send the given packet via the mesh tunnel.
 *
 * @param mesh_tunnel destination
 * @param tnq message to queue
 */
static void
send_packet_to_mesh_tunnel (struct GNUNET_MESH_Tunnel *mesh_tunnel,
			    struct TunnelMessageQueue *tnq)
{
  struct TunnelState *s;

  s = GNUNET_MESH_tunnel_get_data (mesh_tunnel);
  GNUNET_assert (NULL != s);
  GNUNET_CONTAINER_DLL_insert_tail (s->head, s->tail, tnq);
  if (NULL == s->th)
    s->th = GNUNET_MESH_notify_transmit_ready (mesh_tunnel, GNUNET_NO /* cork */, 0 /* priority */,
					       GNUNET_TIME_UNIT_FOREVER_REL,
					       NULL, tnq->len,
					       &send_to_peer_notify_callback,
					       s);
}


/**
 * @brief Handles an ICMP packet received from the helper.
 *
 * @param icmp A pointer to the Packet
 * @param pktlen number of bytes in 'icmp'
 * @param af address family (AFINET or AF_INET6)
 * @param destination_ip destination IP-address of the IP packet (should 
 *                       be our local address)
 * @param source_ip original source IP-address of the IP packet (should
 *                       be the original destination address)
 */
static void
icmp_from_helper (const struct GNUNET_TUN_IcmpHeader *icmp, 
		  size_t pktlen,
		  int af,
		  const void *destination_ip, 
		  const void *source_ip)
{
  struct TunnelState *state;
  struct TunnelMessageQueue *tnq;
  struct GNUNET_EXIT_IcmpToVPNMessage *i2v;
  const struct GNUNET_TUN_IPv4Header *ipv4;
  const struct GNUNET_TUN_IPv6Header *ipv6;
  const struct GNUNET_TUN_UdpHeader *udp;
  size_t mlen;
  uint16_t spt;
  uint16_t dpt;
  uint8_t protocol;

  {
    char sbuf[INET6_ADDRSTRLEN];
    char dbuf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received ICMP packet going from %s to %s\n",
		inet_ntop (af,
			   source_ip,
			   sbuf, sizeof (sbuf)),
		inet_ntop (af,
			   destination_ip,
			   dbuf, sizeof (dbuf)));    
  }
  if (pktlen < sizeof (struct GNUNET_TUN_IcmpHeader))
  {
    /* blame kernel */
    GNUNET_break (0);
    return;
  }

  /* Find out if this is an ICMP packet in response to an existing
     TCP/UDP packet and if so, figure out ports / protocol of the
     existing session from the IP data in the ICMP payload */
  spt = 0;
  dpt = 0;
  protocol = IPPROTO_ICMP;
  switch (af)
  {
  case AF_INET:
    switch (icmp->type)
      {
      case GNUNET_TUN_ICMPTYPE_ECHO_REPLY:
      case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST:
	break;
      case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE:
      case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH:
      case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED:
	if (pktlen < 
	    sizeof (struct GNUNET_TUN_IcmpHeader) +
	    sizeof (struct GNUNET_TUN_IPv4Header) + 8)
	{
	  /* blame kernel */
	  GNUNET_break (0);
	  return;
	}
	ipv4 = (const struct GNUNET_TUN_IPv4Header *) &icmp[1];
	protocol = ipv4->protocol;
	/* could be TCP or UDP, but both have the ports in the right
	   place, so that doesn't matter here */
	udp = (const struct GNUNET_TUN_UdpHeader *) &ipv4[1];
	spt = ntohs (udp->spt);
	dpt = ntohs (udp->dpt);
	/* throw away ICMP payload, won't be useful for the other side anyway */
	pktlen = sizeof (struct GNUNET_TUN_IcmpHeader);
	break;
      default:
	GNUNET_STATISTICS_update (stats,
				  gettext_noop ("# ICMPv4 packets dropped (type not allowed)"),
				  1, GNUNET_NO);
	return;
      }
    break;
  case AF_INET6:
    switch (icmp->type)
      {
      case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE:
      case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG:
      case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED:
      case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM:
	if (pktlen < 
	    sizeof (struct GNUNET_TUN_IcmpHeader) +
	    sizeof (struct GNUNET_TUN_IPv6Header) + 8)
	{
	  /* blame kernel */
	  GNUNET_break (0);
	  return;
	}
	ipv6 = (const struct GNUNET_TUN_IPv6Header *) &icmp[1];
	protocol = ipv6->next_header;
	/* could be TCP or UDP, but both have the ports in the right
	   place, so that doesn't matter here */
	udp = (const struct GNUNET_TUN_UdpHeader *) &ipv6[1];
	spt = ntohs (udp->spt);
	dpt = ntohs (udp->dpt);
	/* throw away ICMP payload, won't be useful for the other side anyway */
	pktlen = sizeof (struct GNUNET_TUN_IcmpHeader);
	break;
      case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST:
      case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY:
	break;
      default:
	GNUNET_STATISTICS_update (stats,
				  gettext_noop ("# ICMPv6 packets dropped (type not allowed)"),
				  1, GNUNET_NO);
	return;
      }
    break;
  default:
    GNUNET_assert (0);
  }
  switch (protocol)
  {
  case IPPROTO_ICMP:
    state = get_redirect_state (af, IPPROTO_ICMP,
				source_ip, 0,
				destination_ip, 0,
				NULL);
    break;
  case IPPROTO_UDP:
    state = get_redirect_state (af, IPPROTO_UDP,
				source_ip,
				spt,
				destination_ip,
				dpt,
				NULL);
    break;
  case IPPROTO_TCP:
    state = get_redirect_state (af, IPPROTO_TCP,
				source_ip,
				spt,
				destination_ip,
				dpt,
				NULL);
    break;
  default:
    GNUNET_STATISTICS_update (stats,
			      gettext_noop ("# ICMP packets dropped (not allowed)"),
			      1, GNUNET_NO);
    return;
  }
  if (NULL == state)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		_("ICMP Packet dropped, have no matching connection information\n"));
    return;
  }
  mlen = sizeof (struct GNUNET_EXIT_IcmpToVPNMessage) + pktlen - sizeof (struct GNUNET_TUN_IcmpHeader);
  tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueue) + mlen);  
  tnq->payload = &tnq[1];
  tnq->len = mlen;
  i2v = (struct GNUNET_EXIT_IcmpToVPNMessage *) &tnq[1];
  i2v->header.size = htons ((uint16_t) mlen);
  i2v->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_VPN);
  i2v->af = htonl (af);
  memcpy (&i2v->icmp_header,
	  icmp,
	  pktlen);
  send_packet_to_mesh_tunnel (state->tunnel,
			      tnq);
}


/**
 * @brief Handles an UDP packet received from the helper.
 *
 * @param udp A pointer to the Packet
 * @param pktlen number of bytes in 'udp'
 * @param af address family (AFINET or AF_INET6)
 * @param destination_ip destination IP-address of the IP packet (should 
 *                       be our local address)
 * @param source_ip original source IP-address of the IP packet (should
 *                       be the original destination address)
 */
static void
udp_from_helper (const struct GNUNET_TUN_UdpHeader *udp, 
		 size_t pktlen,
		 int af,
		 const void *destination_ip, 
		 const void *source_ip)
{
  struct TunnelState *state;
  struct TunnelMessageQueue *tnq;
  struct GNUNET_EXIT_UdpReplyMessage *urm;
  size_t mlen;

  {
    char sbuf[INET6_ADDRSTRLEN];
    char dbuf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received UDP packet going from %s:%u to %s:%u\n",
		inet_ntop (af,
			   source_ip,
			   sbuf, sizeof (sbuf)),
		(unsigned int) ntohs (udp->spt),
		inet_ntop (af,
			   destination_ip,
			   dbuf, sizeof (dbuf)),
		(unsigned int) ntohs (udp->dpt));
  }
  if (pktlen < sizeof (struct GNUNET_TUN_UdpHeader))
  {
    /* blame kernel */
    GNUNET_break (0);
    return;
  }
  if (pktlen != ntohs (udp->len))
  {
    /* blame kernel */
    GNUNET_break (0);
    return;
  }
  state = get_redirect_state (af, IPPROTO_UDP,
			      source_ip,
			      ntohs (udp->spt),
			      destination_ip,
			      ntohs (udp->dpt),
			      NULL);
  if (NULL == state)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		_("UDP Packet dropped, have no matching connection information\n"));
    return;
  }
  mlen = sizeof (struct GNUNET_EXIT_UdpReplyMessage) + pktlen - sizeof (struct GNUNET_TUN_UdpHeader);
  tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueue) + mlen);  
  tnq->payload = &tnq[1];
  tnq->len = mlen;
  urm = (struct GNUNET_EXIT_UdpReplyMessage *) &tnq[1];
  urm->header.size = htons ((uint16_t) mlen);
  urm->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_UDP_REPLY);
  urm->source_port = htons (0);
  urm->destination_port = htons (0);
  memcpy (&urm[1],
	  &udp[1],
	  pktlen - sizeof (struct GNUNET_TUN_UdpHeader));
  send_packet_to_mesh_tunnel (state->tunnel,
			      tnq);
}


/**
 * @brief Handles a TCP packet received from the helper.
 *
 * @param tcp A pointer to the Packet
 * @param pktlen the length of the packet, including its TCP header
 * @param af address family (AFINET or AF_INET6)
 * @param destination_ip destination IP-address of the IP packet (should 
 *                       be our local address)
 * @param source_ip original source IP-address of the IP packet (should
 *                       be the original destination address)
 */
static void
tcp_from_helper (const struct GNUNET_TUN_TcpHeader *tcp, 
		 size_t pktlen,
		 int af,
		 const void *destination_ip,
		 const void *source_ip)
{
  struct TunnelState *state;
  char buf[pktlen];
  struct GNUNET_TUN_TcpHeader *mtcp;
  struct GNUNET_EXIT_TcpDataMessage *tdm;
  struct TunnelMessageQueue *tnq;
  size_t mlen;

  {
    char sbuf[INET6_ADDRSTRLEN];
    char dbuf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received TCP packet with %u bytes going from %s:%u to %s:%u\n",
		pktlen - sizeof (struct GNUNET_TUN_TcpHeader),
		inet_ntop (af,
			   source_ip,
			   sbuf, sizeof (sbuf)),
		(unsigned int) ntohs (tcp->spt),
		inet_ntop (af,
			   destination_ip,
			   dbuf, sizeof (dbuf)),
		(unsigned int) ntohs (tcp->dpt));
  }
  if (pktlen < sizeof (struct GNUNET_TUN_TcpHeader))
  {
    /* blame kernel */
    GNUNET_break (0);
    return;
  }
  state = get_redirect_state (af, IPPROTO_TCP,
			      source_ip, 
			      ntohs (tcp->spt),
			      destination_ip,
			      ntohs (tcp->dpt),
			      NULL);
  if (NULL == state)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		_("TCP Packet dropped, have no matching connection information\n"));
    
    return;
  }
  /* mug port numbers and crc to avoid information leakage;
     sender will need to lookup the correct values anyway */
  memcpy (buf, tcp, pktlen);  
  mtcp = (struct GNUNET_TUN_TcpHeader *) buf;
  mtcp->spt = 0;
  mtcp->dpt = 0;
  mtcp->crc = 0;

  mlen = sizeof (struct GNUNET_EXIT_TcpDataMessage) + (pktlen - sizeof (struct GNUNET_TUN_TcpHeader));
  if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return;
  }

  tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueue) + mlen);
  tnq->payload = &tnq[1];
  tnq->len = mlen;
  tdm = (struct GNUNET_EXIT_TcpDataMessage *) &tnq[1];
  tdm->header.size = htons ((uint16_t) mlen);
  tdm->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_VPN);
  tdm->reserved = htonl (0);
  memcpy (&tdm->tcp_header,
	  buf, 
	  pktlen);
  send_packet_to_mesh_tunnel (state->tunnel,
			      tnq);
}


/**
 * Receive packets from the helper-process
 *
 * @param cls unused
 * @param client unsued
 * @param message message received from helper
 */
static void
message_token (void *cls GNUNET_UNUSED, void *client GNUNET_UNUSED,
               const struct GNUNET_MessageHeader *message)
{
  const struct GNUNET_TUN_Layer2PacketHeader *pkt_tun;
  size_t size;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Got %u-byte message of type %u from gnunet-helper-exit\n",
	      ntohs (message->size),
	      ntohs (message->type));
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Packets received from TUN"),
			    1, GNUNET_NO);
  if (ntohs (message->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER)
  {
    GNUNET_break (0);
    return;
  }
  size = ntohs (message->size);
  if (size < sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_MessageHeader))
  {
    GNUNET_break (0);
    return;
  }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from TUN"),
			    size, GNUNET_NO);
  pkt_tun = (const struct GNUNET_TUN_Layer2PacketHeader *) &message[1];
  size -= sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_MessageHeader);
  switch (ntohs (pkt_tun->proto))
  {
  case ETH_P_IPV4:
    {
      const struct GNUNET_TUN_IPv4Header *pkt4;

      if (size < sizeof (struct GNUNET_TUN_IPv4Header))
      {
	/* Kernel to blame? */
	GNUNET_break (0);
	return;
      }
      pkt4 = (const struct GNUNET_TUN_IPv4Header *) &pkt_tun[1];
      if (size != ntohs (pkt4->total_length))
      {
	/* Kernel to blame? */
	GNUNET_break (0);
	return;
      }
      if (pkt4->header_length * 4 != sizeof (struct GNUNET_TUN_IPv4Header))
      {
	GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		    _("IPv4 packet options received.  Ignored.\n"));
	return;
      }
      
      size -= sizeof (struct GNUNET_TUN_IPv4Header);
      switch (pkt4->protocol)
      {
      case IPPROTO_UDP:
	udp_from_helper ((const struct GNUNET_TUN_UdpHeader *) &pkt4[1], size,
			 AF_INET,
			 &pkt4->destination_address, 
			 &pkt4->source_address);
	break;
      case IPPROTO_TCP:
	tcp_from_helper ((const struct GNUNET_TUN_TcpHeader *) &pkt4[1], size,
			 AF_INET,
			 &pkt4->destination_address, 
			 &pkt4->source_address);
	break;
      case IPPROTO_ICMP:
	icmp_from_helper ((const struct GNUNET_TUN_IcmpHeader *) &pkt4[1], size,
			  AF_INET,
			  &pkt4->destination_address, 
			  &pkt4->source_address);
	break;
      default:
	GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		    _("IPv4 packet with unsupported next header received.  Ignored.\n"));
	return;
      }
    }
    break;
  case ETH_P_IPV6:
    {
      const struct GNUNET_TUN_IPv6Header *pkt6;

      if (size < sizeof (struct GNUNET_TUN_IPv6Header))
      {
	/* Kernel to blame? */
	GNUNET_break (0);
	return;
      }
      pkt6 = (struct GNUNET_TUN_IPv6Header *) &pkt_tun[1];
      if (size != ntohs (pkt6->payload_length))
      {
	/* Kernel to blame? */
	GNUNET_break (0);
	return;
      }
      size -= sizeof (struct GNUNET_TUN_IPv6Header);
      switch (pkt6->next_header)
      {
      case IPPROTO_UDP:
	udp_from_helper ((const struct GNUNET_TUN_UdpHeader *) &pkt6[1], size,
			 AF_INET6,
			 &pkt6->destination_address, 
			 &pkt6->source_address);
	break;
      case IPPROTO_TCP:
	tcp_from_helper ((const struct GNUNET_TUN_TcpHeader *) &pkt6[1], size,
			 AF_INET6,
			 &pkt6->destination_address, 
			 &pkt6->source_address);
	break;
      case IPPROTO_ICMP:
	icmp_from_helper ((const struct GNUNET_TUN_IcmpHeader *) &pkt6[1], size,
			  AF_INET6,
			  &pkt6->destination_address, 
			  &pkt6->source_address);
	break;
      default:
	GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		    _("IPv6 packet with unsupported next header received.  Ignored.\n"));
	return;
      }
    }
    break;
  default:
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		_("Packet from unknown protocol %u received.  Ignored.\n"),
		ntohs (pkt_tun->proto));
    break;
  }
}


/**
 * We need to create a (unique) fresh local address (IP+port).
 * Fill one in.
 *
 * @param af desired address family
 * @param proto desired protocol (IPPROTO_UDP or IPPROTO_TCP)
 * @param local_address address to initialize
 */
static void
setup_fresh_address (int af,
		     uint8_t proto,
		     struct SocketAddress *local_address)
{
  local_address->af = af;
  local_address->proto = (uint8_t) proto;
  /* default "local" port range is often 32768--61000,
     so we pick a random value in that range */	 
  if (proto == IPPROTO_ICMP)
    local_address->port = 0;
  else
    local_address->port 
      = (uint16_t) 32768 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
						     28232);      
  switch (af)
  {
  case AF_INET:
    {
      struct in_addr addr;
      struct in_addr mask;
      struct in_addr rnd;

      addr = exit_ipv4addr;
      mask = exit_ipv4mask;
      if (0 == ~mask.s_addr)
      {
	/* only one valid IP anyway */
	local_address->address.ipv4 = addr;
	return;
      }
      /* Given 192.168.0.1/255.255.0.0, we want a mask 
	 of '192.168.255.255', thus:  */
      mask.s_addr = addr.s_addr | ~mask.s_addr;
      /* Pick random IPv4 address within the subnet, except 'addr' or 'mask' itself */
      do
	{
	  rnd.s_addr = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
						 UINT32_MAX);	
	  local_address->address.ipv4.s_addr = (addr.s_addr | rnd.s_addr) & mask.s_addr;
	}
      while ( (local_address->address.ipv4.s_addr == addr.s_addr) ||
	      (local_address->address.ipv4.s_addr == mask.s_addr) );
    }
    break;
  case AF_INET6:
    {
      struct in6_addr addr;
      struct in6_addr mask;
      struct in6_addr rnd;
      int i;
      
      addr = exit_ipv6addr;
      GNUNET_assert (ipv6prefix < 128);
      if (ipv6prefix == 127)
      {
	/* only one valid IP anyway */
	local_address->address.ipv6 = addr;
	return;
      }
      /* Given ABCD::/96, we want a mask of 'ABCD::FFFF:FFFF,
	 thus: */
      mask = addr;
      for (i=127;i>=128-ipv6prefix;i--)
	mask.s6_addr[i / 8] |= (1 << (i % 8));
      
      /* Pick random IPv6 address within the subnet, except 'addr' or 'mask' itself */
      do
	{
	  for (i=0;i<16;i++)
	  {
	    rnd.s6_addr[i] = (unsigned char) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
								       256);
	    local_address->address.ipv6.s6_addr[i]
	      = (addr.s6_addr[i] | rnd.s6_addr[i]) & mask.s6_addr[i];
	  }
	}
      while ( (0 == memcmp (&local_address->address.ipv6,
			    &addr,
			    sizeof (struct in6_addr))) ||
	      (0 == memcmp (&local_address->address.ipv6,
			    &mask,
			    sizeof (struct in6_addr))) );
    }
    break;
  default:
    GNUNET_assert (0);
  }  
}


/**
 * We are starting a fresh connection (TCP or UDP) and need
 * to pick a source port and IP address (within the correct
 * range and address family) to associate replies with the
 * connection / correct mesh tunnel.  This function generates
 * a "fresh" source IP and source port number for a connection
 * After picking a good source address, this function sets up
 * the state in the 'connections_map' and 'connections_heap'
 * to allow finding the state when needed later.  The function
 * also makes sure that we remain within memory limits by
 * cleaning up 'old' states.
 *
 * @param state skeleton state to setup a record for; should
 *              'state->ri.remote_address' filled in so that
 *              this code can determine which AF/protocol is
 *              going to be used (the 'tunnel' should also
 *              already be set); after calling this function,
 *              heap_node and the local_address will be
 *              also initialized (heap_node != NULL can be
 *              used to test if a state has been fully setup).
 */
static void
setup_state_record (struct TunnelState *state)
{
  GNUNET_HashCode key;
  struct TunnelState *s;

  /* generate fresh, unique address */
  do
  {
    if (NULL == state->serv)
      setup_fresh_address (state->ri.remote_address.af,
			   state->ri.remote_address.proto,
			   &state->ri.local_address);
    else
      setup_fresh_address (state->serv->address.af,
			   state->serv->address.proto,
			   &state->ri.local_address);
  } while (NULL != get_redirect_state (state->ri.remote_address.af,
				       state->ri.remote_address.proto,
				       &state->ri.remote_address.address,
				       state->ri.remote_address.port,
				       &state->ri.local_address.address,
				       state->ri.local_address.port,
				       &key));
  {
    char buf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Picked local address %s:%u for new connection\n",
		inet_ntop (state->ri.local_address.af, 
			   &state->ri.local_address.address,
			   buf, sizeof (buf)),
		(unsigned int) state->ri.local_address.port);
  }
  state->state_key = key;
  GNUNET_assert (GNUNET_OK ==
		 GNUNET_CONTAINER_multihashmap_put (connections_map, 
						    &key, state,
						    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  state->heap_node = GNUNET_CONTAINER_heap_insert (connections_heap,
						   state,
						   GNUNET_TIME_absolute_get ().abs_value);   
  while (GNUNET_CONTAINER_heap_get_size (connections_heap) > max_connections)
  {
    s = GNUNET_CONTAINER_heap_remove_root (connections_heap);
    GNUNET_assert (state != s);
    s->heap_node = NULL;
    GNUNET_MESH_tunnel_destroy (s->tunnel);
    GNUNET_assert (GNUNET_OK ==
		   GNUNET_CONTAINER_multihashmap_remove (connections_map,
							 &s->state_key, 
							 s));
    GNUNET_free (s);
  }
}


/**
 * Prepare an IPv4 packet for transmission via the TUN interface.
 * Initializes the IP header and calculates checksums (IP+UDP/TCP).
 * For UDP, the UDP header will be fully created, whereas for TCP
 * only the ports and checksum will be filled in.  So for TCP,
 * a skeleton TCP header must be part of the provided payload.
 *
 * @param payload payload of the packet (starting with UDP payload or
 *                TCP header, depending on protocol)
 * @param payload_length number of bytes in 'payload'
 * @param protocol IPPROTO_UDP or IPPROTO_TCP
 * @param src_address source address to use (IP and port)
 * @param dst_address destination address to use (IP and port)
 * @param pkt6 where to write the assembled packet; must
 *        contain enough space for the IP header, UDP/TCP header
 *        AND the payload
 */
static void
prepare_ipv4_packet (const void *payload, size_t payload_length,
		     int protocol,
		     const struct GNUNET_TUN_TcpHeader *tcp_header,
		     const struct SocketAddress *src_address,
		     const struct SocketAddress *dst_address,
		     struct GNUNET_TUN_IPv4Header *pkt4)
{
  size_t len;

  len = payload_length;
  switch (protocol)
  {
  case IPPROTO_UDP:
    len += sizeof (struct GNUNET_TUN_UdpHeader);
    break;
  case IPPROTO_TCP:
    len += sizeof (struct GNUNET_TUN_TcpHeader);
    GNUNET_assert (NULL != tcp_header);
    break;
  default:
    GNUNET_break (0);
    return;
  }
  if (len + sizeof (struct GNUNET_TUN_IPv4Header) > UINT16_MAX)
  {
    GNUNET_break (0);
    return;
  }

  GNUNET_TUN_initialize_ipv4_header (pkt4,
				     protocol,
				     len,
				     &src_address->address.ipv4,
				     &dst_address->address.ipv4);
  switch (protocol)
  {
  case IPPROTO_UDP:
    {
      struct GNUNET_TUN_UdpHeader *pkt4_udp = (struct GNUNET_TUN_UdpHeader *) &pkt4[1];

      pkt4_udp->spt = htons (src_address->port);
      pkt4_udp->dpt = htons (dst_address->port);
      pkt4_udp->len = htons ((uint16_t) payload_length);
      GNUNET_TUN_calculate_udp4_checksum (pkt4,
					  pkt4_udp,
					  payload, payload_length);
      memcpy (&pkt4_udp[1], payload, payload_length);
    }
    break;
  case IPPROTO_TCP:
    {
      struct GNUNET_TUN_TcpHeader *pkt4_tcp = (struct GNUNET_TUN_TcpHeader *) &pkt4[1];
      
      memcpy (pkt4_tcp, tcp_header, sizeof (struct GNUNET_TUN_TcpHeader));
      pkt4_tcp->spt = htons (src_address->port);
      pkt4_tcp->dpt = htons (dst_address->port);
      GNUNET_TUN_calculate_tcp4_checksum (pkt4,
					  pkt4_tcp,
					  payload,
					  payload_length);
      memcpy (&pkt4_tcp[1], payload, payload_length);
    }
    break;
  default:
    GNUNET_assert (0);
  }
}


/**
 * Prepare an IPv6 packet for transmission via the TUN interface.
 * Initializes the IP header and calculates checksums (IP+UDP/TCP).
 * For UDP, the UDP header will be fully created, whereas for TCP
 * only the ports and checksum will be filled in.  So for TCP,
 * a skeleton TCP header must be part of the provided payload.
 *
 * @param payload payload of the packet (starting with UDP payload or
 *                TCP header, depending on protocol)
 * @param payload_length number of bytes in 'payload'
 * @param protocol IPPROTO_UDP or IPPROTO_TCP
 * @param src_address source address to use (IP and port)
 * @param dst_address destination address to use (IP and port)
 * @param pkt6 where to write the assembled packet; must
 *        contain enough space for the IP header, UDP/TCP header
 *        AND the payload
 */
static void
prepare_ipv6_packet (const void *payload, size_t payload_length,
		     int protocol,
		     const struct GNUNET_TUN_TcpHeader *tcp_header,
		     const struct SocketAddress *src_address,
		     const struct SocketAddress *dst_address,
		     struct GNUNET_TUN_IPv6Header *pkt6)
{
  size_t len;

  len = payload_length;
  switch (protocol)
  {
  case IPPROTO_UDP:
    len += sizeof (struct GNUNET_TUN_UdpHeader);
    break;
  case IPPROTO_TCP:
    /* tcp_header (with port/crc not set) must be part of payload! */
    if (len < sizeof (struct GNUNET_TUN_TcpHeader))
    {
      GNUNET_break (0);
      return;
    }
    break;
  default:
    GNUNET_break (0);
    return;
  }
  if (len > UINT16_MAX)
  {
    GNUNET_break (0);
    return;
  }

  GNUNET_TUN_initialize_ipv6_header (pkt6,
				     protocol,
				     len,
				     &dst_address->address.ipv6,
				     &src_address->address.ipv6);

  switch (protocol)
  {
  case IPPROTO_UDP:
    {
      struct GNUNET_TUN_UdpHeader *pkt6_udp = (struct GNUNET_TUN_UdpHeader *) &pkt6[1];

      pkt6_udp->spt = htons (src_address->port);
      pkt6_udp->dpt = htons (dst_address->port);
      pkt6_udp->len = htons ((uint16_t) payload_length);
      pkt6_udp->crc = 0;
      GNUNET_TUN_calculate_udp6_checksum (pkt6,
					  pkt6_udp,
					  payload,
					  payload_length);
      memcpy (&pkt6[1], payload, payload_length);
    }
    break;
  case IPPROTO_TCP:
    {
      struct GNUNET_TUN_TcpHeader *pkt6_tcp = (struct GNUNET_TUN_TcpHeader *) pkt6;

      /* memcpy first here as some TCP header fields are initialized this way! */
      memcpy (pkt6_tcp, payload, payload_length);
      pkt6_tcp->spt = htons (src_address->port);
      pkt6_tcp->dpt = htons (dst_address->port);
      GNUNET_TUN_calculate_tcp6_checksum (pkt6,
					  pkt6_tcp,
					  payload,
					  payload_length);
    }
    break;
  default:
    GNUNET_assert (0);
    break;
  }
}


/**
 * Send a TCP packet via the TUN interface.
 *
 * @param destination_address IP and port to use for the TCP packet's destination
 * @param source_address IP and port to use for the TCP packet's source
 * @param tcp header template to use
 * @param payload payload of the TCP packet
 * @param payload_length number of bytes in 'payload'
 */
static void
send_tcp_packet_via_tun (const struct SocketAddress *destination_address,
			 const struct SocketAddress *source_address,
			 const struct GNUNET_TUN_TcpHeader *tcp_header,
			 const void *payload, size_t payload_length)
{
  size_t len;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# TCP packets sent via TUN"),
			    1, GNUNET_NO);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Sending packet with %u bytes TCP payload via TUN\n",
	      (unsigned int) payload_length);
  len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader);
  switch (source_address->af)
  {
  case AF_INET:
    len += sizeof (struct GNUNET_TUN_IPv4Header);
    break;
  case AF_INET6:
    len += sizeof (struct GNUNET_TUN_IPv6Header);
    break;
  default:
    GNUNET_break (0);
    return;
  }
  len += sizeof (struct GNUNET_TUN_TcpHeader);
  len += payload_length;
  if (len >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return;
  }
  {
    char buf[len];
    struct GNUNET_MessageHeader *hdr;
    struct GNUNET_TUN_Layer2PacketHeader *tun;
    
    hdr = (struct GNUNET_MessageHeader *) buf;
    hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
    hdr->size = htons (len);
    tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1];
    tun->flags = htons (0);
    switch (source_address->af)
    {
    case AF_INET:
      {
	struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV4);
	prepare_ipv4_packet (payload, payload_length,
			     IPPROTO_TCP,
			     tcp_header, 
			     source_address,
			     destination_address,
			     ipv4);
      }
      break;
    case AF_INET6:
      {
	struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV6);
	prepare_ipv6_packet (payload, payload_length, 
			     IPPROTO_TCP,
			     tcp_header, 
			     source_address,
			     destination_address,
			     ipv6);
      }
      break;	
    default:
      GNUNET_assert (0);
      break;
    }
    (void) GNUNET_HELPER_send (helper_handle,
			       (const struct GNUNET_MessageHeader*) buf,
			       GNUNET_YES,
			       NULL, NULL);
  }
}


/**
 * Process a request via mesh to send a request to a TCP service
 * offered by this system.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_tcp_service (void *unused GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx GNUNET_UNUSED,
                     const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_TcpServiceStartMessage *start;
  uint16_t pkt_len = ntohs (message->size);

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# TCP service creation requests received via mesh"),
			    1, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  /* check that we got at least a valid header */
  if (pkt_len < sizeof (struct GNUNET_EXIT_TcpServiceStartMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  start = (const struct GNUNET_EXIT_TcpServiceStartMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_TcpServiceStartMessage);
  if ( (NULL == state) ||
       (NULL != state->serv) ||
       (NULL != state->heap_node) )
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  GNUNET_break_op (ntohl (start->reserved) == 0);
  /* setup fresh connection */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received data from %s for forwarding to TCP service %s on port %u\n",
	      GNUNET_i2s (sender),
	      GNUNET_h2s (&start->service_descriptor),
	      (unsigned int) ntohs (start->tcp_header.dpt));  
  if (NULL == (state->serv = find_service (tcp_services, &start->service_descriptor, 
					   ntohs (start->tcp_header.dpt))))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
		_("No service found for %s on port %d!\n"),
		"TCP",
		ntohs (start->tcp_header.dpt));
    GNUNET_STATISTICS_update (stats,
			      gettext_noop ("# TCP requests dropped (no such service)"),
			      1, GNUNET_NO);
    return GNUNET_SYSERR;
  }
  state->ri.remote_address = state->serv->address;    
  setup_state_record (state);
  send_tcp_packet_via_tun (&state->ri.remote_address,
			   &state->ri.local_address,
			   &start->tcp_header,
			   &start[1], pkt_len);
  return GNUNET_YES;
}


/**
 * Process a request to forward TCP data to the Internet via this peer.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_tcp_remote (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
                    void **tunnel_ctx GNUNET_UNUSED,
                    const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
                    const struct GNUNET_MessageHeader *message,
                    const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_TcpInternetStartMessage *start;
  uint16_t pkt_len = ntohs (message->size);
  const struct in_addr *v4;
  const struct in6_addr *v6;
  const void *payload;
  int af;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# TCP IP-exit creation requests received via mesh"),
			    1, GNUNET_NO);
  if (pkt_len < sizeof (struct GNUNET_EXIT_TcpInternetStartMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  start = (const struct GNUNET_EXIT_TcpInternetStartMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_TcpInternetStartMessage);  
  if ( (NULL == state) ||
       (NULL != state->serv) ||
       (NULL != state->heap_node) )
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  af = (int) ntohl (start->af);
  state->ri.remote_address.af = af;
  switch (af)
  {
  case AF_INET:
    if (pkt_len < sizeof (struct in_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv4_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v4 = (const struct in_addr*) &start[1];
    payload = &v4[1];
    pkt_len -= sizeof (struct in_addr);
    state->ri.remote_address.address.ipv4 = *v4;
    break;
  case AF_INET6:
    if (pkt_len < sizeof (struct in6_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv6_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v6 = (const struct in6_addr*) &start[1];
    payload = &v6[1];
    pkt_len -= sizeof (struct in6_addr);
    state->ri.remote_address.address.ipv6 = *v6;
    break;
  default:
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  {
    char buf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received data from %s for starting TCP stream to %s:%u\n",
		GNUNET_i2s (sender),
		inet_ntop (af, 
			   &state->ri.remote_address.address,
			   buf, sizeof (buf)),
		(unsigned int) ntohs (start->tcp_header.dpt));  
  }

  state->ri.remote_address.proto = IPPROTO_TCP;
  state->ri.remote_address.port = ntohs (start->tcp_header.dpt);
  setup_state_record (state);
  send_tcp_packet_via_tun (&state->ri.remote_address,
			   &state->ri.local_address,
			   &start->tcp_header,
			   payload, pkt_len);
  return GNUNET_YES;
}


/**
 * Process a request to forward TCP data on an established 
 * connection via this peer.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_tcp_data (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
		  void **tunnel_ctx GNUNET_UNUSED,
		  const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
		  const struct GNUNET_MessageHeader *message,
		  const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_TcpDataMessage *data;
  uint16_t pkt_len = ntohs (message->size);

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# TCP data requests received via mesh"),
			    1, GNUNET_NO);
  if (pkt_len < sizeof (struct GNUNET_EXIT_TcpDataMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  data = (const struct GNUNET_EXIT_TcpDataMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_TcpDataMessage);  
  if ( (NULL == state) ||
       (NULL == state->heap_node) )
  {
    /* connection should have been up! */
    GNUNET_STATISTICS_update (stats,
			      gettext_noop ("# TCP DATA requests dropped (no session)"),
			      1, GNUNET_NO);
    return GNUNET_SYSERR;
  }
  GNUNET_break_op (ntohl (data->reserved) == 0);
  {
    char buf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received additional %u bytes of data from %s for TCP stream to %s:%u\n",
		pkt_len,
		GNUNET_i2s (sender),
		inet_ntop (state->ri.remote_address.af, 
			   &state->ri.remote_address.address,
			   buf, sizeof (buf)),
		(unsigned int) state->ri.remote_address.port);
  }

  send_tcp_packet_via_tun (&state->ri.remote_address,
			   &state->ri.local_address,
			   &data->tcp_header,
			   &data[1], pkt_len);
  return GNUNET_YES;
}


/**
 * Send an ICMP packet via the TUN interface.
 *
 * @param destination_address IP to use for the ICMP packet's destination
 * @param source_address IP to use for the ICMP packet's source
 * @param icmp_header ICMP header to send
 * @param payload payload of the ICMP packet (does NOT include ICMP header)
 * @param payload_length number of bytes of data in payload
 */
static void
send_icmp_packet_via_tun (const struct SocketAddress *destination_address,
			  const struct SocketAddress *source_address,
			  const struct GNUNET_TUN_IcmpHeader *icmp_header,
			  const void *payload, size_t payload_length)
{
  size_t len;
  struct GNUNET_TUN_IcmpHeader *icmp;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# ICMP packets sent via TUN"),
			    1, GNUNET_NO);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Sending packet with %u bytes ICMP payload via TUN\n",
	      (unsigned int) payload_length);
  len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader);
  switch (destination_address->af)
  {
  case AF_INET:
    len += sizeof (struct GNUNET_TUN_IPv4Header);
    break;
  case AF_INET6:
    len += sizeof (struct GNUNET_TUN_IPv6Header);
    break;
  default:
    GNUNET_break (0);
    return;
  }
  len += sizeof (struct GNUNET_TUN_IcmpHeader);
  len += payload_length;
  if (len >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return;
  }
  {
    char buf[len];
    struct GNUNET_MessageHeader *hdr;
    struct GNUNET_TUN_Layer2PacketHeader *tun;
    
    hdr= (struct GNUNET_MessageHeader *) buf;
    hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
    hdr->size = htons (len);
    tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1];
    tun->flags = htons (0);
    switch (source_address->af)
    {
    case AF_INET:
      {
	struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV4);
	GNUNET_TUN_initialize_ipv4_header (ipv4,
					   IPPROTO_ICMP,
					   sizeof (struct GNUNET_TUN_IcmpHeader) + payload_length,
					   &source_address->address.ipv4,
					   &destination_address->address.ipv4);
	icmp = (struct GNUNET_TUN_IcmpHeader*) &ipv4[1];
      }
      break;
    case AF_INET6:
      {
	struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV6);
	GNUNET_TUN_initialize_ipv6_header (ipv6,
					   IPPROTO_ICMP,
					   sizeof (struct GNUNET_TUN_IcmpHeader) + payload_length,
					   &source_address->address.ipv6,
					   &destination_address->address.ipv6);
	icmp = (struct GNUNET_TUN_IcmpHeader*) &ipv6[1];
      }
      break;	
    default:
      GNUNET_assert (0);
      break;
    }
    *icmp = *icmp_header;
    memcpy (&icmp[1],
	    payload,
	    payload_length);
    GNUNET_TUN_calculate_icmp_checksum (icmp,
					payload,
					payload_length);
    (void) GNUNET_HELPER_send (helper_handle,
			       (const struct GNUNET_MessageHeader*) buf,
			       GNUNET_YES,
			       NULL, NULL);
  }
}


/**
 * Synthesize a plausible ICMP payload for an ICMPv4 error
 * response on the given tunnel.
 *
 * @param state tunnel information
 * @param ipp IPv6 header to fill in (ICMP payload)
 * @param udp "UDP" header to fill in (ICMP payload); might actually
 *            also be the first 8 bytes of the TCP header
 */
static void
make_up_icmpv4_payload (struct TunnelState *state,
			struct GNUNET_TUN_IPv4Header *ipp,
			struct GNUNET_TUN_UdpHeader *udp)
{
  GNUNET_TUN_initialize_ipv4_header (ipp,
				     state->ri.remote_address.proto,
				     sizeof (struct GNUNET_TUN_TcpHeader),
				     &state->ri.remote_address.address.ipv4,
				     &state->ri.local_address.address.ipv4);
  udp->spt = htons (state->ri.remote_address.port);
  udp->dpt = htons (state->ri.local_address.port);
  udp->len = htons (0);
  udp->crc = htons (0);
}


/**
 * Synthesize a plausible ICMP payload for an ICMPv6 error
 * response on the given tunnel.
 *
 * @param state tunnel information
 * @param ipp IPv6 header to fill in (ICMP payload)
 * @param udp "UDP" header to fill in (ICMP payload); might actually
 *            also be the first 8 bytes of the TCP header
 */
static void
make_up_icmpv6_payload (struct TunnelState *state,
			struct GNUNET_TUN_IPv6Header *ipp,
			struct GNUNET_TUN_UdpHeader *udp)
{
  GNUNET_TUN_initialize_ipv6_header (ipp,
				     state->ri.remote_address.proto,
				     sizeof (struct GNUNET_TUN_TcpHeader),
				     &state->ri.remote_address.address.ipv6,
				     &state->ri.local_address.address.ipv6);
  udp->spt = htons (state->ri.remote_address.port);
  udp->dpt = htons (state->ri.local_address.port);
  udp->len = htons (0);
  udp->crc = htons (0);
}


/**
 * Process a request to forward ICMP data to the Internet via this peer.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_icmp_remote (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
		     void **tunnel_ctx GNUNET_UNUSED,
		     const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
		     const struct GNUNET_MessageHeader *message,
		     const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_IcmpInternetMessage *msg;
  uint16_t pkt_len = ntohs (message->size);
  const struct in_addr *v4;
  const struct in6_addr *v6;  
  const void *payload;
  char buf[sizeof (struct GNUNET_TUN_IPv6Header) + 8];
  int af;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# ICMP IP-exit requests received via mesh"),
			    1, GNUNET_NO);
  if (pkt_len < sizeof (struct GNUNET_EXIT_IcmpInternetMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  msg = (const struct GNUNET_EXIT_IcmpInternetMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_IcmpInternetMessage);  

  af = (int) ntohl (msg->af);
  if ( (NULL != state->heap_node) &&
       (af != state->ri.remote_address.af) )
  {
    /* other peer switched AF on this tunnel; not allowed */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  switch (af)
  {
  case AF_INET:
    if (pkt_len < sizeof (struct in_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv4_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v4 = (const struct in_addr*) &msg[1];
    payload = &v4[1];
    pkt_len -= sizeof (struct in_addr);
    state->ri.remote_address.address.ipv4 = *v4;
    if (NULL == state->heap_node)
    {
      state->ri.remote_address.af = af;
      state->ri.remote_address.proto = IPPROTO_ICMP;
      setup_state_record (state);
    }
    /* check that ICMP type is something we want to support 
       and possibly make up payload! */
    switch (msg->icmp_header.type)
    {
    case GNUNET_TUN_ICMPTYPE_ECHO_REPLY:
    case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST:
      break;
    case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE:
    case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH:
    case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED:
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      /* make up payload */
      {
	struct GNUNET_TUN_IPv4Header *ipp = (struct GNUNET_TUN_IPv4Header *) buf;
	struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *) &ipp[1];

	GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader));
	pkt_len = sizeof (struct GNUNET_TUN_IPv4Header) + 8;
	make_up_icmpv4_payload (state, 
				ipp,
				udp);
	payload = ipp;
      }
      break;
    default:
      GNUNET_break_op (0);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# ICMPv4 packets dropped (type not allowed)"),
				1, GNUNET_NO);
      return GNUNET_SYSERR;      
    }
    /* end AF_INET */
    break;
  case AF_INET6:
    if (pkt_len < sizeof (struct in6_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv6_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v6 = (const struct in6_addr*) &msg[1];
    payload = &v6[1];
    pkt_len -= sizeof (struct in6_addr);
    state->ri.remote_address.address.ipv6 = *v6;
    if (NULL == state->heap_node)
    {
      state->ri.remote_address.af = af;
      state->ri.remote_address.proto = IPPROTO_ICMP;
      setup_state_record (state);
    }
    /* check that ICMP type is something we want to support 
       and possibly make up payload! */
    switch (msg->icmp_header.type)
    {
    case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY:
    case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST:
      break;
    case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE:
    case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG:
    case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED:
    case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM:
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      /* make up payload */
      {
	struct GNUNET_TUN_IPv6Header *ipp = (struct GNUNET_TUN_IPv6Header *) buf;
	struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *) &ipp[1];

	GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader));
	pkt_len = sizeof (struct GNUNET_TUN_IPv6Header) + 8;
	make_up_icmpv6_payload (state, 
				ipp,
				udp);
	payload = ipp;
      }
      break;
    default:
      GNUNET_break_op (0);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# ICMPv6 packets dropped (type not allowed)"),
				1, GNUNET_NO);
      return GNUNET_SYSERR;      
    }
    /* end AF_INET6 */
    break;    
  default:
    /* bad AF */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
 
  {
    char buf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received ICMP data from %s for forwarding to %s\n",
		GNUNET_i2s (sender),
		inet_ntop (af, 
			   &state->ri.remote_address.address,
			   buf, sizeof (buf)));
  }
  send_icmp_packet_via_tun (&state->ri.remote_address,
			    &state->ri.local_address,
			    &msg->icmp_header,
			    payload, pkt_len);
  return GNUNET_YES;
}


/**
 * Setup ICMP payload for ICMP error messages. Called
 * for both IPv4 and IPv6 addresses.
 *
 * @param state context for creating the IP Packet
 * @param buf where to create the payload, has at least
 *       sizeof (struct GNUNET_TUN_IPv6Header) + 8 bytes
 * @return number of bytes of payload we created in buf
 */
static uint16_t
make_up_icmp_service_payload (struct TunnelState *state,
			      char *buf)
{
  switch (state->serv->address.af)
  {
  case AF_INET:
    {
      struct GNUNET_TUN_IPv4Header *ipv4;
      struct GNUNET_TUN_UdpHeader *udp;
      
      ipv4 = (struct GNUNET_TUN_IPv4Header *)buf;
      udp = (struct GNUNET_TUN_UdpHeader *) &ipv4[1];
      make_up_icmpv4_payload (state,
			      ipv4,
			      udp);
      GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader));
      return sizeof (struct GNUNET_TUN_IPv4Header) + 8;
    }
    break;
  case AF_INET6:
    {
      struct GNUNET_TUN_IPv6Header *ipv6;
      struct GNUNET_TUN_UdpHeader *udp;

      ipv6 = (struct GNUNET_TUN_IPv6Header *)buf;
      udp = (struct GNUNET_TUN_UdpHeader *) &ipv6[1];
      make_up_icmpv6_payload (state,
			      ipv6,
			      udp);
      GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader));
      return sizeof (struct GNUNET_TUN_IPv6Header) + 8;      
    }
    break;
  default:
    GNUNET_break (0);
  }
  return 0;
}


/**
 * Process a request via mesh to send ICMP data to a service
 * offered by this system.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_icmp_service (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
		      void **tunnel_ctx,
		      const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
		      const struct GNUNET_MessageHeader *message,
		      const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_IcmpServiceMessage *msg;
  uint16_t pkt_len = ntohs (message->size);
  struct GNUNET_TUN_IcmpHeader icmp;
  char buf[sizeof (struct GNUNET_TUN_IPv6Header) + 8];
  const void *payload;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# ICMP service requests received via mesh"),
			    1, GNUNET_NO);
  /* check that we got at least a valid header */
  if (pkt_len < sizeof (struct GNUNET_EXIT_IcmpServiceMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  msg = (const struct GNUNET_EXIT_IcmpServiceMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_IcmpServiceMessage);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received data from %s for forwarding to ICMP service %s\n",
	      GNUNET_i2s (sender),
	      GNUNET_h2s (&msg->service_descriptor));
  if (NULL == state->serv)
  {
    /* first packet to service must not be ICMP (cannot determine service!) */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  icmp = msg->icmp_header;
  payload = &msg[1];
  state->ri.remote_address = state->serv->address;    
  setup_state_record (state);

  /* check that ICMP type is something we want to support,
     perform ICMP PT if needed ans possibly make up payload */
  switch (msg->af)
  {
  case AF_INET:
    switch (msg->icmp_header.type)
    {
    case GNUNET_TUN_ICMPTYPE_ECHO_REPLY:
      if (state->serv->address.af == AF_INET6)
	icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REPLY;
      break;
    case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST:
      if (state->serv->address.af == AF_INET6)
	icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST;
      break;
    case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE:
      if (state->serv->address.af == AF_INET6)
	icmp.type = GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE;
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED:
      if (state->serv->address.af == AF_INET6)
	icmp.type = GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED;
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH:
      if (state->serv->address.af == AF_INET6)
      {
	GNUNET_STATISTICS_update (stats,
				  gettext_noop ("# ICMPv4 packets dropped (impossible PT to v6)"),
				  1, GNUNET_NO);
	return GNUNET_OK;
      }
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    default:
      GNUNET_break_op (0);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# ICMPv4 packets dropped (type not allowed)"),
				1, GNUNET_NO);
      return GNUNET_SYSERR;
    }
    /* end of AF_INET */
    break;
  case AF_INET6:
    switch (msg->icmp_header.type)
    {
    case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY:
      if (state->serv->address.af == AF_INET)
	icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REPLY;
      break;
    case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST:
      if (state->serv->address.af == AF_INET)
	icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REQUEST;
      break;
    case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE:
      if (state->serv->address.af == AF_INET)
	icmp.type = GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE;
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED:
      if (state->serv->address.af == AF_INET)
	icmp.type = GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED;
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG:
    case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM:
      if (state->serv->address.af == AF_INET)
      {
	GNUNET_STATISTICS_update (stats,
				  gettext_noop ("# ICMPv6 packets dropped (impossible PT to v4)"),
				  1, GNUNET_NO);
	return GNUNET_OK;
      }
      if (0 != pkt_len)
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      payload = buf;
      pkt_len = make_up_icmp_service_payload (state, buf);
      break;
    default:
      GNUNET_break_op (0);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# ICMPv6 packets dropped (type not allowed)"),
				1, GNUNET_NO);
      return GNUNET_SYSERR;
    }
    /* end of AF_INET6 */
    break;
  default:
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  send_icmp_packet_via_tun (&state->ri.remote_address,
			    &state->ri.local_address,
			    &icmp,
			    payload, pkt_len);
  return GNUNET_YES;
}


/**
 * Send a UDP packet via the TUN interface.
 *
 * @param destination_address IP and port to use for the UDP packet's destination
 * @param source_address IP and port to use for the UDP packet's source
 * @param payload payload of the UDP packet (does NOT include UDP header)
 * @param payload_length number of bytes of data in payload
 */
static void
send_udp_packet_via_tun (const struct SocketAddress *destination_address,
			 const struct SocketAddress *source_address,
			 const void *payload, size_t payload_length)
{
  size_t len;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# UDP packets sent via TUN"),
			    1, GNUNET_NO);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Sending packet with %u bytes UDP payload via TUN\n",
	      (unsigned int) payload_length);
  len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader);
  switch (source_address->af)
  {
  case AF_INET:
    len += sizeof (struct GNUNET_TUN_IPv4Header);
    break;
  case AF_INET6:
    len += sizeof (struct GNUNET_TUN_IPv6Header);
    break;
  default:
    GNUNET_break (0);
    return;
  }
  len += sizeof (struct GNUNET_TUN_UdpHeader);
  len += payload_length;
  if (len >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return;
  }
  {
    char buf[len];
    struct GNUNET_MessageHeader *hdr;
    struct GNUNET_TUN_Layer2PacketHeader *tun;
    
    hdr= (struct GNUNET_MessageHeader *) buf;
    hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
    hdr->size = htons (len);
    tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1];
    tun->flags = htons (0);
    switch (source_address->af)
    {
    case AF_INET:
      {
	struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV4);
	prepare_ipv4_packet (payload, payload_length,
			     IPPROTO_UDP,
			     NULL,
			     source_address,
			     destination_address,
			     ipv4);
      }
      break;
    case AF_INET6:
      {
	struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*) &tun[1];
	
	tun->proto = htons (ETH_P_IPV6);
	prepare_ipv6_packet (payload, payload_length, 
			     IPPROTO_UDP,
			     NULL,
			     source_address,
			     destination_address,
			     ipv6);
      }
      break;	
    default:
      GNUNET_assert (0);
      break;
    }
    (void) GNUNET_HELPER_send (helper_handle,
			       (const struct GNUNET_MessageHeader*) buf,
			       GNUNET_YES,
			       NULL, NULL);
  }
}


/**
 * Process a request to forward UDP data to the Internet via this peer.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_udp_remote (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
                    void **tunnel_ctx GNUNET_UNUSED,
                    const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
                    const struct GNUNET_MessageHeader *message,
                    const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_UdpInternetMessage *msg;
  uint16_t pkt_len = ntohs (message->size);
  const struct in_addr *v4;
  const struct in6_addr *v6;
  const void *payload;
  int af;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# UDP IP-exit requests received via mesh"),
			    1, GNUNET_NO);
  if (pkt_len < sizeof (struct GNUNET_EXIT_UdpInternetMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  msg = (const struct GNUNET_EXIT_UdpInternetMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_UdpInternetMessage);  
  af = (int) ntohl (msg->af);
  state->ri.remote_address.af = af;
  switch (af)
  {
  case AF_INET:
    if (pkt_len < sizeof (struct in_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv4_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v4 = (const struct in_addr*) &msg[1];
    payload = &v4[1];
    pkt_len -= sizeof (struct in_addr);
    state->ri.remote_address.address.ipv4 = *v4;
    break;
  case AF_INET6:
    if (pkt_len < sizeof (struct in6_addr))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (! ipv6_exit)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    v6 = (const struct in6_addr*) &msg[1];
    payload = &v6[1];
    pkt_len -= sizeof (struct in6_addr);
    state->ri.remote_address.address.ipv6 = *v6;
    break;
  default:
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  {
    char buf[INET6_ADDRSTRLEN];
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Received data from %s for forwarding to UDP %s:%u\n",
		GNUNET_i2s (sender),
		inet_ntop (af, 
			   &state->ri.remote_address.address,
			   buf, sizeof (buf)),
		(unsigned int) ntohs (msg->destination_port));  
  }
  state->ri.remote_address.proto = IPPROTO_UDP;
  state->ri.remote_address.port = msg->destination_port;
  if (NULL == state->heap_node)
    setup_state_record (state);
  if (0 != ntohs (msg->source_port))
    state->ri.local_address.port = msg->source_port;
  send_udp_packet_via_tun (&state->ri.remote_address,
			   &state->ri.local_address,
			   payload, pkt_len);
  return GNUNET_YES;
}


/**
 * Process a request via mesh to send a request to a UDP service
 * offered by this system.
 *
 * @param cls closure, NULL
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to our 'struct TunnelState *'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
receive_udp_service (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
{
  struct TunnelState *state = *tunnel_ctx;
  const struct GNUNET_EXIT_UdpServiceMessage *msg;
  uint16_t pkt_len = ntohs (message->size);

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Bytes received from MESH"),
			    pkt_len, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# UDP service requests received via mesh"),
			    1, GNUNET_NO);
  /* check that we got at least a valid header */
  if (pkt_len < sizeof (struct GNUNET_EXIT_UdpServiceMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  msg = (const struct GNUNET_EXIT_UdpServiceMessage*) message;
  pkt_len -= sizeof (struct GNUNET_EXIT_UdpServiceMessage);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received data from %s for forwarding to UDP service %s on port %u\n",
	      GNUNET_i2s (sender),
	      GNUNET_h2s (&msg->service_descriptor),
	      (unsigned int) ntohs (msg->destination_port));  
  if (NULL == (state->serv = find_service (udp_services, &msg->service_descriptor, 
					   ntohs (msg->destination_port))))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
		_("No service found for %s on port %d!\n"),
		"UDP",
		ntohs (msg->destination_port));
    GNUNET_STATISTICS_update (stats,
			      gettext_noop ("# UDP requests dropped (no such service)"),
			      1, GNUNET_NO);
    return GNUNET_SYSERR;
  }
  state->ri.remote_address = state->serv->address;    
  setup_state_record (state);
  if (0 != ntohs (msg->source_port))
    state->ri.local_address.port = msg->source_port;
  send_udp_packet_via_tun (&state->ri.remote_address,
			   &state->ri.local_address,
			   &msg[1], pkt_len);
  return GNUNET_YES;
}


/**
 * Callback from GNUNET_MESH for new tunnels.
 *
 * @param cls closure
 * @param tunnel new handle to the tunnel
 * @param initiator peer that started the tunnel
 * @param atsi performance information for the tunnel
 * @return initial tunnel context for the tunnel
 */
static void *
new_tunnel (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
            const struct GNUNET_PeerIdentity *initiator GNUNET_UNUSED,
            const struct GNUNET_ATS_Information *ats GNUNET_UNUSED)
{
  struct TunnelState *s = GNUNET_malloc (sizeof (struct TunnelState));

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# Inbound MESH tunnels created"),
			    1, GNUNET_NO);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received inbound tunnel from `%s'\n",
	      GNUNET_i2s (initiator));
  s->tunnel = tunnel;
  return s;
}


/**
 * Function called by mesh whenever an inbound tunnel is destroyed.
 * Should clean up any associated state.
 *
 * @param cls closure (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end (henceforth invalid)
 * @param tunnel_ctx place where local state associated
 *                   with the tunnel is stored
 */
static void
clean_tunnel (void *cls GNUNET_UNUSED, const struct GNUNET_MESH_Tunnel *tunnel,
              void *tunnel_ctx)
{
  struct TunnelState *s = tunnel_ctx;
  struct TunnelMessageQueue *tnq;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Tunnel destroyed\n");
  while (NULL != (tnq = s->head))
  {
    GNUNET_CONTAINER_DLL_remove (s->head,
				 s->tail,
				 tnq);
    GNUNET_free (tnq);
  }
  if (s->heap_node != NULL)
  {
    GNUNET_assert (GNUNET_YES ==
		   GNUNET_CONTAINER_multihashmap_remove (connections_map,
							 &s->state_key,
							 s));
    GNUNET_CONTAINER_heap_remove_node (s->heap_node);
    s->heap_node = NULL;
  }
  if (NULL != s->th)
  {
    GNUNET_MESH_notify_transmit_ready_cancel (s->th);
    s->th = NULL;
  }
  GNUNET_free (s);
}


/**
 * Function that frees everything from a hashmap
 *
 * @param cls unused
 * @param hash key
 * @param value value to free
 */
static int
free_iterate (void *cls GNUNET_UNUSED,
              const GNUNET_HashCode * hash GNUNET_UNUSED, void *value)
{
  GNUNET_free (value);
  return GNUNET_YES;
}


/**
 * Function scheduled as very last function, cleans up after us
 */
static void
cleanup (void *cls GNUNET_UNUSED,
         const struct GNUNET_SCHEDULER_TaskContext *tskctx)
{
  unsigned int i;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Exit service is shutting down now\n");
  if (helper_handle != NULL)
  {
    GNUNET_HELPER_stop (helper_handle);
    helper_handle = NULL;
  }
  if (mesh_handle != NULL)
  {
    GNUNET_MESH_disconnect (mesh_handle);
    mesh_handle = NULL;
  }
  if (NULL != connections_map)
  {
    GNUNET_CONTAINER_multihashmap_iterate (connections_map, &free_iterate, NULL);
    GNUNET_CONTAINER_multihashmap_destroy (connections_map);
    connections_map = NULL;
  }
  if (NULL != connections_heap)
  {
    GNUNET_CONTAINER_heap_destroy (connections_heap);
    connections_heap = NULL;
  }
  if (NULL != tcp_services)
  {
    GNUNET_CONTAINER_multihashmap_iterate (tcp_services, &free_service_record, NULL);
    GNUNET_CONTAINER_multihashmap_destroy (tcp_services);
    tcp_services = NULL;
  }
  if (NULL != udp_services)
  {
    GNUNET_CONTAINER_multihashmap_iterate (udp_services, &free_service_record, NULL);
    GNUNET_CONTAINER_multihashmap_destroy (udp_services);
    udp_services = NULL;
  }
  if (stats != NULL)
  {
    GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
    stats = NULL;
  }
  for (i=0;i<8;i++)
    GNUNET_free_non_null (exit_argv[i]);
}


/**
 * Add services to the service map.
 *
 * @param proto IPPROTO_TCP or IPPROTO_UDP
 * @param cpy copy of the service descriptor (can be mutilated)
 * @param name DNS name of the service
 */
static void
add_services (int proto,
	      char *cpy,
	      const char *name)
{
  char *redirect;
  char *hostname;
  char *hostport;
  struct LocalService *serv;

  for (redirect = strtok (cpy, " "); redirect != NULL;
       redirect = strtok (NULL, " "))
  {
    if (NULL == (hostname = strstr (redirect, ":")))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "option `%s' for domain `%s' is not formatted correctly!\n",
		  redirect,
		  name);
      continue;
    }
    hostname[0] = '\0';
    hostname++;
    if (NULL == (hostport = strstr (hostname, ":")))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "option `%s' for domain `%s' is not formatted correctly!\n",
		  redirect,
		  name);
      continue;
    }
    hostport[0] = '\0';
    hostport++;
    
    int local_port = atoi (redirect);
    int remote_port = atoi (hostport);
    
    if (!((local_port > 0) && (local_port < 65536)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "`%s' is not a valid port number (for domain `%s')!", redirect,
		  name);
      continue;
    }
    if (!((remote_port > 0) && (remote_port < 65536)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "`%s' is not a valid port number (for domain `%s')!", hostport,
		  name);
      continue;
    }

    serv = GNUNET_malloc (sizeof (struct LocalService));
    serv->my_port = (uint16_t) local_port;
    serv->address.port = remote_port;
    if (0 == strcmp ("localhost4", hostname))
    {
      const char *ip4addr = exit_argv[4];

      serv->address.af = AF_INET;      
      GNUNET_assert (1 != inet_pton (AF_INET, ip4addr, &serv->address.address.ipv4));
    }
    else if (0 == strcmp ("localhost6", hostname))
    {
      const char *ip6addr = exit_argv[2];

      serv->address.af = AF_INET6;
      GNUNET_assert (1 == inet_pton (AF_INET6, ip6addr, &serv->address.address.ipv6));
    }
    else
    {
      struct addrinfo *res;      
      int ret;

      ret = getaddrinfo (hostname, NULL, NULL, &res);      
      if ( (ret != 0) || (res == NULL) )
      {
	GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		    _("No addresses found for hostname `%s' of service `%s'!\n"),
		    hostname,
		    name);
	GNUNET_free (serv);
	continue;
      }
      
      serv->address.af = res->ai_family;
      switch (res->ai_family)
      {
      case AF_INET:
	if (! ipv4_enabled)
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		      _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"),
		      name);
	  freeaddrinfo (res);
	  GNUNET_free (serv);
	  continue;
	}
	serv->address.address.ipv4 = ((struct sockaddr_in *) res->ai_addr)->sin_addr;
	break;
      case AF_INET6:
	if (! ipv6_enabled)
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		      _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"),
		      name);
	  freeaddrinfo (res);
	  GNUNET_free (serv);
	  continue;
	}	
	serv->address.address.ipv6 = ((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
	break;
      default:
	freeaddrinfo (res);
	GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		    _("No IP addresses found for hostname `%s' of service `%s'!\n"),
		    hostname,
		    name);
	GNUNET_free (serv);
	continue;
      }
      freeaddrinfo (res);
    }
    store_service ((IPPROTO_UDP == proto) ? udp_services : tcp_services,
		   name,
		   local_port,
		   serv);
  }
}


/**
 * Reads the configuration servicecfg and populates udp_services
 *
 * @param cls unused
 * @param section name of section in config, equal to hostname
 */
static void
read_service_conf (void *cls GNUNET_UNUSED, const char *section)
{
  char *cpy;

  if ((strlen (section) < 8) ||
      (0 != strcmp (".gnunet.", section + (strlen (section) - 8))))
    return;
  if (GNUNET_OK ==
      GNUNET_CONFIGURATION_get_value_string (cfg, section, "UDP_REDIRECTS",
					     &cpy))
  {
    add_services (IPPROTO_UDP, cpy, section);
    GNUNET_free (cpy);
  }
  if (GNUNET_OK ==
      GNUNET_CONFIGURATION_get_value_string (cfg, section, "TCP_REDIRECTS",
					     &cpy))
  {
    add_services (IPPROTO_TCP, cpy, section);
    GNUNET_free (cpy);
  }
}


/**
 * @brief Main function that will be run by the scheduler.
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param cfg_ configuration
 */
static void
run (void *cls, char *const *args GNUNET_UNUSED,
     const char *cfgfile GNUNET_UNUSED,
     const struct GNUNET_CONFIGURATION_Handle *cfg_)
{
  static struct GNUNET_MESH_MessageHandler handlers[] = {
    {&receive_icmp_service, GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_SERVICE, 0},
    {&receive_icmp_remote, GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_INTERNET, 0},
    {&receive_udp_service, GNUNET_MESSAGE_TYPE_VPN_UDP_TO_SERVICE, 0},
    {&receive_udp_remote, GNUNET_MESSAGE_TYPE_VPN_UDP_TO_INTERNET, 0},
    {&receive_tcp_service, GNUNET_MESSAGE_TYPE_VPN_TCP_TO_SERVICE_START, 0},
    {&receive_tcp_remote, GNUNET_MESSAGE_TYPE_VPN_TCP_TO_INTERNET_START, 0},
    {&receive_tcp_data, GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_EXIT, 0},
    {NULL, 0, 0}
  };

  static GNUNET_MESH_ApplicationType apptypes[] = {
    GNUNET_APPLICATION_TYPE_END,
    GNUNET_APPLICATION_TYPE_END,
    GNUNET_APPLICATION_TYPE_END
  };
  unsigned int app_idx;
  char *exit_ifname;
  char *tun_ifname;
  char *ipv6addr;
  char *ipv6prefix_s;
  char *ipv4addr;
  char *ipv4mask;

  cfg = cfg_;
  stats = GNUNET_STATISTICS_create ("exit", cfg);
  ipv4_exit = GNUNET_CONFIGURATION_get_value_yesno (cfg, "exit", "EXIT_IPV4");
  ipv6_exit = GNUNET_CONFIGURATION_get_value_yesno (cfg, "exit", "EXIT_IPV6"); 
  ipv4_enabled = GNUNET_CONFIGURATION_get_value_yesno (cfg, "exit", "ENABLE_IPV4");
  ipv6_enabled = GNUNET_CONFIGURATION_get_value_yesno (cfg, "exit", "ENABLE_IPV6"); 
  if (ipv4_exit && (! ipv4_enabled))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("Cannot enable IPv4 exit but disable IPv4 on TUN interface, will use ENABLE_IPv4=YES\n"));
    ipv4_enabled = GNUNET_YES;
  }
  if (ipv6_exit && (! ipv6_enabled))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("Cannot enable IPv6 exit but disable IPv6 on TUN interface, will use ENABLE_IPv6=YES\n"));
    ipv6_enabled = GNUNET_YES;
  }
  if (! (ipv4_enabled || ipv6_enabled))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("No useful service enabled.  Exiting.\n"));
    GNUNET_SCHEDULER_shutdown ();
    return;    
  }
  app_idx = 0;
  if (GNUNET_YES == ipv4_exit)    
  {
    apptypes[app_idx] = GNUNET_APPLICATION_TYPE_IPV4_GATEWAY;
    app_idx++;
  }
  if (GNUNET_YES == ipv6_exit)    
  {
    apptypes[app_idx] = GNUNET_APPLICATION_TYPE_IPV6_GATEWAY;
    app_idx++;
  }

  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (cfg, "exit", "MAX_CONNECTIONS",
                                             &max_connections))
    max_connections = 1024;
  exit_argv[0] = GNUNET_strdup ("exit-gnunet");
  if (GNUNET_SYSERR ==
      GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "TUN_IFNAME", &tun_ifname))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "No entry 'TUN_IFNAME' in configuration!\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  exit_argv[1] = tun_ifname;
  if (ipv4_enabled)
  {
    if (GNUNET_SYSERR ==
	GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "EXIT_IFNAME", &exit_ifname))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  "No entry 'EXIT_IFNAME' in configuration!\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
    exit_argv[2] = exit_ifname;
  }
  else
  {
    exit_argv[2] = GNUNET_strdup ("%");
  }
  if (GNUNET_YES == ipv6_enabled)
  {
    if ( (GNUNET_SYSERR ==
	  GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "IPV6ADDR",
						 &ipv6addr) ||
	  (1 != inet_pton (AF_INET6, ipv6addr, &exit_ipv6addr))) )
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  "No valid entry 'IPV6ADDR' in configuration!\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
    exit_argv[3] = ipv6addr;
    if (GNUNET_SYSERR ==
	GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "IPV6PREFIX",
					       &ipv6prefix_s))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  "No entry 'IPV6PREFIX' in configuration!\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
    exit_argv[4] = ipv6prefix_s;
    if ( (GNUNET_OK !=
	  GNUNET_CONFIGURATION_get_value_number (cfg, "exit",
						 "IPV6PREFIX",
						 &ipv6prefix)) ||
	 (ipv6prefix >= 127) )
    {
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  } 
  else
  {
    /* IPv6 explicitly disabled */
    exit_argv[3] = GNUNET_strdup ("-");
    exit_argv[4] = GNUNET_strdup ("-");
  }
  if (GNUNET_YES == ipv4_enabled)
  {
    if ( (GNUNET_SYSERR ==
	  GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "IPV4ADDR",
						 &ipv4addr) ||
	  (1 != inet_pton (AF_INET, ipv4addr, &exit_ipv4addr))) )
      {
	GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		    "No valid entry for 'IPV4ADDR' in configuration!\n");
	GNUNET_SCHEDULER_shutdown ();
	return;
      }
    exit_argv[5] = ipv4addr;
    if ( (GNUNET_SYSERR ==
	  GNUNET_CONFIGURATION_get_value_string (cfg, "exit", "IPV4MASK",
						 &ipv4mask) ||
	  (1 != inet_pton (AF_INET, ipv4mask, &exit_ipv4mask))) )
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  "No valid entry 'IPV4MASK' in configuration!\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
    exit_argv[6] = ipv4mask;
  }
  else
  {
    /* IPv4 explicitly disabled */
    exit_argv[5] = GNUNET_strdup ("-");
    exit_argv[6] = GNUNET_strdup ("-");
  }
  exit_argv[7] = NULL;

  udp_services = GNUNET_CONTAINER_multihashmap_create (65536);
  tcp_services = GNUNET_CONTAINER_multihashmap_create (65536);
  GNUNET_CONFIGURATION_iterate_sections (cfg, &read_service_conf, NULL);

  connections_map = GNUNET_CONTAINER_multihashmap_create (65536);
  connections_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
  mesh_handle 
    = GNUNET_MESH_connect (cfg, 42 /* queue size */, NULL, 
			   &new_tunnel, 
			   &clean_tunnel, handlers,
                           apptypes);
  if (NULL == mesh_handle)
  {
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  helper_handle = GNUNET_HELPER_start ("gnunet-helper-exit", 
				       exit_argv,
				       &message_token, NULL);
}


/**
 * The main function
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc, char *const *argv)
{
  static const struct GNUNET_GETOPT_CommandLineOption options[] = {
    GNUNET_GETOPT_OPTION_END
  };

  return (GNUNET_OK ==
          GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-exit",
                              gettext_noop
                              ("Daemon to run to provide an IP exit node for the VPN"),
                              options, &run, NULL)) ? 0 : 1;
}


/* end of gnunet-daemon-exit.c */