summaryrefslogtreecommitdiff
path: root/src/gns/gnunet-gns-proxy.c
blob: 35f42cdecaa875be7139f55f6662dde1a276841a (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
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
/*
     This file is part of GNUnet.
     Copyright (C) 2012-2014 GNUnet e.V.

     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., 51 Franklin Street, Fifth Floor,
     Boston, MA 02110-1301, USA.
*/
/**
 * @author Martin Schanzenbach
 * @author Christian Grothoff
 * @file src/gns/gnunet-gns-proxy.c
 * @brief HTTP(S) proxy that rewrites URIs and fakes certificats to make GNS work
 *        with legacy browsers
 *
 * TODO:
 * - double-check queueing logic
 */
#include "platform.h"
#include <microhttpd.h>
#if HAVE_CURL_CURL_H
#include <curl/curl.h>
#elif HAVE_GNURL_CURL_H
#include <gnurl/curl.h>
#endif
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>
#include <gnutls/crypto.h>
#if HAVE_GNUTLS_DANE
#include <gnutls/dane.h>
#endif
#include <regex.h>
#include "gnunet_util_lib.h"
#include "gnunet_gns_service.h"
#include "gnunet_identity_service.h"
#include "gns.h"


/**
 * Default Socks5 listen port.
 */
#define GNUNET_GNS_PROXY_PORT 7777

/**
 * Maximum supported length for a URI.
 * Should die. @deprecated
 */
#define MAX_HTTP_URI_LENGTH 2048

/**
 * Size of the buffer for the data upload / download.  Must be
 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
 */
#define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE

/**
 * Size of the read/write buffers for Socks.   Uses
 * 256 bytes for the hostname (at most), plus a few
 * bytes overhead for the messages.
 */
#define SOCKS_BUFFERSIZE (256 + 32)

/**
 * Port for plaintext HTTP.
 */
#define HTTP_PORT 80

/**
 * Port for HTTPS.
 */
#define HTTPS_PORT 443

/**
 * Largest allowed size for a PEM certificate.
 */
#define MAX_PEM_SIZE (10 * 1024)

/**
 * After how long do we clean up unused MHD SSL/TLS instances?
 */
#define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)

/**
 * After how long do we clean up Socks5 handles that failed to show any activity
 * with their respective MHD instance?
 */
#define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)


/**
 * Log curl error.
 *
 * @param level log level
 * @param fun name of curl_easy-function that gave the error
 * @param rc return code from curl
 */
#define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))


/* *************** Socks protocol definitions (move to TUN?) ****************** */

/**
 * Which SOCKS version do we speak?
 */
#define SOCKS_VERSION_5 0x05

/**
 * Flag to set for 'no authentication'.
 */
#define SOCKS_AUTH_NONE 0


/**
 * Commands in Socks5.
 */
enum Socks5Commands
{
  /**
   * Establish TCP/IP stream.
   */
  SOCKS5_CMD_TCP_STREAM = 1,

  /**
   * Establish TCP port binding.
   */
  SOCKS5_CMD_TCP_PORT = 2,

  /**
   * Establish UDP port binding.
   */
  SOCKS5_CMD_UDP_PORT = 3
};


/**
 * Address types in Socks5.
 */
enum Socks5AddressType
{
  /**
   * IPv4 address.
   */
  SOCKS5_AT_IPV4 = 1,

  /**
   * IPv4 address.
   */
  SOCKS5_AT_DOMAINNAME = 3,

  /**
   * IPv6 address.
   */
  SOCKS5_AT_IPV6 = 4

};


/**
 * Status codes in Socks5 response.
 */
enum Socks5StatusCode
{
  SOCKS5_STATUS_REQUEST_GRANTED = 0,
  SOCKS5_STATUS_GENERAL_FAILURE = 1,
  SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
  SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
  SOCKS5_STATUS_HOST_UNREACHABLE = 4,
  SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
  SOCKS5_STATUS_TTL_EXPIRED = 6,
  SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
  SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
};


/**
 * Client hello in Socks5 protocol.
 */
struct Socks5ClientHelloMessage
{
  /**
   * Should be #SOCKS_VERSION_5.
   */
  uint8_t version;

  /**
   * How many authentication methods does the client support.
   */
  uint8_t num_auth_methods;

  /* followed by supported authentication methods, 1 byte per method */

};


/**
 * Server hello in Socks5 protocol.
 */
struct Socks5ServerHelloMessage
{
  /**
   * Should be #SOCKS_VERSION_5.
   */
  uint8_t version;

  /**
   * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
   * which skips the authentication step.
   */
  uint8_t auth_method;
};


/**
 * Client socks request in Socks5 protocol.
 */
struct Socks5ClientRequestMessage
{
  /**
   * Should be #SOCKS_VERSION_5.
   */
  uint8_t version;

  /**
   * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
   */
  uint8_t command;

  /**
   * Reserved, always zero.
   */
  uint8_t resvd;

  /**
   * Address type, an `enum Socks5AddressType`.
   */
  uint8_t addr_type;

  /*
   * Followed by either an ip4/ipv6 address or a domain name with a
   * length field (uint8_t) in front (depending on @e addr_type).
   * followed by port number in network byte order (uint16_t).
   */
};


/**
 * Server response to client requests in Socks5 protocol.
 */
struct Socks5ServerResponseMessage
{
  /**
   * Should be #SOCKS_VERSION_5.
   */
  uint8_t version;

  /**
   * Status code, an `enum Socks5StatusCode`
   */
  uint8_t reply;

  /**
   * Always zero.
   */
  uint8_t reserved;

  /**
   * Address type, an `enum Socks5AddressType`.
   */
  uint8_t addr_type;

  /*
   * Followed by either an ip4/ipv6 address or a domain name with a
   * length field (uint8_t) in front (depending on @e addr_type).
   * followed by port number in network byte order (uint16_t).
   */

};



/* *********************** Datastructures for HTTP handling ****************** */

/**
 * A structure for CA cert/key
 */
struct ProxyCA
{
  /**
   * The certificate
   */
  gnutls_x509_crt_t cert;

  /**
   * The private key
   */
  gnutls_x509_privkey_t key;
};


/**
 * Structure for GNS certificates
 */
struct ProxyGNSCertificate
{
  /**
   * The certificate as PEM
   */
  char cert[MAX_PEM_SIZE];

  /**
   * The private key as PEM
   */
  char key[MAX_PEM_SIZE];
};



/**
 * A structure for all running Httpds
 */
struct MhdHttpList
{
  /**
   * DLL for httpds
   */
  struct MhdHttpList *prev;

  /**
   * DLL for httpds
   */
  struct MhdHttpList *next;

  /**
   * the domain name to server (only important for SSL)
   */
  char *domain;

  /**
   * The daemon handle
   */
  struct MHD_Daemon *daemon;

  /**
   * Optional proxy certificate used
   */
  struct ProxyGNSCertificate *proxy_cert;

  /**
   * The task ID
   */
  struct GNUNET_SCHEDULER_Task *httpd_task;

  /**
   * is this an ssl daemon?
   */
  int is_ssl;

};


/* ***************** Datastructures for Socks handling **************** */


/**
 * The socks phases.
 */
enum SocksPhase
{
  /**
   * We're waiting to get the client hello.
   */
  SOCKS5_INIT,

  /**
   * We're waiting to get the initial request.
   */
  SOCKS5_REQUEST,

  /**
   * We are currently resolving the destination.
   */
  SOCKS5_RESOLVING,

  /**
   * We're in transfer mode.
   */
  SOCKS5_DATA_TRANSFER,

  /**
   * Finish writing the write buffer, then clean up.
   */
  SOCKS5_WRITE_THEN_CLEANUP,

  /**
   * Socket has been passed to MHD, do not close it anymore.
   */
  SOCKS5_SOCKET_WITH_MHD,

  /**
   * We've started receiving upload data from MHD.
   */
  SOCKS5_SOCKET_UPLOAD_STARTED,

  /**
   * We've finished receiving upload data from MHD.
   */
  SOCKS5_SOCKET_UPLOAD_DONE,

  /**
   * We've finished uploading data via CURL and can now download.
   */
  SOCKS5_SOCKET_DOWNLOAD_STARTED,

  /**
   * We've finished receiving download data from cURL.
   */
  SOCKS5_SOCKET_DOWNLOAD_DONE
};


/**
 * A header list
 */
struct HttpResponseHeader
{
  /**
   * DLL
   */
  struct HttpResponseHeader *next;

  /**
   * DLL
   */
  struct HttpResponseHeader *prev;

  /**
   * Header type
   */
  char *type;

  /**
   * Header value
   */
  char *value;
};

/**
 * A structure for socks requests
 */
struct Socks5Request
{

  /**
   * DLL.
   */
  struct Socks5Request *next;

  /**
   * DLL.
   */
  struct Socks5Request *prev;

  /**
   * The client socket
   */
  struct GNUNET_NETWORK_Handle *sock;

  /**
   * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
   */
  struct GNUNET_GNS_LookupRequest *gns_lookup;

  /**
   * Client socket read task
   */
  struct GNUNET_SCHEDULER_Task * rtask;

  /**
   * Client socket write task
   */
  struct GNUNET_SCHEDULER_Task * wtask;

  /**
   * Timeout task
   */
  struct GNUNET_SCHEDULER_Task * timeout_task;

  /**
   * Read buffer
   */
  char rbuf[SOCKS_BUFFERSIZE];

  /**
   * Write buffer
   */
  char wbuf[SOCKS_BUFFERSIZE];

  /**
   * Buffer we use for moving data between MHD and curl (in both directions).
   */
  char io_buf[IO_BUFFERSIZE];

  /**
   * MHD HTTP instance handling this request, NULL for none.
   */
  struct MhdHttpList *hd;

  /**
   * MHD response object for this request.
   */
  struct MHD_Response *response;

  /**
   * the domain name to server (only important for SSL)
   */
  char *domain;

  /**
   * DNS Legacy Host Name as given by GNS, NULL if not given.
   */
  char *leho;

  /**
   * Payload of the (last) DANE record encountered.
   */
  char *dane_data;

  /**
   * The URL to fetch
   */
  char *url;

  /**
   * Handle to cURL
   */
  CURL *curl;

  /**
   * HTTP request headers for the curl request.
   */
  struct curl_slist *headers;

  /**
   * DNS->IP mappings resolved through GNS
   */
  struct curl_slist *hosts;

  /**
   * HTTP response code to give to MHD for the response.
   */
  unsigned int response_code;

  /**
   * Number of bytes in @e dane_data.
   */
  size_t dane_data_len;

  /**
   * Number of bytes already in read buffer
   */
  size_t rbuf_len;

  /**
   * Number of bytes already in write buffer
   */
  size_t wbuf_len;

  /**
   * Number of bytes already in the IO buffer.
   */
  size_t io_len;

  /**
   * Once known, what's the target address for the connection?
   */
  struct sockaddr_storage destination_address;

  /**
   * The socks state
   */
  enum SocksPhase state;

  /**
   * Desired destination port.
   */
  uint16_t port;

  /**
   * Headers from response
   */
  struct HttpResponseHeader *header_head;

  /**
   * Headers from response
   */
  struct HttpResponseHeader *header_tail;

  /**
   * SSL Certificate status
   */
  int ssl_checked;
};



/* *********************** Globals **************************** */


/**
 * The port the proxy is running on (default 7777)
 */
static unsigned long long port = GNUNET_GNS_PROXY_PORT;

/**
 * The CA file (pem) to use for the proxy CA
 */
static char *cafile_opt;

/**
 * The listen socket of the proxy for IPv4
 */
static struct GNUNET_NETWORK_Handle *lsock4;

/**
 * The listen socket of the proxy for IPv6
 */
static struct GNUNET_NETWORK_Handle *lsock6;

/**
 * The listen task ID for IPv4
 */
static struct GNUNET_SCHEDULER_Task * ltask4;

/**
 * The listen task ID for IPv6
 */
static struct GNUNET_SCHEDULER_Task * ltask6;

/**
 * The cURL download task (curl multi API).
 */
static struct GNUNET_SCHEDULER_Task * curl_download_task;

/**
 * The cURL multi handle
 */
static CURLM *curl_multi;

/**
 * Handle to the GNS service
 */
static struct GNUNET_GNS_Handle *gns_handle;

/**
 * DLL for http/https daemons
 */
static struct MhdHttpList *mhd_httpd_head;

/**
 * DLL for http/https daemons
 */
static struct MhdHttpList *mhd_httpd_tail;

/**
 * Daemon for HTTP (we have one per SSL certificate, and then one for
 * all HTTP connections; this is the one for HTTP, not HTTPS).
 */
static struct MhdHttpList *httpd;

/**
 * DLL of active socks requests.
 */
static struct Socks5Request *s5r_head;

/**
 * DLL of active socks requests.
 */
static struct Socks5Request *s5r_tail;

/**
 * The users local GNS master zone
 */
static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;

/**
 * The CA for SSL certificate generation
 */
static struct ProxyCA proxy_ca;

/**
 * Response we return on cURL failures.
 */
static struct MHD_Response *curl_failure_response;

/**
 * Connection to identity service.
 */
static struct GNUNET_IDENTITY_Handle *identity;

/**
 * Request for our ego.
 */
static struct GNUNET_IDENTITY_Operation *id_op;

/**
 * Our configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;


/* ************************* Global helpers ********************* */


/**
 * Run MHD now, we have extra data ready for the callback.
 *
 * @param hd the daemon to run now.
 */
static void
run_mhd_now (struct MhdHttpList *hd);


/**
 * Clean up s5r handles.
 *
 * @param s5r the handle to destroy
 */
static void
cleanup_s5r (struct Socks5Request *s5r)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Cleaning up socks request\n");
  if (NULL != s5r->curl)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Cleaning up cURL handle\n");
    curl_multi_remove_handle (curl_multi, s5r->curl);
    curl_easy_cleanup (s5r->curl);
    s5r->curl = NULL;
  }
  curl_slist_free_all (s5r->headers);
  if (NULL != s5r->hosts)
  {
    curl_slist_free_all (s5r->hosts);
  }
  if ( (NULL != s5r->response) &&
       (curl_failure_response != s5r->response) )
    MHD_destroy_response (s5r->response);
  if (NULL != s5r->rtask)
    GNUNET_SCHEDULER_cancel (s5r->rtask);
  if (NULL != s5r->timeout_task)
    GNUNET_SCHEDULER_cancel (s5r->timeout_task);
  if (NULL != s5r->wtask)
    GNUNET_SCHEDULER_cancel (s5r->wtask);
  if (NULL != s5r->gns_lookup)
    GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
  if (NULL != s5r->sock)
  {
    if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
      GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
    else
      GNUNET_NETWORK_socket_close (s5r->sock);
  }
  GNUNET_CONTAINER_DLL_remove (s5r_head,
			       s5r_tail,
			       s5r);
  GNUNET_free_non_null (s5r->domain);
  GNUNET_free_non_null (s5r->leho);
  GNUNET_free_non_null (s5r->url);
  GNUNET_free_non_null (s5r->dane_data);
  GNUNET_free (s5r);
}


/* ************************* HTTP handling with cURL *********************** */


/**
 * Callback for MHD response generation.  This function is called from
 * MHD whenever MHD expects to get data back.  Copies data from the
 * io_buf, if available.
 *
 * @param cls closure with our `struct Socks5Request`
 * @param pos in buffer
 * @param buf where to copy data
 * @param max available space in @a buf
 * @return number of bytes written to @a buf
 */
static ssize_t
mhd_content_cb (void *cls,
                uint64_t pos,
                char* buf,
                size_t max)
{
  struct Socks5Request *s5r = cls;
  size_t bytes_to_copy;

  if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
       (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
  {
    /* we're still not done with the upload, do not yet
       start the download, the IO buffer is still full
       with upload data. */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Pausing MHD download, not yet ready for download\n");
    return 0; /* not yet ready for data download */
  }
  bytes_to_copy = GNUNET_MIN (max,
			      s5r->io_len);
  if ( (0 == bytes_to_copy) &&
       (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Pausing MHD download, no data available\n");
    return 0; /* more data later */
  }
  if ( (0 == bytes_to_copy) &&
       (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Completed MHD download\n");
    return MHD_CONTENT_READER_END_OF_STREAM;
  }
  GNUNET_memcpy (buf, s5r->io_buf, bytes_to_copy);
  memmove (s5r->io_buf,
	   &s5r->io_buf[bytes_to_copy],
	   s5r->io_len - bytes_to_copy);
  s5r->io_len -= bytes_to_copy;
  if (NULL != s5r->curl)
    curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
  return bytes_to_copy;
}


/**
 * Check that the website has presented us with a valid SSL certificate.
 * The certificate must either match the domain name or the LEHO name
 * (or, if available, the TLSA record).
 *
 * @param s5r request to check for.
 * @return #GNUNET_OK if the certificate is valid
 */
static int
check_ssl_certificate (struct Socks5Request *s5r)
{
  unsigned int cert_list_size;
  const gnutls_datum_t *chainp;
  const struct curl_tlssessioninfo *tlsinfo;
  char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
  size_t size;
  gnutls_x509_crt_t x509_cert;
  int rc;
  const char *name;

  s5r->ssl_checked = GNUNET_YES;
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Checking SSL certificate\n");
  if (CURLE_OK !=
      curl_easy_getinfo (s5r->curl,
			 CURLINFO_TLS_SESSION,
			 (struct curl_slist **) &tlsinfo))
    return GNUNET_SYSERR;
  if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("Unsupported CURL SSL backend %d\n"),
                tlsinfo->backend);
    return GNUNET_SYSERR;
  }
  chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
  if ( (! chainp) || (0 == cert_list_size) )
    return GNUNET_SYSERR;

  size = sizeof (certdn);
  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init (&x509_cert);
  gnutls_x509_crt_import (x509_cert,
                          chainp,
                          GNUTLS_X509_FMT_DER);

  if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
                                                GNUTLS_OID_X520_COMMON_NAME,
                                                0, /* the first and only one */
                                                0 /* no DER encoding */,
                                                certdn,
                                                &size)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                _("Failed to fetch CN from cert: %s\n"),
                gnutls_strerror(rc));
    gnutls_x509_crt_deinit (x509_cert);
    return GNUNET_SYSERR;
  }
  /* check for TLSA/DANE records */
#if HAVE_GNUTLS_DANE
  if (NULL != s5r->dane_data)
  {
    char *dd[] = { s5r->dane_data, NULL };
    int dlen[] = { s5r->dane_data_len, 0};
    dane_state_t dane_state;
    dane_query_t dane_query;
    unsigned int verify;

    /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
    if (0 != (rc = dane_state_init (&dane_state,
#ifdef DANE_F_IGNORE_DNSSEC
                                    DANE_F_IGNORE_DNSSEC |
#endif
                                    DANE_F_IGNORE_LOCAL_RESOLVER)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Failed to initialize DANE: %s\n"),
                  dane_strerror(rc));
      gnutls_x509_crt_deinit (x509_cert);
      return GNUNET_SYSERR;
    }
    if (0 != (rc = dane_raw_tlsa (dane_state,
                                  &dane_query,
                                  dd,
                                  dlen,
                                  GNUNET_YES,
                                  GNUNET_NO)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Failed to parse DANE record: %s\n"),
                  dane_strerror(rc));
      dane_state_deinit (dane_state);
      gnutls_x509_crt_deinit (x509_cert);
      return GNUNET_SYSERR;
    }
    if (0 != (rc = dane_verify_crt_raw (dane_state,
                                        chainp,
                                        cert_list_size,
                                        gnutls_certificate_type_get (tlsinfo->internals),
                                        dane_query,
                                        0, 0,
                                        &verify)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Failed to verify TLS connection using DANE: %s\n"),
                  dane_strerror(rc));
      dane_query_deinit (dane_query);
      dane_state_deinit (dane_state);
      gnutls_x509_crt_deinit (x509_cert);
      return GNUNET_SYSERR;
    }
    if (0 != verify)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
                  verify);
      dane_query_deinit (dane_query);
      dane_state_deinit (dane_state);
      gnutls_x509_crt_deinit (x509_cert);
      return GNUNET_SYSERR;
    }
    dane_query_deinit (dane_query);
    dane_state_deinit (dane_state);
    /* success! */
  }
  else
#endif
  {
    /* try LEHO or ordinary domain name X509 verification */
    name = s5r->domain;
    if (NULL != s5r->leho)
      name = s5r->leho;
    if (NULL != name)
    {
      if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
                                                     name)))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    _("SSL certificate subject name (%s) does not match `%s'\n"),
                    certdn,
                    name);
        gnutls_x509_crt_deinit (x509_cert);
        return GNUNET_SYSERR;
      }
    }
    else
    {
      /* we did not even have the domain name!? */
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  gnutls_x509_crt_deinit (x509_cert);
  return GNUNET_OK;
}


/**
 * We're getting an HTTP response header from cURL.  Convert it to the
 * MHD response headers.  Mostly copies the headers, but makes special
 * adjustments to "Set-Cookie" and "Location" headers as those may need
 * to be changed from the LEHO to the domain the browser expects.
 *
 * @param buffer curl buffer with a single line of header data; not 0-terminated!
 * @param size curl blocksize
 * @param nmemb curl blocknumber
 * @param cls our `struct Socks5Request *`
 * @return size of processed bytes
 */
static size_t
curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
{
  struct Socks5Request *s5r = cls;
  struct HttpResponseHeader *header;
  size_t bytes = size * nmemb;
  char *ndup;
  const char *hdr_type;
  const char *cookie_domain;
  char *hdr_val;
  char *new_cookie_hdr;
  char *new_location;
  size_t offset;
  size_t delta_cdomain;
  int domain_matched;
  char *tok;

  /* first, check SSL certificate */
  if ((GNUNET_YES != s5r->ssl_checked) &&
      (HTTPS_PORT == s5r->port))
  {
      if (GNUNET_OK != check_ssl_certificate (s5r))
        return 0;
  }

  ndup = GNUNET_strndup (buffer, bytes);
  hdr_type = strtok (ndup, ":");
  if (NULL == hdr_type)
  {
    GNUNET_free (ndup);
    return bytes;
  }
  hdr_val = strtok (NULL, "");
  if (NULL == hdr_val)
  {
    GNUNET_free (ndup);
    return bytes;
  }
  if (' ' == *hdr_val)
    hdr_val++;

  /* custom logic for certain header types */
  new_cookie_hdr = NULL;
  if ( (NULL != s5r->leho) &&
       (0 == strcasecmp (hdr_type,
                         MHD_HTTP_HEADER_SET_COOKIE)) )

  {
    new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
                                    strlen (s5r->domain) + 1);
    offset = 0;
    domain_matched = GNUNET_NO; /* make sure we match domain at most once */
    for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
    {
      if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
           (GNUNET_NO == domain_matched) )
      {
        domain_matched = GNUNET_YES;
        cookie_domain = tok + strlen (" domain") + 1;
        if (strlen (cookie_domain) < strlen (s5r->leho))
        {
          delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
          if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
          {
            offset += sprintf (new_cookie_hdr + offset,
                               " domain=%s;",
                               s5r->domain);
            continue;
          }
        }
        else if (0 == strcmp (cookie_domain, s5r->leho))
        {
          offset += sprintf (new_cookie_hdr + offset,
                             " domain=%s;",
                             s5r->domain);
          continue;
        }
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    _("Cookie domain `%s' supplied by server is invalid\n"),
                    tok);
      }
      GNUNET_memcpy (new_cookie_hdr + offset, tok, strlen (tok));
      offset += strlen (tok);
      new_cookie_hdr[offset++] = ';';
    }
    hdr_val = new_cookie_hdr;
  }

  new_location = NULL;
  if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
  {
    char *leho_host;

    GNUNET_asprintf (&leho_host,
                     (HTTPS_PORT != s5r->port)
                     ? "http://%s"
                     : "https://%s",
                     s5r->leho);
    if (0 == strncmp (leho_host,
                      hdr_val,
                      strlen (leho_host)))
    {
      GNUNET_asprintf (&new_location,
                       "%s%s%s",
                       (HTTPS_PORT != s5r->port)
                       ? "http://"
                       : "https://",
                       s5r->domain,
                       hdr_val + strlen (leho_host));
      hdr_val = new_location;
    }
    GNUNET_free (leho_host);
  }
  /* MHD does not allow certain characters in values, remove those */
  if (NULL != (tok = strchr (hdr_val, '\n')))
    *tok = '\0';
  if (NULL != (tok = strchr (hdr_val, '\r')))
    *tok = '\0';
  if (NULL != (tok = strchr (hdr_val, '\t')))
    *tok = '\0';
  if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Adding header %s: %s to MHD response\n",
                hdr_type,
                hdr_val);
    header = GNUNET_new (struct HttpResponseHeader);
    header->type = GNUNET_strndup (hdr_type, strlen (hdr_type));
    header->value = GNUNET_strndup (hdr_val, strlen (hdr_val));
    GNUNET_CONTAINER_DLL_insert (s5r->header_head,
                                 s5r->header_tail,
                                 header);
  }
  GNUNET_free (ndup);
  GNUNET_free_non_null (new_cookie_hdr);
  GNUNET_free_non_null (new_location);
  return bytes;
}

static int
create_mhd_response_from_s5r (struct Socks5Request *s5r)
{
  long resp_code;
  double content_length;
  struct HttpResponseHeader *header;

  if (NULL != s5r->response)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Response already set!\n");
    return GNUNET_SYSERR;
  }

  GNUNET_break (CURLE_OK ==
                curl_easy_getinfo (s5r->curl,
                                   CURLINFO_RESPONSE_CODE,
                                   &resp_code));
  GNUNET_break (CURLE_OK ==
                curl_easy_getinfo (s5r->curl,
                                   CURLINFO_CONTENT_LENGTH_DOWNLOAD,
                                   &content_length));
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Creating MHD response with code %d and size %d\n",
              (int) resp_code, (int) content_length);
  s5r->response_code = resp_code;
  s5r->response = MHD_create_response_from_callback ((-1 == content_length) ? MHD_SIZE_UNKNOWN : content_length,
                                                     IO_BUFFERSIZE,
                                                     &mhd_content_cb,
                                                     s5r,
                                                     NULL);
  for (header = s5r->header_head; NULL != header; header = header->next)
  {
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (s5r->response,
                                           header->type,
                                           header->value));

  }
  if (NULL != s5r->leho)
  {
    char *cors_hdr;

    GNUNET_asprintf (&cors_hdr,
                     (HTTPS_PORT == s5r->port)
                     ? "https://%s"
                     : "http://%s",
                     s5r->leho);

    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (s5r->response,
                                           MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
                                           cors_hdr));
    GNUNET_free (cors_hdr);
  }
  /* force connection to be closed after each request, as we
     do not support HTTP pipelining (yet, FIXME!) */
  /*GNUNET_break (MHD_YES ==
    MHD_add_response_header (s5r->response,
    MHD_HTTP_HEADER_CONNECTION,
    "close"));*/
  return GNUNET_OK;
}

/**
 * Handle response payload data from cURL.  Copies it into our `io_buf` to make
 * it available to MHD.
 *
 * @param ptr pointer to the data
 * @param size number of blocks of data
 * @param nmemb blocksize
 * @param ctx our `struct Socks5Request *`
 * @return number of bytes handled
 */
static size_t
curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
{
  struct Socks5Request *s5r = ctx;
  size_t total = size * nmemb;

  if (NULL == s5r->response)
    GNUNET_assert (GNUNET_OK == create_mhd_response_from_s5r (s5r));

  if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
       (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
  {
    /* we're still not done with the upload, do not yet
       start the download, the IO buffer is still full
       with upload data. */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Pausing CURL download, waiting for UPLOAD to finish\n");
    return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
  }
  if (sizeof (s5r->io_buf) - s5r->io_len < total)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Pausing CURL download, not enough space\n");
    return CURL_WRITEFUNC_PAUSE; /* not enough space */
  }
  GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
                 ptr,
                 total);
  s5r->io_len += total;
  if (s5r->io_len == total)
    run_mhd_now (s5r->hd);
  return total;
}


/**
 * cURL callback for uploaded (PUT/POST) data.  Copies it into our `io_buf`
 * to make it available to MHD.
 *
 * @param buf where to write the data
 * @param size number of bytes per member
 * @param nmemb number of members available in @a buf
 * @param cls our `struct Socks5Request` that generated the data
 * @return number of bytes copied to @a buf
 */
static size_t
curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
{
  struct Socks5Request *s5r = cls;
  size_t len = size * nmemb;
  size_t to_copy;

  if ( (0 == s5r->io_len) &&
       (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Pausing CURL UPLOAD, need more data\n");
    return CURL_READFUNC_PAUSE;
  }
  if ( (0 == s5r->io_len) &&
       (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
  {
    s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Completed CURL UPLOAD\n");
    return 0; /* upload finished, can now download */
  }
  if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
       (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
  {
    GNUNET_break (0);
    return CURL_READFUNC_ABORT;
  }
  to_copy = GNUNET_MIN (s5r->io_len,
                        len);
  GNUNET_memcpy (buf, s5r->io_buf, to_copy);
  memmove (s5r->io_buf,
           &s5r->io_buf[to_copy],
           s5r->io_len - to_copy);
  s5r->io_len -= to_copy;
  if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
    run_mhd_now (s5r->hd); /* got more space for upload now */
  return to_copy;
}


/* ************************** main loop of cURL interaction ****************** */


/**
 * Task that is run when we are ready to receive more data
 * from curl
 *
 * @param cls closure
 */
static void
curl_task_download (void *cls);


/**
 * Ask cURL for the select() sets and schedule cURL operations.
 */
static void
curl_download_prepare ()
{
  CURLMcode mret;
  fd_set rs;
  fd_set ws;
  fd_set es;
  int max;
  struct GNUNET_NETWORK_FDSet *grs;
  struct GNUNET_NETWORK_FDSet *gws;
  long to;
  struct GNUNET_TIME_Relative rtime;

  if (NULL != curl_download_task)
  {
    GNUNET_SCHEDULER_cancel (curl_download_task);
    curl_download_task = NULL;
  }
  max = -1;
  FD_ZERO (&rs);
  FD_ZERO (&ws);
  FD_ZERO (&es);
  if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "%s failed at %s:%d: `%s'\n",
                "curl_multi_fdset", __FILE__, __LINE__,
                curl_multi_strerror (mret));
    return;
  }
  to = -1;
  GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
  if (-1 == to)
    rtime = GNUNET_TIME_UNIT_FOREVER_REL;
  else
    rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
  if (-1 != max)
  {
    grs = GNUNET_NETWORK_fdset_create ();
    gws = GNUNET_NETWORK_fdset_create ();
    GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
    GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
    curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                                      rtime,
                                                      grs, gws,
                                                      &curl_task_download, curl_multi);
    GNUNET_NETWORK_fdset_destroy (gws);
    GNUNET_NETWORK_fdset_destroy (grs);
  }
  else
  {
    curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
                                                       &curl_task_download,
                                                       curl_multi);
  }
}


/**
 * Task that is run when we are ready to receive more data from curl.
 *
 * @param cls closure, NULL
 */
static void
curl_task_download (void *cls)
{
  int running;
  int msgnum;
  struct CURLMsg *msg;
  CURLMcode mret;
  struct Socks5Request *s5r;

  curl_download_task = NULL;
  do
  {
    running = 0;
    mret = curl_multi_perform (curl_multi, &running);
    while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
    {
      GNUNET_break (CURLE_OK ==
                    curl_easy_getinfo (msg->easy_handle,
                                       CURLINFO_PRIVATE,
                                       (char **) &s5r ));
      if (NULL == s5r)
      {
        GNUNET_break (0);
        continue;
      }
      switch (msg->msg)
      {
        case CURLMSG_NONE:
          /* documentation says this is not used */
          GNUNET_break (0);
          break;
        case CURLMSG_DONE:
          switch (msg->data.result)
          {
            case CURLE_OK:
            case CURLE_GOT_NOTHING:
              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                          "CURL download completed.\n");
              if (NULL == s5r->response)
                GNUNET_assert (GNUNET_OK == create_mhd_response_from_s5r (s5r));
              s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
              run_mhd_now (s5r->hd);
              break;
            default:
              GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                          "Download curl failed: %s\n",
                          curl_easy_strerror (msg->data.result));
              /* FIXME: indicate error somehow? close MHD connection badly as well? */
              s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
              run_mhd_now (s5r->hd);
              break;
          }
          if (NULL == s5r->response)
            s5r->response = curl_failure_response;
          break;
        case CURLMSG_LAST:
          /* documentation says this is not used */
          GNUNET_break (0);
          break;
        default:
          /* unexpected status code */
          GNUNET_break (0);
          break;
      }
    };
  } while (mret == CURLM_CALL_MULTI_PERFORM);
  if (CURLM_OK != mret)
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "%s failed at %s:%d: `%s'\n",
                "curl_multi_perform", __FILE__, __LINE__,
                curl_multi_strerror (mret));
  if (0 == running)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Suspending cURL multi loop, no more events pending\n");
    return; /* nothing more in progress */
  }
  curl_download_prepare ();
}


/* ********************************* MHD response generation ******************* */


/**
 * Read HTTP request header field from the request.  Copies the fields
 * over to the 'headers' that will be given to curl.  However, 'Host'
 * is substituted with the LEHO if present.  We also change the
 * 'Connection' header value to "close" as the proxy does not support
 * pipelining.
 *
 * @param cls our `struct Socks5Request`
 * @param kind value kind
 * @param key field key
 * @param value field value
 * @return MHD_YES to continue to iterate
 */
static int
con_val_iter (void *cls,
              enum MHD_ValueKind kind,
              const char *key,
              const char *value)
{
  struct Socks5Request *s5r = cls;
  char *hdr;

  if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
       (NULL != s5r->leho) )
    value = s5r->leho;
  if (0 == strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, key))
    return MHD_YES;
  if (0 == strcasecmp (MHD_HTTP_HEADER_ACCEPT_ENCODING, key))
    return MHD_YES;
  GNUNET_asprintf (&hdr,
                   "%s: %s",
                   key,
                   value);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Adding HEADER `%s' to HTTP request\n",
              hdr);
  s5r->headers = curl_slist_append (s5r->headers,
                                    hdr);
  GNUNET_free (hdr);
  return MHD_YES;
}


/**
 * Main MHD callback for handling requests.
 *
 * @param cls unused
 * @param con MHD connection handle
 * @param url the url in the request
 * @param meth the HTTP method used ("GET", "PUT", etc.)
 * @param ver the HTTP version string (i.e. "HTTP/1.1")
 * @param upload_data the data being uploaded (excluding HEADERS,
 *        for a POST that fits into memory and that is encoded
 *        with a supported encoding, the POST data will NOT be
 *        given in upload_data and is instead available as
 *        part of MHD_get_connection_values; very large POST
 *        data *will* be made available incrementally in
 *        upload_data)
 * @param upload_data_size set initially to the size of the
 *        @a upload_data provided; the method must update this
 *        value to the number of bytes NOT processed;
 * @param con_cls pointer to location where we store the 'struct Request'
 * @return MHD_YES if the connection was handled successfully,
 *         MHD_NO if the socket must be closed due to a serious
 *         error while handling the request
 */
static int
create_response (void *cls,
                 struct MHD_Connection *con,
                 const char *url,
                 const char *meth,
                 const char *ver,
                 const char *upload_data,
                 size_t *upload_data_size,
                 void **con_cls)
{
  struct Socks5Request *s5r = *con_cls;
  char *curlurl;
  char *curl_hosts;
  char ipstring[INET6_ADDRSTRLEN];
  char ipaddr[INET6_ADDRSTRLEN + 2];
  const struct sockaddr *sa;
  const struct sockaddr_in *s4;
  const struct sockaddr_in6 *s6;
  uint16_t port;
  size_t left;

  if (NULL == s5r)
  {
    GNUNET_break (0);
    return MHD_NO;
  }
  //Fresh connection.
  if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
  {
    /* first time here, initialize curl handle */
    sa = (const struct sockaddr *) &s5r->destination_address;
    switch (sa->sa_family)
    {
      case AF_INET:
        s4 = (const struct sockaddr_in *) &s5r->destination_address;
        if (NULL == inet_ntop (AF_INET,
                               &s4->sin_addr,
                               ipstring,
                               sizeof (ipstring)))
        {
          GNUNET_break (0);
          return MHD_NO;
        }
        GNUNET_snprintf (ipaddr,
                         sizeof (ipaddr),
                         "%s",
                         ipstring);
        port = ntohs (s4->sin_port);
        break;
      case AF_INET6:
        s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
        if (NULL == inet_ntop (AF_INET6,
                               &s6->sin6_addr,
                               ipstring,
                               sizeof (ipstring)))
        {
          GNUNET_break (0);
          return MHD_NO;
        }
        GNUNET_snprintf (ipaddr,
                         sizeof (ipaddr),
                         "%s",
                         ipstring);
        port = ntohs (s6->sin6_port);
        break;
      default:
        GNUNET_break (0);
        return MHD_NO;
    }
    if (NULL == s5r->curl)
      s5r->curl = curl_easy_init ();
    if (NULL == s5r->curl)
      return MHD_queue_response (con,
                                 MHD_HTTP_INTERNAL_SERVER_ERROR,
                                 curl_failure_response);
    curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
    curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
    curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
    curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
    curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
    curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
    curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
    curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
    curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
    curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
    curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
    /**
     * Pre-populate cache to resolve Hostname.
     * This is necessary as the DNS name in the CURLOPT_URL is used
     * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
     */
    if (NULL != s5r->leho)
    {
      GNUNET_asprintf (&curl_hosts,
                       "%s:%d:%s",
                       s5r->leho,
                       port,
                       ipaddr);
      s5r->hosts = curl_slist_append(NULL, curl_hosts);
      curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
      GNUNET_free (curl_hosts);
    }
    GNUNET_asprintf (&curlurl,
                     (HTTPS_PORT != s5r->port)
                     ? "http://%s:%d%s"
                     : "https://%s:%d%s",
                     (NULL != s5r->leho)
                     ? s5r->leho
                     : ipaddr,
                     port,
                     s5r->url);
    curl_easy_setopt (s5r->curl,
                      CURLOPT_URL,
                      curlurl);
    GNUNET_free (curlurl);
    if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
    {
      s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
      curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
      curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
      curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
      curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
    }
    else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
    {
      s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
      curl_easy_setopt (s5r->curl, CURLOPT_POST, 1L);
            curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
      curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
      curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
      curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
    }
    else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
    {
      s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
      curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
    }
    else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
    {
      s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
      curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
    }
    else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
    {
      s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
      curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
      curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
      curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
    }
    else
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Unsupported HTTP method `%s'\n"),
                  meth);
      curl_easy_cleanup (s5r->curl);
      s5r->curl = NULL;
      return MHD_NO;
    }

    if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
    {
      curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    }
    else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
    {
      curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    }
    else
    {
      curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
    }

    if (HTTPS_PORT == s5r->port)
    {
      curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
      if (NULL != s5r->dane_data)
        curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 0L);
      else
        curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
      /* Disable cURL checking the hostname, as we will check ourselves
         as only we have the domain name or the LEHO or the DANE record */
      curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
    }
    else
    {
      curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
    }

    if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
    {
      GNUNET_break (0);
      curl_easy_cleanup (s5r->curl);
      s5r->curl = NULL;
      return MHD_NO;
    }
    MHD_get_connection_values (con,
                               MHD_HEADER_KIND,
                               &con_val_iter, s5r);
    curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
    curl_download_prepare ();
    return MHD_YES;
  }

  /* continuing to process request */
  if (0 != *upload_data_size)
  {

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Processing %u bytes UPLOAD\n",
		(unsigned int) *upload_data_size);

    /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
     * upload callback is not called!
     */
    curl_easy_setopt (s5r->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);

    left = GNUNET_MIN (*upload_data_size,
                       sizeof (s5r->io_buf) - s5r->io_len);
    GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
                   upload_data,
                   left);
    s5r->io_len += left;
    *upload_data_size -= left;
    GNUNET_assert (NULL != s5r->curl);
    curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
    return MHD_YES;
  }
  if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Finished processing UPLOAD\n");
    s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
  }
  if (NULL == s5r->response)
    return MHD_YES;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Queueing response with MHD\n");
  run_mhd_now (s5r->hd);
  return MHD_queue_response (con,
                             s5r->response_code,
                             s5r->response);
}


/* ******************** MHD HTTP setup and event loop ******************** */


/**
 * Function called when MHD decides that we are done with a request.
 *
 * @param cls NULL
 * @param connection connection handle
 * @param con_cls value as set by the last call to
 *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
 * @param toe reason for request termination (ignored)
 */
static void
mhd_completed_cb (void *cls,
                  struct MHD_Connection *connection,
                  void **con_cls,
                  enum MHD_RequestTerminationCode toe)
{
  struct Socks5Request *s5r = *con_cls;
  struct HttpResponseHeader *header;

  if (NULL == s5r)
    return;
  if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "MHD encountered error handling request: %d\n",
                toe);
  if (NULL != s5r->curl)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Resetting cURL handle\n");
    curl_multi_remove_handle (curl_multi, s5r->curl);
    curl_slist_free_all (s5r->headers);
    s5r->headers = NULL;
    curl_easy_reset (s5r->curl);
    s5r->rbuf_len = 0;
    s5r->wbuf_len = 0;
    s5r->io_len = 0;
  }
  if ( (NULL != s5r->response) &&
       (curl_failure_response != s5r->response) )
    MHD_destroy_response (s5r->response);
  for (header = s5r->header_head; header != NULL; header = s5r->header_head)
  {
    GNUNET_CONTAINER_DLL_remove (s5r->header_head,
                                 s5r->header_head,
                                 header);
    GNUNET_free (header->type);
    GNUNET_free (header->value);
    GNUNET_free (header);
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Finished request for %s\n", s5r->url);
  GNUNET_free (s5r->url);
  s5r->state = SOCKS5_SOCKET_WITH_MHD;
  s5r->url = NULL;
  s5r->response = NULL;
  *con_cls = NULL;
}


/**
 * Function called when MHD connection is opened or closed.
 *
 * @param cls NULL
 * @param connection connection handle
 * @param con_cls value as set by the last call to
 *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
 * @param toe connection notification type
 */
static void
mhd_connection_cb (void *cls,
                   struct MHD_Connection *connection,
                   void **con_cls,
                   enum MHD_ConnectionNotificationCode cnc)
{
  struct Socks5Request *s5r;
  const union MHD_ConnectionInfo *ci;
  int sock;

  switch (cnc)
  {
    case MHD_CONNECTION_NOTIFY_STARTED:
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
      ci = MHD_get_connection_info (connection,
                                    MHD_CONNECTION_INFO_CONNECTION_FD);
      if (NULL == ci)
      {
        GNUNET_break (0);
        return;
      }
      sock = ci->connect_fd;
      for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
      {
        if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "Context set...\n");
          s5r->ssl_checked = GNUNET_NO;
          *con_cls = s5r;
          break;
        }
      }
      break;
    case MHD_CONNECTION_NOTIFY_CLOSED:
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Connection closed... cleaning up\n");
      s5r = *con_cls;
      if (NULL == s5r)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Connection stale!\n");
        return;
      }
      cleanup_s5r (s5r);
      curl_download_prepare ();
      *con_cls = NULL;
      break;
    default:
      GNUNET_break (0);
  }
}

/**
 * Function called when MHD first processes an incoming connection.
 * Gives us the respective URI information.
 *
 * We use this to associate the `struct MHD_Connection` with our
 * internal `struct Socks5Request` data structure (by checking
 * for matching sockets).
 *
 * @param cls the HTTP server handle (a `struct MhdHttpList`)
 * @param url the URL that is being requested
 * @param connection MHD connection object for the request
 * @return the `struct Socks5Request` that this @a connection is for
 */
static void *
mhd_log_callback (void *cls,
                  const char *url,
                  struct MHD_Connection *connection)
{
  struct Socks5Request *s5r;
  const union MHD_ConnectionInfo *ci;

  ci = MHD_get_connection_info (connection,
                                MHD_CONNECTION_INFO_SOCKET_CONTEXT);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
  if (NULL == ci)
  {
    GNUNET_break (0);
    return NULL;
  }
  s5r = ci->socket_context;
  if (NULL != s5r->url)
  {
    GNUNET_break (0);
    return NULL;
  }
  s5r->url = GNUNET_strdup (url);
  if (NULL != s5r->timeout_task)
    GNUNET_SCHEDULER_cancel (s5r->timeout_task);
  s5r->timeout_task = NULL;
  GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
  return s5r;
}


/**
 * Kill the given MHD daemon.
 *
 * @param hd daemon to stop
 */
static void
kill_httpd (struct MhdHttpList *hd)
{
  GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
                               mhd_httpd_tail,
                               hd);
  GNUNET_free_non_null (hd->domain);
  MHD_stop_daemon (hd->daemon);
  if (NULL != hd->httpd_task)
  {
    GNUNET_SCHEDULER_cancel (hd->httpd_task);
    hd->httpd_task = NULL;
  }
  GNUNET_free_non_null (hd->proxy_cert);
  if (hd == httpd)
    httpd = NULL;
  GNUNET_free (hd);
}


/**
 * Task run whenever HTTP server is idle for too long. Kill it.
 *
 * @param cls the `struct MhdHttpList *`
 */
static void
kill_httpd_task (void *cls)
{
  struct MhdHttpList *hd = cls;

  hd->httpd_task = NULL;
  kill_httpd (hd);
}


/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls the `struct MhdHttpList *` of the daemon that is being run
 */
static void
do_httpd (void *cls);


/**
 * Schedule MHD.  This function should be called initially when an
 * MHD is first getting its client socket, and will then automatically
 * always be called later whenever there is work to be done.
 *
 * @param hd the daemon to schedule
 */
static void
schedule_httpd (struct MhdHttpList *hd)
{
  fd_set rs;
  fd_set ws;
  fd_set es;
  struct GNUNET_NETWORK_FDSet *wrs;
  struct GNUNET_NETWORK_FDSet *wws;
  int max;
  int haveto;
  MHD_UNSIGNED_LONG_LONG timeout;
  struct GNUNET_TIME_Relative tv;

  FD_ZERO (&rs);
  FD_ZERO (&ws);
  FD_ZERO (&es);
  max = -1;
  if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
  {
    kill_httpd (hd);
    return;
  }
  haveto = MHD_get_timeout (hd->daemon, &timeout);
  if (MHD_YES == haveto)
    tv.rel_value_us = (uint64_t) timeout * 1000LL;
  else
    tv = GNUNET_TIME_UNIT_FOREVER_REL;
  if (-1 != max)
  {
    wrs = GNUNET_NETWORK_fdset_create ();
    wws = GNUNET_NETWORK_fdset_create ();
    GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
    GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
  }
  else
  {
    wrs = NULL;
    wws = NULL;
  }
  if (NULL != hd->httpd_task)
    GNUNET_SCHEDULER_cancel (hd->httpd_task);
  if ( (MHD_YES != haveto) &&
       (-1 == max) &&
       (hd != httpd) )
  {
    /* daemon is idle, kill after timeout */
    hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
                                                   &kill_httpd_task,
                                                   hd);
  }
  else
  {
    hd->httpd_task =
      GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                   tv, wrs, wws,
                                   &do_httpd, hd);
  }
  if (NULL != wrs)
    GNUNET_NETWORK_fdset_destroy (wrs);
  if (NULL != wws)
    GNUNET_NETWORK_fdset_destroy (wws);
}


/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls the `struct MhdHttpList` of the daemon that is being run
 */
static void
do_httpd (void *cls)
{
  struct MhdHttpList *hd = cls;

  hd->httpd_task = NULL;
  MHD_run (hd->daemon);
  schedule_httpd (hd);
}


/**
 * Run MHD now, we have extra data ready for the callback.
 *
 * @param hd the daemon to run now.
 */
static void
run_mhd_now (struct MhdHttpList *hd)
{
  if (NULL !=
      hd->httpd_task)
    GNUNET_SCHEDULER_cancel (hd->httpd_task);
  hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
                                             hd);
}


/**
 * Read file in filename
 *
 * @param filename file to read
 * @param size pointer where filesize is stored
 * @return NULL on error
 */
static void*
load_file (const char* filename,
           unsigned int* size)
{
  void *buffer;
  uint64_t fsize;

  if (GNUNET_OK !=
      GNUNET_DISK_file_size (filename, &fsize,
                             GNUNET_YES, GNUNET_YES))
    return NULL;
  if (fsize > MAX_PEM_SIZE)
    return NULL;
  *size = (unsigned int) fsize;
  buffer = GNUNET_malloc (*size);
  if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
  {
    GNUNET_free (buffer);
    return NULL;
  }
  return buffer;
}


/**
 * Load PEM key from file
 *
 * @param key where to store the data
 * @param keyfile path to the PEM file
 * @return #GNUNET_OK on success
 */
static int
load_key_from_file (gnutls_x509_privkey_t key,
                    const char* keyfile)
{
  gnutls_datum_t key_data;
  int ret;

  key_data.data = load_file (keyfile, &key_data.size);
  if (NULL == key_data.data)
    return GNUNET_SYSERR;
  ret = gnutls_x509_privkey_import (key, &key_data,
                                    GNUTLS_X509_FMT_PEM);
  if (GNUTLS_E_SUCCESS != ret)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("Unable to import private key from file `%s'\n"),
                keyfile);
  }
  GNUNET_free_non_null (key_data.data);
  return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
}


/**
 * Load cert from file
 *
 * @param crt struct to store data in
 * @param certfile path to pem file
 * @return #GNUNET_OK on success
 */
static int
load_cert_from_file (gnutls_x509_crt_t crt,
                     const char* certfile)
{
  gnutls_datum_t cert_data;
  int ret;

  cert_data.data = load_file (certfile, &cert_data.size);
  if (NULL == cert_data.data)
    return GNUNET_SYSERR;
  ret = gnutls_x509_crt_import (crt, &cert_data,
                                GNUTLS_X509_FMT_PEM);
  if (GNUTLS_E_SUCCESS != ret)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("Unable to import certificate %s\n"), certfile);
  }
  GNUNET_free_non_null (cert_data.data);
  return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
}


/**
 * Generate new certificate for specific name
 *
 * @param name the subject name to generate a cert for
 * @return a struct holding the PEM data, NULL on error
 */
static struct ProxyGNSCertificate *
generate_gns_certificate (const char *name)
{
  unsigned int serial;
  size_t key_buf_size;
  size_t cert_buf_size;
  gnutls_x509_crt_t request;
  time_t etime;
  struct tm *tm_data;
  struct ProxyGNSCertificate *pgc;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Generating TLS/SSL certificate for `%s'\n",
              name);
  GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
  GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
  pgc = GNUNET_new (struct ProxyGNSCertificate);
  gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
                                 0, "ZZ", 2);
  gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
                                 0, "GNU Name System", 4);
  gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
                                 0, name, strlen (name));
  GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
  gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
  gnutls_x509_crt_set_serial (request,
                              &serial,
                              sizeof (serial));
  etime = time (NULL);
  tm_data = localtime (&etime);
  gnutls_x509_crt_set_activation_time (request,
                                       etime);
  tm_data->tm_year++;
  etime = mktime (tm_data);
  gnutls_x509_crt_set_expiration_time (request,
                                       etime);
  gnutls_x509_crt_sign (request,
                        proxy_ca.cert,
                        proxy_ca.key);
  key_buf_size = sizeof (pgc->key);
  cert_buf_size = sizeof (pgc->cert);
  gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
                          pgc->cert, &cert_buf_size);
  gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
                              pgc->key, &key_buf_size);
  gnutls_x509_crt_deinit (request);
  return pgc;
}


/**
 * Function called by MHD with errors, suppresses them all.
 *
 * @param cls closure
 * @param fm format string (`printf()`-style)
 * @param ap arguments to @a fm
 */
static void
mhd_error_log_callback (void *cls,
                        const char *fm,
                        va_list ap)
{
  /* do nothing */
}


/**
 * Lookup (or create) an SSL MHD instance for a particular domain.
 *
 * @param domain the domain the SSL daemon has to serve
 * @return NULL on error
 */
static struct MhdHttpList *
lookup_ssl_httpd (const char* domain)
{
  struct MhdHttpList *hd;
  struct ProxyGNSCertificate *pgc;

  if (NULL == domain)
  {
    GNUNET_break (0);
    return NULL;
  }
  for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
    if ( (NULL != hd->domain) &&
         (0 == strcmp (hd->domain, domain)) )
      return hd;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting fresh MHD HTTPS instance for domain `%s'\n",
              domain);
  pgc = generate_gns_certificate (domain);
  hd = GNUNET_new (struct MhdHttpList);
  hd->is_ssl = GNUNET_YES;
  hd->domain = GNUNET_strdup (domain);
  hd->proxy_cert = pgc;
  hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
                                 0,
                                 NULL, NULL,
                                 &create_response, hd,
                                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
                                 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
                                 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
                                 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
                                 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
                                 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
                                 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
                                 MHD_OPTION_END);
  if (NULL == hd->daemon)
  {
    GNUNET_free (pgc);
    GNUNET_free (hd);
    return NULL;
  }
  GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
                               mhd_httpd_tail,
                               hd);
  return hd;
}


/**
 * Task run when a Socks5Request somehow fails to be associated with
 * an MHD connection (i.e. because the client never speaks HTTP after
 * the SOCKS5 handshake).  Clean up.
 *
 * @param cls the `struct Socks5Request *`
 */
static void
timeout_s5r_handshake (void *cls)
{
  struct Socks5Request *s5r = cls;

  s5r->timeout_task = NULL;
  cleanup_s5r (s5r);
}


/**
 * We're done with the Socks5 protocol, now we need to pass the
 * connection data through to the final destination, either
 * direct (if the protocol might not be HTTP), or via MHD
 * (if the port looks like it should be HTTP).
 *
 * @param s5r socks request that has reached the final stage
 */
static void
setup_data_transfer (struct Socks5Request *s5r)
{
  struct MhdHttpList *hd;
  int fd;
  const struct sockaddr *addr;
  socklen_t len;

  switch (s5r->port)
  {
    case HTTPS_PORT:
      hd = lookup_ssl_httpd (s5r->domain);
      if (NULL == hd)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    _("Failed to start HTTPS server for `%s'\n"),
                    s5r->domain);
        cleanup_s5r (s5r);
        return;
      }
      break;
    case HTTP_PORT:
    default:
      GNUNET_assert (NULL != httpd);
      hd = httpd;
      break;
  }
  fd = GNUNET_NETWORK_get_fd (s5r->sock);
  addr = GNUNET_NETWORK_get_addr (s5r->sock);
  len = GNUNET_NETWORK_get_addrlen (s5r->sock);
  s5r->state = SOCKS5_SOCKET_WITH_MHD;
  if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                _("Failed to pass client to MHD\n"));
    cleanup_s5r (s5r);
    return;
  }
  s5r->hd = hd;
  schedule_httpd (hd);
  s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
                                                    &timeout_s5r_handshake,
                                                    s5r);
}


/* ********************* SOCKS handling ************************* */


/**
 * Write data from buffer to socks5 client, then continue with state machine.
 *
 * @param cls the closure with the `struct Socks5Request`
 */
static void
do_write (void *cls)
{
  struct Socks5Request *s5r = cls;
  ssize_t len;

  s5r->wtask = NULL;
  len = GNUNET_NETWORK_socket_send (s5r->sock,
                                    s5r->wbuf,
                                    s5r->wbuf_len);
  if (len <= 0)
  {
    /* write error: connection closed, shutdown, etc.; just clean up */
    cleanup_s5r (s5r);
    return;
  }
  memmove (s5r->wbuf,
           &s5r->wbuf[len],
           s5r->wbuf_len - len);
  s5r->wbuf_len -= len;
  if (s5r->wbuf_len > 0)
  {
    /* not done writing */
    s5r->wtask =
      GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                      s5r->sock,
                                      &do_write, s5r);
    return;
  }

  /* we're done writing, continue with state machine! */

  switch (s5r->state)
  {
    case SOCKS5_INIT:
      GNUNET_assert (0);
      break;
    case SOCKS5_REQUEST:
      GNUNET_assert (NULL != s5r->rtask);
      break;
    case SOCKS5_DATA_TRANSFER:
      setup_data_transfer (s5r);
      return;
    case SOCKS5_WRITE_THEN_CLEANUP:
      cleanup_s5r (s5r);
      return;
    default:
      GNUNET_break (0);
      break;
  }
}


/**
 * Return a server response message indicating a failure to the client.
 *
 * @param s5r request to return failure code for
 * @param sc status code to return
 */
static void
signal_socks_failure (struct Socks5Request *s5r,
                      enum Socks5StatusCode sc)
{
  struct Socks5ServerResponseMessage *s_resp;

  s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
  memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
  s_resp->version = SOCKS_VERSION_5;
  s_resp->reply = sc;
  s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
  if (NULL != s5r->wtask)
    s5r->wtask =
      GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                      s5r->sock,
                                      &do_write, s5r);
}


/**
 * Return a server response message indicating success.
 *
 * @param s5r request to return success status message for
 */
static void
signal_socks_success (struct Socks5Request *s5r)
{
  struct Socks5ServerResponseMessage *s_resp;

  s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
  s_resp->version = SOCKS_VERSION_5;
  s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
  s_resp->reserved = 0;
  s_resp->addr_type = SOCKS5_AT_IPV4;
  /* zero out IPv4 address and port */
  memset (&s_resp[1],
          0,
          sizeof (struct in_addr) + sizeof (uint16_t));
  s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
    sizeof (struct in_addr) + sizeof (uint16_t);
  if (NULL == s5r->wtask)
    s5r->wtask =
      GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                      s5r->sock,
                                      &do_write, s5r);
}


/**
 * Process GNS results for target domain.
 *
 * @param cls the `struct Socks5Request *`
 * @param rd_count number of records returned
 * @param rd record data
 */
static void
handle_gns_result (void *cls,
                   uint32_t rd_count,
                   const struct GNUNET_GNSRECORD_Data *rd)
{
  struct Socks5Request *s5r = cls;
  uint32_t i;
  const struct GNUNET_GNSRECORD_Data *r;
  int got_ip;

  s5r->gns_lookup = NULL;
  got_ip = GNUNET_NO;
  for (i=0;i<rd_count;i++)
  {
    r = &rd[i];
    switch (r->record_type)
    {
      case GNUNET_DNSPARSER_TYPE_A:
        {
          struct sockaddr_in *in;

          if (sizeof (struct in_addr) != r->data_size)
          {
            GNUNET_break_op (0);
            break;
          }
          if (GNUNET_YES == got_ip)
            break;
          if (GNUNET_OK !=
              GNUNET_NETWORK_test_pf (PF_INET))
            break;
          got_ip = GNUNET_YES;
          in = (struct sockaddr_in *) &s5r->destination_address;
          in->sin_family = AF_INET;
          GNUNET_memcpy (&in->sin_addr,
                         r->data,
                         r->data_size);
          in->sin_port = htons (s5r->port);
#if HAVE_SOCKADDR_IN_SIN_LEN
          in->sin_len = sizeof (*in);
#endif
        }
        break;
      case GNUNET_DNSPARSER_TYPE_AAAA:
        {
          struct sockaddr_in6 *in;

          if (sizeof (struct in6_addr) != r->data_size)
          {
            GNUNET_break_op (0);
            break;
          }
          if (GNUNET_YES == got_ip)
            break;
          if (GNUNET_OK !=
              GNUNET_NETWORK_test_pf (PF_INET))
            break;
          /* FIXME: allow user to disable IPv6 per configuration option... */
          got_ip = GNUNET_YES;
          in = (struct sockaddr_in6 *) &s5r->destination_address;
          in->sin6_family = AF_INET6;
          GNUNET_memcpy (&in->sin6_addr,
                         r->data,
                         r->data_size);
          in->sin6_port = htons (s5r->port);
#if HAVE_SOCKADDR_IN_SIN_LEN
          in->sin6_len = sizeof (*in);
#endif
        }
        break;
      case GNUNET_GNSRECORD_TYPE_VPN:
        GNUNET_break (0); /* should have been translated within GNS */
        break;
      case GNUNET_GNSRECORD_TYPE_LEHO:
        GNUNET_free_non_null (s5r->leho);
        s5r->leho = GNUNET_strndup (r->data,
                                    r->data_size);
        break;
      case GNUNET_GNSRECORD_TYPE_BOX:
        {
          const struct GNUNET_GNSRECORD_BoxRecord *box;

          if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
          {
            GNUNET_break_op (0);
            break;
          }
          box = r->data;
          if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
               (ntohs (box->protocol) != IPPROTO_TCP) ||
               (ntohs (box->service) != s5r->port) )
            break; /* BOX record does not apply */
          GNUNET_free_non_null (s5r->dane_data);
          s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
          s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
          GNUNET_memcpy (s5r->dane_data,
                         &box[1],
                         s5r->dane_data_len);
          break;
        }
      default:
        /* don't care */
        break;
    }
  }
  if (GNUNET_YES != got_ip)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Name resolution failed to yield useful IP address.\n");
    signal_socks_failure (s5r,
                          SOCKS5_STATUS_GENERAL_FAILURE);
    return;
  }
  s5r->state = SOCKS5_DATA_TRANSFER;
  signal_socks_success (s5r);
}


/**
 * Remove the first @a len bytes from the beginning of the read buffer.
 *
 * @param s5r the handle clear the read buffer for
 * @param len number of bytes in read buffer to advance
 */
static void
clear_from_s5r_rbuf (struct Socks5Request *s5r,
                     size_t len)
{
  GNUNET_assert (len <= s5r->rbuf_len);
  memmove (s5r->rbuf,
           &s5r->rbuf[len],
           s5r->rbuf_len - len);
  s5r->rbuf_len -= len;
}


/**
 * Read data from incoming Socks5 connection
 *
 * @param cls the closure with the `struct Socks5Request`
 */
static void
do_s5r_read (void *cls)
{
  struct Socks5Request *s5r = cls;
  const struct Socks5ClientHelloMessage *c_hello;
  struct Socks5ServerHelloMessage *s_hello;
  const struct Socks5ClientRequestMessage *c_req;
  ssize_t rlen;
  size_t alen;
  const struct GNUNET_SCHEDULER_TaskContext *tc;

  s5r->rtask = NULL;
  tc = GNUNET_SCHEDULER_get_task_context ();
  if ( (NULL != tc->read_ready) &&
       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
  {
    rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
                                       &s5r->rbuf[s5r->rbuf_len],
                                       sizeof (s5r->rbuf) - s5r->rbuf_len);
    if (rlen <= 0)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "socks5 client disconnected.\n");
      cleanup_s5r (s5r);
      return;
    }
    s5r->rbuf_len += rlen;
  }
  s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              s5r->sock,
                                              &do_s5r_read, s5r);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Processing %zu bytes of socks data in state %d\n",
              s5r->rbuf_len,
              s5r->state);
  switch (s5r->state)
  {
    case SOCKS5_INIT:
      c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
      if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
           (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
        return; /* need more data */
      if (SOCKS_VERSION_5 != c_hello->version)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    _("Unsupported socks version %d\n"),
                    (int) c_hello->version);
        cleanup_s5r (s5r);
        return;
      }
      clear_from_s5r_rbuf (s5r,
                           sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
      GNUNET_assert (0 == s5r->wbuf_len);
      s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
      s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
      s_hello->version = SOCKS_VERSION_5;
      s_hello->auth_method = SOCKS_AUTH_NONE;
      GNUNET_assert (NULL == s5r->wtask);
      s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                                   s5r->sock,
                                                   &do_write, s5r);
      s5r->state = SOCKS5_REQUEST;
      return;
    case SOCKS5_REQUEST:
      c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
      if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
        return;
      switch (c_req->command)
      {
        case SOCKS5_CMD_TCP_STREAM:
          /* handled below */
          break;
        default:
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      _("Unsupported socks command %d\n"),
                      (int) c_req->command);
          signal_socks_failure (s5r,
                                SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
          return;
      }
      switch (c_req->addr_type)
      {
        case SOCKS5_AT_IPV4:
          {
            const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
            const uint16_t *port = (const uint16_t *) &v4[1];
            struct sockaddr_in *in;

            s5r->port = ntohs (*port);
            if (HTTPS_PORT == s5r->port)
            {
              GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                          _("SSL connection to plain IPv4 address requested\n"));
              signal_socks_failure (s5r,
                                    SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
              return;
            }
            alen = sizeof (struct in_addr);
            if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
                alen + sizeof (uint16_t))
              return; /* need more data */
            in = (struct sockaddr_in *) &s5r->destination_address;
            in->sin_family = AF_INET;
            in->sin_addr = *v4;
            in->sin_port = *port;
#if HAVE_SOCKADDR_IN_SIN_LEN
            in->sin_len = sizeof (*in);
#endif
            s5r->state = SOCKS5_DATA_TRANSFER;
          }
          break;
        case SOCKS5_AT_IPV6:
          {
            const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
            const uint16_t *port = (const uint16_t *) &v6[1];
            struct sockaddr_in6 *in;

            s5r->port = ntohs (*port);
            if (HTTPS_PORT == s5r->port)
            {
              GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                          _("SSL connection to plain IPv4 address requested\n"));
              signal_socks_failure (s5r,
                                    SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
              return;
            }
            alen = sizeof (struct in6_addr);
            if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
                alen + sizeof (uint16_t))
              return; /* need more data */
            in = (struct sockaddr_in6 *) &s5r->destination_address;
            in->sin6_family = AF_INET6;
            in->sin6_addr = *v6;
            in->sin6_port = *port;
#if HAVE_SOCKADDR_IN_SIN_LEN
            in->sin6_len = sizeof (*in);
#endif
            s5r->state = SOCKS5_DATA_TRANSFER;
          }
          break;
        case SOCKS5_AT_DOMAINNAME:
          {
            const uint8_t *dom_len;
            const char *dom_name;
            const uint16_t *port;

            dom_len = (const uint8_t *) &c_req[1];
            alen = *dom_len + 1;
            if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
                alen + sizeof (uint16_t))
              return; /* need more data */
            dom_name = (const char *) &dom_len[1];
            port = (const uint16_t*) &dom_name[*dom_len];
            s5r->domain = GNUNET_strndup (dom_name, *dom_len);
            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                        "Requested connection is to %s:%d\n",
                        s5r->domain,
                        ntohs (*port));
            s5r->state = SOCKS5_RESOLVING;
            s5r->port = ntohs (*port);
            s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
                                                 s5r->domain,
                                                 &local_gns_zone,
                                                 GNUNET_DNSPARSER_TYPE_A,
                                                 GNUNET_NO /* only cached */,
                                                 &handle_gns_result,
                                                 s5r);
            break;
          }
        default:
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      _("Unsupported socks address type %d\n"),
                      (int) c_req->addr_type);
          signal_socks_failure (s5r,
                                SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
          return;
      }
      clear_from_s5r_rbuf (s5r,
                           sizeof (struct Socks5ClientRequestMessage) +
                           alen + sizeof (uint16_t));
      if (0 != s5r->rbuf_len)
      {
        /* read more bytes than healthy, why did the client send more!? */
        GNUNET_break_op (0);
        signal_socks_failure (s5r,
                              SOCKS5_STATUS_GENERAL_FAILURE);
        return;
      }
      if (SOCKS5_DATA_TRANSFER == s5r->state)
      {
        /* if we are not waiting for GNS resolution, signal success */
        signal_socks_success (s5r);
      }
      /* We are done reading right now */
      GNUNET_SCHEDULER_cancel (s5r->rtask);
      s5r->rtask = NULL;
      return;
    case SOCKS5_RESOLVING:
      GNUNET_assert (0);
      return;
    case SOCKS5_DATA_TRANSFER:
      GNUNET_assert (0);
      return;
    default:
      GNUNET_assert (0);
      return;
  }
}


/**
 * Accept new incoming connections
 *
 * @param cls the closure with the lsock4 or lsock6
 * @param tc the scheduler context
 */
static void
do_accept (void *cls)
{
  struct GNUNET_NETWORK_Handle *lsock = cls;
  struct GNUNET_NETWORK_Handle *s;
  struct Socks5Request *s5r;

  if (lsock == lsock4)
    ltask4 = NULL;
  else
    ltask6 = NULL;
  if (lsock == lsock4)
    ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                            lsock,
                                            &do_accept, lsock);
  else
    ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                            lsock,
                                            &do_accept, lsock);
  s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
  if (NULL == s)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got an inbound connection, waiting for data\n");
  s5r = GNUNET_new (struct Socks5Request);
  GNUNET_CONTAINER_DLL_insert (s5r_head,
                               s5r_tail,
                               s5r);
  s5r->sock = s;
  s5r->state = SOCKS5_INIT;
  s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              s5r->sock,
                                              &do_s5r_read, s5r);
}


/* ******************* General / main code ********************* */


/**
 * Task run on shutdown
 *
 * @param cls closure
 */
static void
do_shutdown (void *cls)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Shutting down...\n");
  while (NULL != mhd_httpd_head)
    kill_httpd (mhd_httpd_head);
  while (NULL != s5r_head)
    cleanup_s5r (s5r_head);
  if (NULL != lsock4)
  {
    GNUNET_NETWORK_socket_close (lsock4);
    lsock4 = NULL;
  }
  if (NULL != lsock6)
  {
    GNUNET_NETWORK_socket_close (lsock6);
    lsock6 = NULL;
  }
  if (NULL != id_op)
  {
    GNUNET_IDENTITY_cancel (id_op);
    id_op = NULL;
  }
  if (NULL != identity)
  {
    GNUNET_IDENTITY_disconnect (identity);
    identity = NULL;
  }
  if (NULL != curl_multi)
  {
    curl_multi_cleanup (curl_multi);
    curl_multi = NULL;
  }
  if (NULL != gns_handle)
  {
    GNUNET_GNS_disconnect (gns_handle);
    gns_handle = NULL;
  }
  if (NULL != curl_download_task)
  {
    GNUNET_SCHEDULER_cancel (curl_download_task);
    curl_download_task = NULL;
  }
  if (NULL != ltask4)
  {
    GNUNET_SCHEDULER_cancel (ltask4);
    ltask4 = NULL;
  }
  if (NULL != ltask6)
  {
    GNUNET_SCHEDULER_cancel (ltask6);
    ltask6 = NULL;
  }
  gnutls_x509_crt_deinit (proxy_ca.cert);
  gnutls_x509_privkey_deinit (proxy_ca.key);
  gnutls_global_deinit ();
}


/**
 * Create an IPv4 listen socket bound to our port.
 *
 * @return NULL on error
 */
static struct GNUNET_NETWORK_Handle *
bind_v4 ()
{
  struct GNUNET_NETWORK_Handle *ls;
  struct sockaddr_in sa4;
  int eno;

  memset (&sa4, 0, sizeof (sa4));
  sa4.sin_family = AF_INET;
  sa4.sin_port = htons (port);
#if HAVE_SOCKADDR_IN_SIN_LEN
  sa4.sin_len = sizeof (sa4);
#endif
  ls = GNUNET_NETWORK_socket_create (AF_INET,
                                     SOCK_STREAM,
                                     0);
  if (NULL == ls)
    return NULL;
  if (GNUNET_OK !=
      GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
                                  sizeof (sa4)))
  {
    eno = errno;
    GNUNET_NETWORK_socket_close (ls);
    errno = eno;
    return NULL;
  }
  return ls;
}


/**
 * Create an IPv6 listen socket bound to our port.
 *
 * @return NULL on error
 */
static struct GNUNET_NETWORK_Handle *
bind_v6 ()
{
  struct GNUNET_NETWORK_Handle *ls;
  struct sockaddr_in6 sa6;
  int eno;

  memset (&sa6, 0, sizeof (sa6));
  sa6.sin6_family = AF_INET6;
  sa6.sin6_port = htons (port);
#if HAVE_SOCKADDR_IN_SIN_LEN
  sa6.sin6_len = sizeof (sa6);
#endif
  ls = GNUNET_NETWORK_socket_create (AF_INET6,
                                     SOCK_STREAM,
                                     0);
  if (NULL == ls)
    return NULL;
  if (GNUNET_OK !=
      GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
                                  sizeof (sa6)))
  {
    eno = errno;
    GNUNET_NETWORK_socket_close (ls);
    errno = eno;
    return NULL;
  }
  return ls;
}


/**
 * Continue initialization after we have our zone information.
 */
static void
run_cont ()
{
  struct MhdHttpList *hd;

  /* Open listen socket for socks proxy */
  lsock6 = bind_v6 ();
  if (NULL == lsock6)
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
  else
  {
    if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
      GNUNET_NETWORK_socket_close (lsock6);
      lsock6 = NULL;
    }
    else
    {
      ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              lsock6, &do_accept, lsock6);
    }
  }
  lsock4 = bind_v4 ();
  if (NULL == lsock4)
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
  else
  {
    if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
      GNUNET_NETWORK_socket_close (lsock4);
      lsock4 = NULL;
    }
    else
    {
      ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              lsock4, &do_accept, lsock4);
    }
  }
  if ( (NULL == lsock4) &&
       (NULL == lsock6) )
  {
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "cURL global init failed!\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Proxy listens on port %llu\n",
              port);

  /* start MHD daemon for HTTP */
  hd = GNUNET_new (struct MhdHttpList);
  hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
                                 0,
                                 NULL, NULL,
                                 &create_response, hd,
                                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
                                 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
                                 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
                                 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
                                 MHD_OPTION_END);
  if (NULL == hd->daemon)
  {
    GNUNET_free (hd);
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  httpd = hd;
  GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
}


/**
 * Method called to inform about the egos of the master zone of this peer.
 *
 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
 * this function is only called ONCE, and 'NULL' being passed in
 * @a ego does indicate an error (i.e. name is taken or no default
 * value is known).  If @a ego is non-NULL and if '*ctx'
 * is set in those callbacks, the value WILL be passed to a subsequent
 * call to the identity callback of #GNUNET_IDENTITY_connect (if
 * that one was not NULL).
 *
 * @param cls closure, NULL
 * @param ego ego handle
 * @param ctx context for application to store data for this ego
 *                 (during the lifetime of this process, initially NULL)
 * @param name name assigned by the user for this ego,
 *                   NULL if the user just deleted the ego and it
 *                   must thus no longer be used
 */
static void
identity_master_cb (void *cls,
                    struct GNUNET_IDENTITY_Ego *ego,
                    void **ctx,
                    const char *name)
{
  id_op = NULL;
  if (NULL == ego)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("No ego configured for `%s`\n"),
                "gns-proxy");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_IDENTITY_ego_get_public_key (ego,
                                      &local_gns_zone);
  run_cont ();
}


/**
 * Main function that will be run
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param c configuration
 */
static void
run (void *cls,
     char *const *args,
     const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  char* cafile_cfg = NULL;
  char* cafile;

  cfg = c;

  if (NULL == (curl_multi = curl_multi_init ()))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to create cURL multi handle!\n");
    return;
  }
  cafile = cafile_opt;
  if (NULL == cafile)
  {
    if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
                                                              "PROXY_CACERT",
                                                              &cafile_cfg))
    {
      GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                                 "gns-proxy",
                                 "PROXY_CACERT");
      return;
    }
    cafile = cafile_cfg;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Using %s as CA\n", cafile);

  gnutls_global_init ();
  gnutls_x509_crt_init (&proxy_ca.cert);
  gnutls_x509_privkey_init (&proxy_ca.key);

  if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
       (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("Failed to load SSL/TLS key and certificate from `%s'\n"),
                cafile);
    gnutls_x509_crt_deinit (proxy_ca.cert);
    gnutls_x509_privkey_deinit (proxy_ca.key);
    gnutls_global_deinit ();
    GNUNET_free_non_null (cafile_cfg);
    return;
  }
  GNUNET_free_non_null (cafile_cfg);
  if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unable to connect to GNS!\n");
    gnutls_x509_crt_deinit (proxy_ca.cert);
    gnutls_x509_privkey_deinit (proxy_ca.key);
    gnutls_global_deinit ();
    return;
  }
  identity = GNUNET_IDENTITY_connect (cfg,
                                      NULL, NULL);
  id_op = GNUNET_IDENTITY_get (identity,
                               "gns-proxy",
                               &identity_master_cb,
                               NULL);
  GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
}


/**
 * The main function for gnunet-gns-proxy.
 *
 * @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)
{
  struct GNUNET_GETOPT_CommandLineOption options[] = {

    GNUNET_GETOPT_OPTION_SET_ULONG ('p',
                                    "port",
                                    NULL,
                                    gettext_noop ("listen on specified port (default: 7777)"),
                                    &port),

    GNUNET_GETOPT_OPTION_STRING ('a',
                                 "authority",
                                 NULL,
                                 gettext_noop ("pem file to use as CA"),
                                 &cafile_opt),

    GNUNET_GETOPT_OPTION_END
  };
  static const char* page =
    "<html><head><title>gnunet-gns-proxy</title>"
    "</head><body>cURL fail</body></html>";
  int ret;

  if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
                                                 &argc, &argv))
    return 2;
  GNUNET_log_setup ("gnunet-gns-proxy",
                    "WARNING",
                    NULL);
  curl_failure_response
    = MHD_create_response_from_buffer (strlen (page),
                                       (void *) page,
                                       MHD_RESPMEM_PERSISTENT);

  ret =
    (GNUNET_OK ==
     GNUNET_PROGRAM_run (argc, argv,
                         "gnunet-gns-proxy",
                         _("GNUnet GNS proxy"),
                         options,
                         &run, NULL)) ? 0 : 1;
  MHD_destroy_response (curl_failure_response);
  GNUNET_free_non_null ((char *) argv);
  return ret;
}

/* end of gnunet-gns-proxy.c */