File: network.c

package info (click to toggle)
openvas-libraries 1.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 1,724 kB
  • ctags: 1,254
  • sloc: ansic: 11,752; sh: 6,698; makefile: 288
file content (2678 lines) | stat: -rw-r--r-- 57,403 bytes parent folder | download
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
/* OpenVAS
 * $Id$
 * Description: Network Functions.
 *
 * Authors:
 * Renaud Deraison <deraison@nessus.org> (Original pre-fork development)
 * Michel Arboi (Original pre-fork development)
 *
 * Copyright:
 * Based on work Copyright (C) 1998 - 2002 Renaud Deraison
 *               SSL Support Copyright (C) 2001 Michel Arboi
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <sys/types.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

#include "libopenvas.h"
#include "resolve.h"
#include "ids_send.h"
#include "plugutils.h"

#include <setjmp.h>

#define TIMEOUT 20

#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif

extern int plug_get_port_transport(struct arglist*, int);
extern void plug_set_port_transport(struct arglist*, int, int);


/*----------------------------------------------------------------*
 * Low-level connection management                                *
 *----------------------------------------------------------------*/
 
/* Nessus "FILE" structure */
typedef struct {
 int fd;		/* socket number, or whatever */
 int transport;	/* "transport" layer code when stream is encapsultated. 
		 * Negative transport signals a free descriptor */
 int timeout;	  /* timeout, in seconds
		   * special values: -2 for default */
 int options;			/* Misc options - see libopenvas.h */
  
 int port;			 

 gnutls_session_t tls_session;  /* GnuTLS session */
 gnutls_certificate_credentials_t tls_cred; /* GnuTLS credentials */

 pid_t		pid;		/* Owner - for debugging only */

  char*		buf;		/* NULL if unbuffered */
  int		bufsz, bufcnt, bufptr;
  int 		last_err;
} nessus_connection;

/* 
 * The role of this offset is:
 * 1. To detect bugs when the program tries to write to a bad fd
 * 2. See if a fd is a real socket or a "nessus descriptor". This is a
 * quick & dirty hack and should be changed!!!
 */
#define NESSUS_FD_MAX 1024
#define NESSUS_FD_OFF 1000000

static nessus_connection connections[NESSUS_FD_MAX];

/*
 * Quick & dirty patch to run Nessus from behind a picky firewall (e.g.
 * FW/1 and his 'Rule 0'): Nessus will never open more than 1 connection at
 * a time.
 * Define NESSUS_CNX_LOCK, recompile and install nessus-library, and restart nessusd
 *
 * WARNING: waiting on the lock file may be long, so increase the default
 * script timeout or some scripts may be killed.
 */
#undef NESSUS_CNX_LOCK
/*#define NESSUS_CNX_LOCK	"/tmp/NessusCnx"*/

#ifdef NESSUS_CNX_LOCK
static int	lock_cnt = 0;
static int	lock_fd = -1;
#endif

/*
 * NESSUS_STREAM(x) is TRUE if <x> is a Nessus-ified fd
 */
#define NESSUS_STREAM(x) (((x - NESSUS_FD_OFF) < NESSUS_FD_MAX) && ((x - NESSUS_FD_OFF) >=0))

/* determine the nessus_connection* from the nessus fd */
#define OVAS_CONNECTION_FROM_FD(fd) (connections + ((fd) - NESSUS_FD_OFF))


static void
renice_myself()
{
 static pid_t pid = 0;
 pid_t cpid = getpid();
 
 if( pid != cpid )
 {
  if(nice(0) >= 10)return;
  pid = cpid;
  nice(1);
 }
}
/*
 * Same as perror(), but prefixes the data by our pid
 */
static int 
nessus_perror(error)
 const char* error;
{
  fprintf(stderr, "[%d] %s : %s\n", getpid(), error, strerror(errno));
  return 0;
}


int
stream_get_err(fd)
 int fd;
{
 nessus_connection *p;
 
 if(!NESSUS_STREAM(fd))
    {
     errno = EINVAL;
     return -1;
    }
    
    
 p = &(connections[fd - NESSUS_FD_OFF]);
 return p->last_err;
}

/*
 * Returns a free file descriptor
 */
static int
get_connection_fd()
{
 int i;
 
 for ( i = 0; i < NESSUS_FD_MAX ; i++)
 {
  if(connections[i].transport <= 0) /* Not used */
  {
   bzero(&(connections[i]),  sizeof(connections[i]));
   connections[i].pid = getpid();
   return i + NESSUS_FD_OFF;
  }
 }
 fprintf(stderr, "[%d] %s:%d : Out of Nessus file descriptors\n", 
	 getpid(), __FILE__, __LINE__);
 errno = EMFILE;
 return -1;
}



static int
release_connection_fd(fd)
 int fd;
{
 nessus_connection *p;
 
 if(!NESSUS_STREAM(fd))
    {
     errno = EINVAL;
     return -1;
    }
    
    
 p = &(connections[fd - NESSUS_FD_OFF]);

 efree(&p->buf);

 /* TLS FIXME: we should call gnutls_bye somewhere.  OTOH, the OpenSSL
  * equivalent SSL_shutdown wasn't called anywhere in the OpenVAS
  * (libopenvas nor elsewhere) code either.
  */

/* 
 * So far, fd is always a socket. If this is changed in the future, this
 * code shall be fixed
 */
if (p->fd >= 0)
 {
  if (shutdown(p->fd, 2) < 0)
    {
#if DEBUG_SSL > 1
    /*
     * It's not uncommon to see that one fail, since a lot of
     * services close the connection before we ask them to
     * (ie: http), so we don't show this error by default
     */
    nessus_perror("release_connection_fd: shutdown()");
#endif    
    }
  if (socket_close(p->fd)  < 0)
    nessus_perror("release_connection_fd: close()");
 }

 if (p->tls_session != NULL)
   gnutls_deinit(p->tls_session);
 if (p->tls_cred != NULL)
   gnutls_certificate_free_credentials(p->tls_cred);

 bzero(p, sizeof(*p));
 p->transport = -1; 
 return 0;
}

/* ******** Compatibility function ******** */

/* TLS FIXME: migrate this to TLS */
int
ovas_allocate_connection(int s, int transport)
{
  int			fd;
  nessus_connection	*p;

  if((fd = get_connection_fd()) < 0)
    return -1;
  p = OVAS_CONNECTION_FROM_FD(fd);
  p->timeout = TIMEOUT;		/* default value */
  p->port = 0;			/* just used for debug */
  p->fd = s;
  p->transport = transport;
  p->last_err  = 0;
  return fd;
}

int
nessus_register_connection(int	s, void	*ssl)
{
  if (ssl != NULL)
    {
      fprintf(stderr, "[%d] nessus_register_connection:"
	      " ssl != NULL not supported", getpid());
      return -1;
    }

  return ovas_allocate_connection(s,
				  (ssl != NULL) ? NESSUS_ENCAPS_SSLv23
				                : NESSUS_ENCAPS_IP);
}

int
nessus_deregister_connection(fd)
 int fd;
{
 nessus_connection * p;
 if(!NESSUS_STREAM(fd))
 {
  errno = EINVAL;
  return -1;
 }
 
 p = connections +  (fd - NESSUS_FD_OFF);
 bzero(p, sizeof(*p));
 p->transport = -1; 
 return 0;
}

/*----------------------------------------------------------------*
 * High-level connection management                               *
 *----------------------------------------------------------------*/

static int __port_closed;

static int unblock_socket(int soc)
{
  int	flags =  fcntl(soc, F_GETFL, 0);
  if (flags < 0)
{
      nessus_perror("fcntl(F_GETFL)");
      return -1;
    }
  if (fcntl(soc, F_SETFL, O_NONBLOCK | flags) < 0)
    {
      nessus_perror("fcntl(F_SETFL,O_NONBLOCK)");
      return -1;
    }
  return 0;
}

static int block_socket(int soc)
{
  int	flags =  fcntl(soc, F_GETFL, 0);
  if (flags < 0)
    {
      nessus_perror("fcntl(F_GETFL)");
      return -1;
    }
  if (fcntl(soc, F_SETFL, (~O_NONBLOCK) & flags) < 0)
    {
      nessus_perror("fcntl(F_SETFL,~O_NONBLOCK)");
      return -1;
    }
  return 0;
}

/*
 * Initialize the SSL library (error strings and algorithms) and try
 * to set the pseudo random generator to something less silly than the
 * default value: 1 according to SVID 3, BSD 4.3, ISO 9899 :-(
 */


void tlserror(char *txt, int err)
{
  fprintf(stderr, "[%d] %s: %s\n", getpid(), txt, gnutls_strerror(err));
}



/* initializes SSL support in libopenvas.  The parameter path used to be
 * the filename of the entropy pool for OpenSSL in libnessus.  It's
 * unused in libopenvas.  At the time of the move to GNUTLS, all calls
 * passed NULL as the path anyway.
 */

int
nessus_SSL_init(char *path)
{
  static int initialized = 0;

  if (initialized)
    return 0;

  int ret = gnutls_global_init();
  if (ret < 0)
    {
      tlserror("gnutls_global_init", ret);
      return -1;
    }

  initialized = 1;

  return 0;
}

# if 0
void
nessus_print_SSL_certificate(cert)
     X509* cert;    
{
 BIO * b;
 BUF_MEM * bptr;
 char * ret = NULL;
 int	i;

 if(cert == NULL)
   return;

 b = BIO_new(BIO_s_mem());
 if(X509_print(b, cert) > 0)
   {
     BIO_get_mem_ptr(b, &bptr);
     printf("* Peer certificate *\n");
     for(i = 0; i < bptr->length; i ++)
       putchar(bptr->data[i]);
     printf("\n********************\n");
   }
 BIO_free(b);
}

void
nessus_print_peer_SSL_certificate(ssl)
     SSL* ssl;
{
  X509 * cert = SSL_get_peer_certificate(ssl);
  nessus_print_SSL_certificate(cert);
}
# endif


int
nessus_get_socket_from_connection(fd)
     int	fd;
{
  nessus_connection	*fp;

  if (!NESSUS_STREAM(fd))
    {
      fprintf(stderr,
	      "[%d] nessus_get_socket_from_connection: bad fd <%d>\n", getpid(), fd);
      fflush(stderr);
      return fd;
    }
  fp = connections + (fd - NESSUS_FD_OFF);
  if(fp->transport <= 0)
    {
      fprintf(stderr, "nessus_get_socket_from_connection: fd <%d> is closed\n", fd);
      return -1;
    }
  return fp->fd;
}

static int
set_gnutls_priorities(gnutls_session_t session,
		      int * protocol_priority,
		      int * cipher_priority,
		      int * comp_priority,
		      int * kx_priority,
		      int * mac_priority)
{
  int err;

  if((err = gnutls_protocol_set_priority(session, protocol_priority))
     || (err = gnutls_cipher_set_priority(session, cipher_priority))
     || (err = gnutls_compression_set_priority(session, comp_priority))
     || (err = gnutls_kx_set_priority(session, kx_priority))
     || (err = gnutls_mac_set_priority(session, mac_priority)))
    {
      tlserror("setting session priorities", err);
      return -1;
    }
  return 0;
}

static int
set_gnutls_sslv23(gnutls_session_t session)
{
  static int protocol_priority[] = {GNUTLS_TLS1,
				    GNUTLS_SSL3,
				    0};
  static int cipher_priority[] = {GNUTLS_CIPHER_AES_128_CBC,
				  GNUTLS_CIPHER_3DES_CBC,
				  GNUTLS_CIPHER_AES_256_CBC,
				  GNUTLS_CIPHER_ARCFOUR_128,
				  0};
  static int comp_priority[] = {GNUTLS_COMP_ZLIB,
				GNUTLS_COMP_NULL,
				0};
  static int kx_priority[] = {GNUTLS_KX_DHE_RSA,
			      GNUTLS_KX_RSA,
			      GNUTLS_KX_DHE_DSS,
			      0};
  static int mac_priority[] = {GNUTLS_MAC_SHA1,
			       GNUTLS_MAC_MD5,
			       0};

  return set_gnutls_priorities(session, protocol_priority, cipher_priority,
			       comp_priority, kx_priority, mac_priority);
}

static int
set_gnutls_sslv3(gnutls_session_t session)
{
  static int protocol_priority[] = {GNUTLS_SSL3,
				    0};
  static int cipher_priority[] = {GNUTLS_CIPHER_3DES_CBC,
				  GNUTLS_CIPHER_ARCFOUR_128,
				  0};
  static int comp_priority[] = {GNUTLS_COMP_ZLIB,
				GNUTLS_COMP_NULL,
				0};

  static int kx_priority[] = {GNUTLS_KX_DHE_RSA,
			      GNUTLS_KX_RSA,
			      GNUTLS_KX_DHE_DSS,
			      0};

  static int mac_priority[] = {GNUTLS_MAC_SHA1,
			       GNUTLS_MAC_MD5,
			       0};

  return set_gnutls_priorities(session, protocol_priority, cipher_priority,
			       comp_priority, kx_priority, mac_priority);
}

static int
set_gnutls_tlsv1(gnutls_session_t session)
{
  static int protocol_priority[] = {GNUTLS_TLS1,
				    0};
  static int cipher_priority[] = {GNUTLS_CIPHER_AES_128_CBC,
				  GNUTLS_CIPHER_3DES_CBC,
				  GNUTLS_CIPHER_AES_256_CBC,
				  GNUTLS_CIPHER_ARCFOUR_128,
				  0};
  static int comp_priority[] = {GNUTLS_COMP_ZLIB,
				GNUTLS_COMP_NULL,
				0};
  static int kx_priority[] = {GNUTLS_KX_DHE_RSA,
			      GNUTLS_KX_RSA,
			      GNUTLS_KX_DHE_DSS,
			      0};
  static int mac_priority[] = {GNUTLS_MAC_SHA1,
			       GNUTLS_MAC_MD5,
			       0};

  return set_gnutls_priorities(session, protocol_priority, cipher_priority,
			       comp_priority, kx_priority, mac_priority);
}

/*
 * Sets the priorities for the GnuTLS session according to encaps, one
 * of hte NESSUS_ENCAPS_* constants.
 */
static int
set_gnutls_protocol(gnutls_session_t session, int encaps)
{
  switch (encaps)
    {
    case NESSUS_ENCAPS_SSLv3:
      set_gnutls_sslv3(session);
      break;
    case NESSUS_ENCAPS_TLSv1:
      set_gnutls_tlsv1(session);
      break;
    case NESSUS_ENCAPS_SSLv23:	/* Compatibility mode */
      set_gnutls_sslv23(session);
      break;

    default:
#if DEBUG_SSL > 0
      fprintf(stderr, "*Bug* at %s:%d. Unknown transport %d\n",
	      __FILE__, __LINE__, encaps);
#endif
      set_gnutls_sslv23(session);
      break;
    }

  return 0;
}

/*
 * Verifies the peer's certificate.  If the certificate is not valid or
 * cannot be verified, the function prints diagnostics to stderr and
 * returns -1.  If the certificate was verified successfully the
 * function returns 0.  If the peer did not send a certificate, the
 * function also returns 0.
 */
static int
verify_peer_certificate(gnutls_session_t session)
{
  static struct {int flag; const char * message;} messages[] = {
    {GNUTLS_CERT_INVALID, "The peer certificate is invalid"},
    {GNUTLS_CERT_REVOKED, "The peer certificate has been revoked"},
    {GNUTLS_CERT_SIGNER_NOT_FOUND,
     "The peer certificate doesn't have a known issuer"},
    {GNUTLS_CERT_SIGNER_NOT_CA, "The peer certificate's issuer is not a CA"},
    {GNUTLS_CERT_INSECURE_ALGORITHM,
     "The peer certificate was signed using an insecure algorithm"},
    {0, NULL},
  };
  unsigned int status;
  int ret;
  int i;

  ret = gnutls_certificate_verify_peers2(session, &status);
  if (ret == GNUTLS_E_NO_CERTIFICATE_FOUND)
    /* The peer did not send a certificate.  We treat it as a valid
     * certificate in this function */
    return 0;
  if (ret < 0)
    {
      tlserror("gnutls_certificate_verify_peers2", ret);
      return -1;
    }

  for (i = 0; messages[i].message != NULL; i++)
    {
      if (status & messages[i].flag)
	fprintf(stderr, "[%d] failed to verify certificate: %s\n",
		getpid(), messages[i].message);
    }

  if (status)
    return -1;

  return 0;
}


/* helper function copied from cli.c from GnuTLS
 * Reads a file into a gnutls_datum
 */
static gnutls_datum
load_file (const char *file)
{
  FILE *f;
  gnutls_datum loaded_file = { NULL, 0 };
  long filelen;
  void *ptr;

  if (!(f = fopen(file, "r"))
      || fseek(f, 0, SEEK_END) != 0
      || (filelen = ftell(f)) < 0
      || fseek(f, 0, SEEK_SET) != 0
      || !(ptr = emalloc((size_t) filelen))
      || fread(ptr, 1, (size_t) filelen, f) < (size_t) filelen)
    {
      return loaded_file;
    }

  loaded_file.data = ptr;
  loaded_file.size = (unsigned int) filelen;
  return loaded_file;
}

/* helper function copied from cli.c from GnuTLS.
 *
 * Frees the data read by load_file.  It's safe to call this function
 * twice on the same data.
 */
static void
unload_file (gnutls_datum * data)
{
  efree(&(data->data));
}

/* Loads a certificate and the corresponding private key from PEM files.
 * The private key may be encrypted, in which case the password to
 * decrypt the key should be given as the passwd parameter.
 * Returns 0 on success and -1 on failure.
 */
static int
load_cert_and_key(gnutls_certificate_credentials_t xcred,
		  const char *cert, const char *key, const char *passwd)
{
  gnutls_x509_crt_t x509_crt = NULL;
  gnutls_x509_privkey_t x509_key = NULL;
  gnutls_datum data = { NULL, 0 };
  int ret;
  int result = 0;

  data = load_file(cert);
  if (data.data == NULL)
    {
      fprintf(stderr, "[%d] load_cert_and_key: Error loading cert file %s\n",
	      getpid(), cert);
      result = -1;
      goto cleanup;
    }

  ret = gnutls_x509_crt_init(&x509_crt);
  if (ret < 0)
    {
      tlserror("gnutls_x509_crt_init", ret);
      /* x509_crt may be != NULL even if gnutls_x509_crt_init fails */
      x509_crt = NULL;
      result = -1;
      goto cleanup;
    }

  ret = gnutls_x509_crt_import(x509_crt, &data, GNUTLS_X509_FMT_PEM);
  if (ret < 0)
    {
      tlserror("gnutls_x509_crt_import", ret);
      result = -1;
      goto cleanup;
    }

  unload_file(&data);

  data = load_file(key);
  if (data.data == NULL)
    {
      fprintf(stderr, "[%d] load_cert_and_key: Error loading key file %s\n",
	      getpid(), key);
      result = -1;
      goto cleanup;
    }

  ret = gnutls_x509_privkey_init (&x509_key);
  if (ret < 0)
    {
      tlserror("gnutls_x509_privkey_init", ret);
      /* x509_key may be != NULL even if gnutls_x509_privkey_init fails */
      x509_key = NULL;
      result = -1;
      goto cleanup;
    }

  if (passwd)
    {
      ret = gnutls_x509_privkey_import_pkcs8(x509_key, &data,
					     GNUTLS_X509_FMT_PEM, passwd, 0);
      if (ret < 0)
	{
	  tlserror("gnutls_x509_privkey_import_pkcs8", ret);
	  result = -1;
	  goto cleanup;
	}
    }
  else
    {
      ret = gnutls_x509_privkey_import(x509_key, &data, GNUTLS_X509_FMT_PEM);
      if (ret < 0)
	{
	  tlserror("gnutls_x509_privkey_import", ret);
	  result = -1;
	  goto cleanup;
	}
    }

  unload_file(&data);

  ret = gnutls_certificate_set_x509_key(xcred, &x509_crt, 1, x509_key);
  if (ret < 0)
    {
      tlserror("gnutls_certificate_set_x509_key", ret);
      result = -1;
      goto cleanup;
    }

  cleanup:

  unload_file(&data);
  if (x509_crt)
    gnutls_x509_crt_deinit(x509_crt);
  if (x509_key)
    gnutls_x509_privkey_deinit(x509_key);

  return result;
}

static int
open_SSL_connection(nessus_connection *fp, int timeout,
		    const char *cert, const char *key, const char *passwd,
		    const char *cafile)
{
  int		ret, err, d;
  time_t	tictac;
  fd_set	fdw, fdr;
  struct timeval	to;

  nessus_SSL_init(NULL);

  ret = gnutls_init (&(fp->tls_session), GNUTLS_CLIENT);
  if (ret < 0)
    {
      tlserror("gnutls_init", ret);
      return -1;
    }

  /* set_gnutls_protocol handles NESSUS_ENCAPS_SSLv2 by falling back
   * to NESSUS_ENCAPS_SSLv23.  However, this function
   * (open_SSL_connection) is called only by open_stream_connection and
   * open_stream_connection will exit with an error code if called with
   * NESSUS_ENCAPS_SSLv2, so it should never end up calling
   * open_SSL_connection with NESSUS_ENCAPS_SSLv2.
   */
  if (set_gnutls_protocol(fp->tls_session, fp->transport) < 0)
    return -1;

  ret = gnutls_certificate_allocate_credentials(&(fp->tls_cred));
  if (ret < 0)
    {
      tlserror("gnutls_certificate_allocate_credentials", ret);
      return -1;
    }
  ret = gnutls_credentials_set(fp->tls_session, GNUTLS_CRD_CERTIFICATE,
			       fp->tls_cred);
  if (ret < 0)
    {
      tlserror("gnutls_credentials_set", ret);
      return -1;
    }

  if (cert != NULL && key != NULL)
    {
      if (load_cert_and_key(fp->tls_cred, cert, key, passwd) < 0)
	return -1;
    }

  if (cafile != NULL)
    {
      ret = gnutls_certificate_set_x509_trust_file(fp->tls_cred, cafile,
						   GNUTLS_X509_FMT_PEM);
      if (ret < 0)
	{
	  tlserror("gnutls_certificate_set_x509_trust_file", ret);
	  return -1;
	}
    }

  unblock_socket(fp->fd);
  /* for non-blocking sockets, gnutls requires a 0 lowat value */
  gnutls_transport_set_lowat(fp->tls_session, 0);

  gnutls_transport_set_ptr(fp->tls_session, (gnutls_transport_ptr_t) fp->fd);

  tictac = time(NULL);

  for (;;)
    {
      err = gnutls_handshake(fp->tls_session);

      if (err == 0)
	{
	  /* success! */
	  return 1;
	}

      if (err != GNUTLS_E_INTERRUPTED && err != GNUTLS_E_AGAIN)
	{
#ifdef DEBUG_SSL
	  tlserror("gnutls_handshake", err);
#endif
	  return -1;
	}

      FD_ZERO(&fdr);
      FD_SET(fp->fd, &fdr);
      FD_ZERO(&fdw);
      FD_SET(fp->fd, &fdw);

      do
	{
	  d = tictac + timeout - time(NULL);
	  if (d <= 0)
	    {
	      fp->last_err = ETIMEDOUT;
	      return -1;
            }
	  to.tv_sec = d;
	  to.tv_usec = 0;
	  errno = 0;
	  if ((ret = select(fp->fd + 1, &fdr, &fdw, NULL, &to)) <= 0)
	    {
#if DEBUG_SSL > 1
	      nessus_perror("select");
#endif
	    }
	}
      while (ret < 0 && errno == EINTR);

      if (ret <= 0)
	{
	  fp->last_err = ETIMEDOUT;
	  return -1;
        }
    }
  /*NOTREACHED*/
}


static void
set_ids_evasion_mode(args, fp)
     struct arglist	*args;
     nessus_connection	*fp;
{
 struct kb_item ** kb = plug_get_kb(args);
 char		*ids_evasion_split = kb_item_get_str(kb, "NIDS/TCP/split");
 char 		*ids_evasion_inject = kb_item_get_str(kb, "NIDS/TCP/inject");
 char 		*ids_evasion_short_ttl = kb_item_get_str(kb,"NIDS/TCP/short_ttl");
 char		*ids_evasion_fake_rst = kb_item_get_str(kb, "NIDS/TCP/fake_rst");
 int option = 0;
 
 
 /*
  * These first three options are mutually exclusive
  */
 if(ids_evasion_split != NULL && strcmp(ids_evasion_split, "yes") == 0)
 	option = NESSUS_CNX_IDS_EVASION_SPLIT;

 if(ids_evasion_inject != NULL && strcmp(ids_evasion_inject, "yes") == 0)
 	option = NESSUS_CNX_IDS_EVASION_INJECT;
 
 if(ids_evasion_short_ttl != NULL && strcmp(ids_evasion_short_ttl, "yes") == 0)
 	option = NESSUS_CNX_IDS_EVASION_SHORT_TTL;


 /*
  * This is not exclusive with the above
  */
 if(ids_evasion_fake_rst != NULL && strcmp(ids_evasion_fake_rst, "yes") == 0)
 	option |= NESSUS_CNX_IDS_EVASION_FAKE_RST;

 if(option)
   {
#ifdef SO_SNDLOWAT
     int		n = 1;
     (void) setsockopt(fp->fd, SOL_SOCKET, SO_SNDLOWAT, (void*)&n, sizeof(n));
#endif
     fp->options |= option;
   }
}

int
open_stream_connection(struct arglist * args, unsigned int port, int transport,
		       int timeout)
{
 int			fd;
 nessus_connection * fp;
 char * cert   = NULL;
 char * key    = NULL;
 char * passwd = NULL;
 char * cafile = NULL;


#if DEBUG_SSL > 2
 fprintf(stderr, "[%d] open_stream_connection: TCP:%d transport:%d timeout:%d\n",
       getpid(), port, transport, timeout);
#endif

 if(timeout == -2)
  timeout = TIMEOUT;
  
 switch(transport)
 {
  case NESSUS_ENCAPS_IP:

  case NESSUS_ENCAPS_SSLv23:
  case NESSUS_ENCAPS_SSLv3:
  case NESSUS_ENCAPS_TLSv1:
   break;

  case NESSUS_ENCAPS_SSLv2:
  default:
   fprintf(stderr, "open_stream_connection(): unsupported transport layer %d\n",
   	transport);
   errno = EINVAL;
   return -1;
 }
 
 if((fd = get_connection_fd()) < 0)
  return -1;
 
 fp = &(connections[fd - NESSUS_FD_OFF]);
 
 
 fp->transport = transport;
 fp->timeout   = timeout;
 fp->port      = port;
 fp->last_err  = 0;
 set_ids_evasion_mode(args, fp);

 if(fp->options & NESSUS_CNX_IDS_EVASION_FAKE_RST)
   fp->fd = ids_open_sock_tcp(args, port, fp->options, timeout);
 else
   fp->fd = open_sock_tcp(args, port, timeout);
	
  if(fp->fd < 0)
	  goto failed;

 switch(transport)
 {
  case NESSUS_ENCAPS_IP:
    break;
  case NESSUS_ENCAPS_SSLv23:
  case NESSUS_ENCAPS_SSLv3:
  case NESSUS_ENCAPS_TLSv1:
    renice_myself();
    cert   = kb_item_get_str(plug_get_kb(args), "SSL/cert");
    key    = kb_item_get_str(plug_get_kb(args), "SSL/key");
    passwd = kb_item_get_str(plug_get_kb(args), "SSL/password");

    cafile = kb_item_get_str(plug_get_kb(args), "SSL/CA");

    /* fall through */

  case NESSUS_ENCAPS_SSLv2:
    /* We do not need a client certificate in this case */
    if (open_SSL_connection(fp, timeout, cert, key, passwd, cafile) <= 0)
      goto failed;
  break;
 }
 
 return fd;

failed:
 release_connection_fd(fd);
 return -1;
}


int
open_stream_connection_unknown_encaps5(args, port, timeout, p, delta_t)
 struct arglist * args;
 unsigned int  port;
 int timeout, * p;
 int	*delta_t;		/* time, in micro-seconds */
{
 int fd;
 int i;
  struct timeval	tv1, tv2;
 static int encaps[] = {
   NESSUS_ENCAPS_SSLv2,
   NESSUS_ENCAPS_TLSv1,
   NESSUS_ENCAPS_SSLv3,
    NESSUS_ENCAPS_IP
  };
 
#if DEBUG_SSL > 2
 fprintf(stderr, "[%d] open_stream_connection_unknown_encaps: TCP:%d; %d\n",
	 getpid(), port,timeout);
#endif

 for (i = 0; i < sizeof(encaps) / sizeof(*encaps); i ++)
    {
      if (delta_t != NULL) (void) gettimeofday(&tv1, NULL);
   if ((fd = open_stream_connection(args, port, encaps[i], timeout)) >= 0)
     {
       *p = encaps[i];
#if DEBUG_SSL > 2
       fprintf(stderr, "[%d] open_stream_connection_unknown_encaps: TCP:%d -> transport=%d\n", getpid(), port, *p);
#endif
	  if (delta_t != NULL)
	    {
	      (void) gettimeofday(&tv2, NULL);
	      *delta_t = (tv2.tv_sec - tv1.tv_sec) * 1000000 + (tv2.tv_usec - tv1.tv_usec);
	    }
       return fd;
     }
   else if (__port_closed)
     {
#if DEBUG_SSL > 2
       fprintf(stderr, "[%d] open_stream_connection_unknown_encaps: TCP:%d -> closed\n", getpid(), port);
#endif
       return -1;
     }
    }
  return -1;
 }
 
int
open_stream_connection_unknown_encaps(args, port, timeout, p)
 struct arglist * args;
 unsigned int  port;
 int timeout, * p;
{
  return open_stream_connection_unknown_encaps5(args, port, timeout, p, NULL);
}


int
open_stream_auto_encaps(args, port, timeout)
 struct arglist * args;
 unsigned int     port;
 int              timeout;
{
 int trp = plug_get_port_transport(args, port);
 int fd;
 
 if(trp == 0)
 {
  if ((fd = open_stream_connection_unknown_encaps(args, port, timeout, &trp)) < 0)
   return -1;
  plug_set_port_transport(args, port, trp);
  return fd;
 }
 else
 {
  fd = open_stream_connection(args, port, trp, timeout);
  return fd;
 }
 /*NOTREACHED*/
}


/*
 * Server socket functions
 */

struct ovas_server_context_s
{
  /* transport encapsulation to use */
  int encaps;

  /* whether to force public key authentication */
  int force_pubkey_auth;

  /* GnuTLS credentials */
  gnutls_certificate_credentials_t tls_cred;
};

/*
 * Creates a new ovas_server_context_t.  The parameter encaps should be
 * one of the NESSUS_ENCAPS_* constants.  If any of the SSL
 * encapsulations are used, the parameters certfile, keyfile, and cafile
 * should be the filenames of the server certificate and corresponding
 * key and the CA certificate.  The optional passwd parameter is used as
 * the password to decrypt the keyfile if it is encrypted.
 *
 * The force_pubkey_auth parameter is a boolean controlling public key
 * authentication of the client.  If force_pubkey_auth is true, the
 * client must authenticate itself with a certificate.  Otherwise the
 * client will be asked for a certificate but doesn't have to present
 * one.
 */
ovas_server_context_t
ovas_server_context_new(int encaps,
			const char* certfile,
			const char* keyfile,
			const char* passwd,
			const char* cafile,
			int force_pubkey_auth)
{
  ovas_server_context_t ctx = NULL;

  if (nessus_SSL_init(NULL) < 0)
    return NULL;

  ctx = emalloc(sizeof(struct ovas_server_context_s));
  if (ctx == NULL)
    return NULL;

  ctx->encaps = encaps;
  ctx->force_pubkey_auth = force_pubkey_auth;

  if (ctx->encaps != NESSUS_ENCAPS_IP)
    {
      int ret = gnutls_certificate_allocate_credentials(&(ctx->tls_cred));
      if (ret < 0)
	{
	  tlserror("gnutls_certificate_allocate_credentials", ret);
	  ctx->tls_cred = NULL;
	  goto fail;
	}

      if (certfile && keyfile)
	{
	  if (load_cert_and_key(ctx->tls_cred, certfile, keyfile, passwd) < 0)
	    goto fail;
	}

      if (cafile != NULL)
	{
	  ret = gnutls_certificate_set_x509_trust_file(ctx->tls_cred, cafile,
						       GNUTLS_X509_FMT_PEM);
	  if (ret < 0)
	    {
	      tlserror("gnutls_certificate_set_x509_trust_file", ret);
	      goto fail;
	    }
	}
    }

  return ctx;


 fail:
  ovas_server_context_free(ctx);
  return NULL;
}


/*
 * Frees the ovas_server_context_t instance ctx.  If ctx is NULL, nothing
 * is done.
 */
void
ovas_server_context_free(ovas_server_context_t ctx)
{
  if (ctx == NULL)
    return;

  if (ctx->tls_cred != NULL)
    gnutls_certificate_free_credentials(ctx->tls_cred);

  efree(&ctx);
}

/*
 * Sets up SSL/TLS on the socket soc and returns a nessus file
 * descriptor.  The parameters for the SSL/TLS layer are taken from ctx.
 * Afterwards, the credentials of ctx are also referenced by the SSL/TLS
 * objects associated with the nessus file descriptor.  This means that
 * the context ctx must not be freed until the nessus file descriptor is
 * closed.
 *
 * If the context's force_pubkey_auth member is true (!= 0), the client
 * must provide a certificate.  If force_pubkey_auth is false, the
 * client certificate is optional.  In any case, if the client provides
 * a certificate, the certificate is verified.  If the verification
 * fails, ovas_server_context_attach returns -1.
 *
 * ovas_server_context_attach returns the nessus file descriptor on
 * success and -1 on failure.
 */
int
ovas_server_context_attach(ovas_server_context_t ctx, int soc)
{
  int fd = -1;
  nessus_connection * fp = NULL;
  int ret;

  fd = ovas_allocate_connection(soc, ctx->encaps);
  if (fd < 0)
    return -1;

  fp = OVAS_CONNECTION_FROM_FD(fd);

  if (fp->transport != NESSUS_ENCAPS_IP)
    {
      ret = gnutls_init(&(fp->tls_session), GNUTLS_SERVER);
      if (ret < 0)
	{
	  tlserror("gnutls_init", ret);
	  goto fail;
	}

      ret = set_gnutls_protocol(fp->tls_session, fp->transport);
      if (ret < 0)
	{
	  goto fail;
	}

      if (ctx->tls_cred)
	{
	  /* *fp contains a field for the gnutls credentials.  We do not
	   * set it here because ctx->tls_cred is owned by ctx and
	   * copying it to fp->tls_cred would lead to it being freed
	   * when the connection is closed. */
	  ret = gnutls_credentials_set(fp->tls_session, GNUTLS_CRD_CERTIFICATE,
				       ctx->tls_cred);
	  if (ret < 0)
	    {
	      tlserror("gnutls_credentials_set", ret);
	      return -1;
	    }
	}


      /* request client certificate if any. */
      gnutls_certificate_server_set_request(fp->tls_session,
					    ctx->force_pubkey_auth
					    ? GNUTLS_CERT_REQUIRE
					    : GNUTLS_CERT_REQUEST);

      gnutls_transport_set_ptr(fp->tls_session,
			       (gnutls_transport_ptr_t) fp->fd);
      ret = gnutls_handshake(fp->tls_session);
      if (ret < 0)
	{
	  tlserror("gnutls_handshake", ret);
	  goto fail;
	}

      if (verify_peer_certificate(fp->tls_session) < 0)
	{
	  goto fail;
	}
    }

  return fd;

 fail:
  release_connection_fd(fd);
  return -1;
}



/* TLS: This function is only used in one place,
 * openvas-plugins/plugins/ssl_ciphers/ssl_ciphers.c:145 (function
 * plugin_run).  The code there prints information about the
 * certificates and the server's ciphers if sslv2 is used.  Some of the
 * functionality should perhaps be moved to openvas-libraries.
 */
void*
stream_get_ssl(int fd)
{
  return NULL;
}


int
stream_set_timeout(fd, timeout)
 int fd;
 int timeout;
{
 int old;
 nessus_connection * fp;
 if(!NESSUS_STREAM(fd))
    {
     errno = EINVAL;
     return 0;
    }
  fp = &(connections[fd - NESSUS_FD_OFF]);
  old = fp->timeout;
  fp->timeout = timeout;
  return old;
}

int
stream_set_options(fd, reset_opt, set_opt)
     int	fd, reset_opt, set_opt;
{
 nessus_connection * fp;
 if(!NESSUS_STREAM(fd))
    {
     errno = EINVAL;
     return -1;
    }
  fp = &(connections[fd - NESSUS_FD_OFF]);
  fp->options &= ~reset_opt;
  fp->options |= set_opt;
  return 0;
}


static int 
read_stream_connection_unbuffered(fd, buf0, min_len, max_len)
 int fd;
 void* buf0;
 int min_len, max_len;
{
  int			ret, realfd, trp, t;
  int			total = 0, flag = 0, timeout = TIMEOUT, waitall = 0;
  unsigned char		* buf = (unsigned char*)buf0;
  nessus_connection	*fp = NULL;
  fd_set		fdr, fdw;
  struct timeval	tv;
  time_t		now, then;

  int		 	select_status;
 
#if 0
  fprintf(stderr, "read_stream_connection(%d, 0x%x, %d, %d)\n",
	  fd, buf, min_len, max_len);
#endif

  if (NESSUS_STREAM(fd))
    {
      fp = &(connections[fd - NESSUS_FD_OFF]);
      trp = fp->transport;
      realfd = fp->fd;
      fp->last_err = 0;
      if (fp->timeout != -2)
	timeout = fp->timeout;
    }
  else
    {
#if 0
      fprintf(stderr, "read_stream_connection[%d] : supposedly bad fd %d\n",
	      getpid(), fd);
#endif
      trp = NESSUS_ENCAPS_IP;
      if(fd < 0 || fd > 1024)
	      	{
			errno = EBADF;
			return -1;
		}
      realfd = fd;
    }

#ifndef INCR_TIMEOUT
# define INCR_TIMEOUT	1
#endif

#ifdef MSG_WAITALL
  if (min_len == max_len || timeout <= 0)
    waitall = MSG_WAITALL;
#endif

  if(trp == NESSUS_ENCAPS_IP)
    {
      for (t = 0; total < max_len && (timeout <= 0 || t < timeout); )
	{
	  tv.tv_sec = INCR_TIMEOUT; /* Not timeout! */
	  tv.tv_usec = 0;
	  FD_ZERO(&fdr);
	  FD_SET(realfd, &fdr);
	  if(select(realfd + 1, &fdr, NULL, NULL, timeout > 0 ? &tv : NULL) <= 0)
	    {
	      t += INCR_TIMEOUT;
	      /* Try to be smart */
	      if (total > 0 && flag) 
		return total;
	      else if (total >= min_len)
		flag ++;
	    }
	  else
	    {
	      errno = 0;
	      ret = recv(realfd, buf + total, max_len - total, waitall);
	      if (ret < 0)
		if (errno != EINTR)
                  {
		  fp->last_err = errno;
		  return total;
                  }
		else
		  ret = 0;
	      else if (ret == 0) /* EOF */
                {
                fp->last_err = EPIPE;
		return total;
                }
	      /*ret > 0*/
	      total += ret; 
	      if (min_len > 0 && total >= min_len)
		return total;
	      flag = 0;
	    }
	}
      if ( t >= timeout ) fp->last_err = ETIMEDOUT;
      return total;
    }

  switch(trp)
    {
      /* NESSUS_ENCAPS_IP was treated before with the non-Nessus fd */
    case NESSUS_ENCAPS_SSLv2:
    case NESSUS_ENCAPS_SSLv23:
    case NESSUS_ENCAPS_SSLv3:
    case NESSUS_ENCAPS_TLSv1:
# if DEBUG_SSL > 0
      if (getpid() != fp->pid)
	{
	  fprintf(stderr, "PID %d tries to use a SSL connection established by PID %d\n", getpid(), fp->pid);
	  errno = EINVAL;
	  return -1;
	}
# endif

      now = then = time(NULL);
      for (t = 0; timeout <= 0 || t < timeout; t = now - then )
	{	
          now = time(NULL);
	  tv.tv_sec = INCR_TIMEOUT; tv.tv_usec = 0;
	  FD_ZERO(&fdr); FD_ZERO(&fdw);
	  FD_SET(realfd, &fdr); FD_SET(realfd, &fdw);

	  select_status = select ( realfd + 1, &fdr, &fdw, NULL, &tv );

	  if (select_status > 0)
	    {
	      /* TLS FIXME: handle rehandshake */
	      ret = gnutls_record_recv(fp->tls_session, buf + total,
				       max_len - total);
	      if (ret > 0)
		{
		  total += ret;
		}

	      if (total >= max_len)
		return total;

	      if (ret != GNUTLS_E_INTERRUPTED && ret != GNUTLS_E_AGAIN)
		{
		  /* This branch also handles the case where ret == 0,
		   * i.e. that the connection has been closed.  This is
		   * for compatibility with the old OpenSSL based nessus
		   * code which treated SSL_ERROR_ZERO_RETURN as an
		   * error too.
		   */
#ifdef DEBUG_SSL
		  if (ret < 0)
		    {
		      tlserror("gnutls_record_recv", ret);
		    }
		  else
		    {
		      fprintf(stderr, "gnutls_record_recv[%d]: EOF\n",
			      getpid());
		    }
#endif
		  fp->last_err = EPIPE;
		  return total;
		}
	    }

	    if (min_len <= 0)
	      {
		/* Be smart */
		if (total > 0 && flag)
		  return total;
		else
		  flag ++;
	      }
	  else if (total >= min_len)
		return total;
	}
      if ( t >= timeout ) fp->last_err = ETIMEDOUT;
      return total;

    default :
      if (fp->transport != -1 || fp->fd != 0)
	fprintf(stderr, "Severe bug! Unhandled transport layer %d (fd=%d)\n",
		fp->transport, fd);
      else
	fprintf(stderr, "read_stream_connection_unbuffered: fd=%d is closed\n", fd);
      errno = EINVAL;
      return -1;
    }
  /*NOTREACHED*/
}

int
read_stream_connection_min(fd, buf0, min_len, max_len)
 int fd;
 void* buf0;
 int min_len, max_len;
{
  nessus_connection	*fp;

  if (NESSUS_STREAM(fd))
    {
      fp = &(connections[fd - NESSUS_FD_OFF]);
      if (fp->buf != NULL)
	{
	  int		l1, l2;

	  if (max_len == 1) min_len = 1; /* avoid "magic read" later */
	  l2 = max_len > fp->bufcnt ? fp->bufcnt : max_len;
	  if (l2 > 0)
	    {
	      memcpy(buf0, fp->buf + fp->bufptr, l2);
	      fp->bufcnt -= l2;
	      if (fp->bufcnt == 0)
		{
		  fp->bufptr = 0;
		  fp->buf[0] = '\0'; /* debug */
		}
	      else
		fp->bufptr += l2;
	      if (l2 >= min_len || l2 >= max_len)
		return l2;
	      max_len -= l2;
	      min_len -= l2;
	    }
	  if (min_len > fp->bufsz)
	    {
	      l1 = read_stream_connection_unbuffered(fd, (char*)buf0 + l2,
						     min_len, max_len);
	      if (l1 > 0)
		return l1 + l2;
	      else
		return l2;
	    }
	  /* Fill buffer */
	  l1 = read_stream_connection_unbuffered(fd, fp->buf, min_len, fp->bufsz);
	  if (l1 <= 0)
	    return l2;
	  
	  fp->bufcnt = l1;
	  l1 = max_len > fp->bufcnt ? fp->bufcnt : max_len;
	  memcpy((char*)buf0 + l2, fp->buf + fp->bufptr, l1);
	  fp->bufcnt -= l1;
	  if (fp->bufcnt == 0)
	    fp->bufptr = 0;
	  else
	    fp->bufptr += l1;
	  return l1 + l2;
	}
    }
  return read_stream_connection_unbuffered(fd, buf0, min_len, max_len);
}

int
read_stream_connection(fd, buf0, len)
 int fd;
 void* buf0;
 int len;
{
 return read_stream_connection_min(fd, buf0, -1, len);
}

static int
write_stream_connection4(fd, buf0, n, i_opt) 
 int fd;
 void * buf0;
 int n;
 int	i_opt;
{
  int			ret, count;
 unsigned char* buf = (unsigned char*)buf0;
 nessus_connection * fp;
  fd_set		fdr, fdw;
  struct timeval	tv;
  int e;

 if(!NESSUS_STREAM(fd))
   {
#if DEBUG_SSL > 0
     fprintf(stderr, "write_stream_connection: fd <%d> invalid\n", fd);
# if 0
     abort();
# endif
#endif
     errno = EINVAL;
     return -1;
    }

 fp = &(connections[fd - NESSUS_FD_OFF]);
 fp->last_err = 0;
 
#if DEBUG_SSL > 8
 fprintf(stderr, "> write_stream_connection(%d, 0x%x, %d, 0x%x) \tE=%d 0=0x%x\n",
	 fd, buf, n, i_opt, fp->transport, fp->options);
#endif

 switch(fp->transport)
 {
  case NESSUS_ENCAPS_IP:
   for(count = 0; count < n;)
   {
     if ((fp->options & NESSUS_CNX_IDS_EVASION_SEND_MASK) != 0)
     {
      if(fp->options & NESSUS_CNX_IDS_EVASION_SPLIT)
       /* IDS evasion */
       ret = send(fp->fd, buf + count, 1, i_opt);
     else 
       /* i_opt ignored for ids_send */
     	ret = ids_send(fp->fd, buf + count, n - count, fp->options);
     }
     else
       ret = send(fp->fd, buf + count, n - count, i_opt);

    if(ret <= 0)
      {
       if ( ret < 0 ) fp->last_err = errno;
       else fp->last_err = EPIPE;
       break;
      }
     
     count += ret;
    }
    break;

  case NESSUS_ENCAPS_SSLv2:
  case NESSUS_ENCAPS_SSLv23:
  case NESSUS_ENCAPS_SSLv3:
  case NESSUS_ENCAPS_TLSv1:

    /* i_opt ignored for SSL */
    for (count = 0; count < n;)
      {
	ret = gnutls_record_send(fp->tls_session, buf + count, n - count);

	if (ret > 0)
	  {
	    count += ret;
	  }
	else if (ret != GNUTLS_E_INTERRUPTED && ret != GNUTLS_E_AGAIN)
	  {
	    /* This branch also handles the case where ret == 0,
	     * i.e. that the connection has been closed.  This is
	     * for compatibility with the old nessus code which
	     * treated SSL_ERROR_ZERO_RETURN as an error too.
	     */
#ifdef DEBUG_SSL
	    if (ret < 0)
	      {
		tlserror("gnutls_record_send", ret);
	      }
	    else
	      {
		fprintf(stderr, "gnutls_record_send[%d]: EOF\n",
			getpid());
	      }
#endif
	    fp->last_err = EPIPE;
	    break;
	  }

	if (fp->timeout >= 0)
	  tv.tv_sec = fp->timeout;
	else
	  tv.tv_sec = TIMEOUT;
	tv.tv_usec = 0;

	do
	  {
	    errno = 0;
	    FD_ZERO(&fdr); FD_ZERO(&fdw);
	    FD_SET(fp->fd, &fdr); FD_SET(fp->fd, &fdw);
	    e = select(fp->fd+1, &fdr, &fdw, NULL, &tv);
	  }
	while (e < 0 && errno == EINTR);

	if (e <= 0)
	  {
#if DEBUG_SSL > 0
	    nessus_perror("select");
#endif
	    fp->last_err = ETIMEDOUT;
	    break;
	  }
      }
    break;

   default:
     if (fp->transport != -1 || fp->fd != 0)
       fprintf(stderr, "Severe bug! Unhandled transport layer %d (fd=%d)\n",
	       fp->transport, fd);
     else
       fprintf(stderr, "read_stream_connection_unbuffered: fd=%d is closed\n", fd);
     errno =EINVAL;
     return -1;
  }
 
  
  if(count == 0 && n > 0)
   return -1;
  else 
   return count;
}

int
write_stream_connection(fd, buf0, n) 
 int fd;
 void * buf0;
 int n;
{
  return write_stream_connection4(fd, buf0, n, 0);
}

int
nsend (fd, data, length, i_opt)
 int fd;
 void * data;
 int length, i_opt;
{
  int		n = 0;

 if(NESSUS_STREAM(fd))
 {
  if(connections[fd - NESSUS_FD_OFF].fd < 0)
   fprintf(stderr, "Nessus file descriptor %d closed ?!\n", fd);
  else 
    return write_stream_connection4(fd, data, length, i_opt);
 }
#if DEBUG_SSL > 1
 else
   fprintf(stderr, "nsend[%d]: fd=%d\n", getpid(), fd);
#endif
#if 0
   for (i = 0; i < NESSUS_FD_MAX; i ++)
     if (connections[i].fd == fd && connections[i].transport > 0)
       {
	 /* Fixing a severe bug! */
	 fprintf(stderr, "nsend: fd=%d used by Nessus FD %d\n",
		 fd, i + NESSUS_FD_OFF);
	 return write_stream_connection4(i + NESSUS_FD_OFF, data, length, i_opt);
       }
#endif
 /* Trying OS's send() */
   block_socket(fd);		/* ??? */
   do
 {
       struct timeval tv = {0,5};
       fd_set wr;
       int e;
       
       FD_ZERO(&wr);
       FD_SET(fd, &wr);
       
       errno = 0;
       e  = select(fd + 1, NULL, &wr, NULL, &tv);
       if ( e > 0 )
        n = os_send(fd, data, length, i_opt);
       else if ( e < 0 && errno == EINTR ) continue;
       else break;
     }
   while (n <= 0 && errno == EINTR);
   if (n < 0)
     fprintf(stderr, "[%d] nsend():send %s\n", getpid(), strerror(errno));
   return n;
 }
 
int
nrecv (fd, data, length, i_opt)
 int fd;
 void * data;
 int length, i_opt;
{
  int e;
#if DEBUG_SSL > 8
   fprintf(stderr, "nrecv: fd=%d len=%d\n", fd, length);
#endif
 if(NESSUS_STREAM(fd))
 {
  if(connections[fd - NESSUS_FD_OFF].fd < 0)
   fprintf(stderr, "Nessus file descriptor %d closed ?!\n", fd);
  else 
    return read_stream_connection(fd, data, length);
 }
 /* Trying OS's recv() 
  *
  * Do *NOT* use os_recv() here, as it will be blocking until the exact
  * amount of requested data arrives
  */
 block_socket(fd);
 do {
	e = recv(fd, data, length, i_opt);
 } while ( e < 0 && errno == EINTR );
 return e;
}
 

int
close_stream_connection(fd)
 int fd;
{
#if DEBUG_SSL > 2
 nessus_connection * fp;
 if(!NESSUS_STREAM(fd))
    {
     errno = EINVAL;
     return -1;
    }
  fp = &(connections[fd - NESSUS_FD_OFF]);
  fprintf(stderr, "close_stream_connection TCP:%d\n", fp->port);
#endif

  if(!NESSUS_STREAM(fd))	/* Will never happen if debug is on! */
   {
    if ( fd < 0 || fd > 1024 )
    {
	   errno = EINVAL;
	   return -1;
    }
   shutdown(fd, 2);
   return socket_close(fd);
   }
  else
   return release_connection_fd(fd);
}


int
get_encaps(fd)
 int fd;
{
 if(!NESSUS_STREAM(fd))
 {
   fprintf(stderr, "get_encaps() : bad argument\n");
   return -1;
 }
 return connections[fd - NESSUS_FD_OFF].transport;
}


 
const char *
get_encaps_name(code)
 int code;
{
 static char str[100];
 switch(code)
 {
  case NESSUS_ENCAPS_IP:
   return "IP";
  case NESSUS_ENCAPS_SSLv2:
    return "SSLv2";
  case NESSUS_ENCAPS_SSLv23:
    return "SSLv23";
  case NESSUS_ENCAPS_SSLv3:
    return "SSLv3";
  case NESSUS_ENCAPS_TLSv1:
    return "TLSv1";
  default:
   snprintf(str, sizeof(str), "[unknown transport layer - code %d (0x%x)]", code, code);
   return str;
 }
}

const char *
get_encaps_through(code)
 int code;
{
 static char str[100];
 switch(code)
 {
  case NESSUS_ENCAPS_IP:
   return "";
  case NESSUS_ENCAPS_SSLv2:
  case NESSUS_ENCAPS_SSLv23:
  case NESSUS_ENCAPS_SSLv3:
  case NESSUS_ENCAPS_TLSv1:
    return " through SSL";
  default:
    snprintf(str, sizeof(str), " through unknown transport layer - code %d (0x%x)", code, code);
    return str;
 }
}

static int
open_socket(struct sockaddr_in *paddr, 
	    int port, int type, int protocol, int timeout)
{
  fd_set		fd_w;
  struct timeval	to;
  int			soc, x;
  int			opt;
  unsigned int opt_sz;

  __port_closed = 0;

  if ((soc = socket(AF_INET, type, protocol)) < 0)
    {
      nessus_perror("socket");
      return -1;
    }

  if (timeout == -2)
    timeout = TIMEOUT;

  if (timeout > 0)
    if (unblock_socket(soc) < 0)
      {
	close(soc);
	return -1;
      }

  set_socket_source_addr(soc, 0);

#if defined NESSUS_CNX_LOCK
  if (lock_cnt == 0)
{
      lock_fd = open(NESSUS_CNX_LOCK, O_RDWR|O_CREAT);
      if (lock_fd < 0)
	nessus_perror(NESSUS_CNX_LOCK);
      else
	{
	  time_t	t1 = time(NULL), t2;
	  if (flock(lock_fd, LOCK_EX) < 0)
	    nessus_perror(NESSUS_CNX_LOCK);
	  else
	    {
	      lock_cnt ++;
	      t2 = time(NULL);
#if 1
	      if (t2 - t1 > 0)
		fprintf(stderr, "[%d] open_socket: " NESSUS_CNX_LOCK " locked in %d s\n", getpid(), t2 - t1);
#endif
	    }
	}
    }
  else
    {
#if 1
      fprintf(stderr, "[%d] open_socket: sleeping 1 second\n", getpid());
#endif
      sleep(1);
    }
#endif  
  
  if (connect(soc, (struct sockaddr*) paddr, sizeof(*paddr)) < 0)
    {
#if DEBUG_SSL > 2
      nessus_perror("connect");
#endif
again:
      switch (errno)
	{
	case EINPROGRESS:
	case EAGAIN:
	  FD_ZERO(&fd_w);
	  FD_SET(soc, &fd_w);
	  to.tv_sec = timeout;
	  to.tv_usec = 0;
	  x = select(soc + 1, NULL, &fd_w, NULL, &to);
	  if (x == 0)
	    {
#if DEBUG_SSL > 2
	      nessus_perror("connect->select: timeout");
#endif
	      socket_close(soc);
	      errno = ETIMEDOUT;
	      return -1;
	    }
	  else if (x < 0)
	    {
	      if ( errno == EINTR )
               {
 		 errno = EAGAIN;
		 goto again;
	       }
	      nessus_perror("select");
	      socket_close(soc);
	      return -1;
            }
 
	  opt = 0; opt_sz = sizeof(opt);
	  if (getsockopt(soc, SOL_SOCKET, SO_ERROR, &opt, &opt_sz) < 0)
	    {
	      nessus_perror("getsockopt");
	      socket_close(soc);
	      return -1;
	    }
	  if (opt == 0)
	    break;
#if DEBUG_SSL > 2
	  errno = opt;
	  nessus_perror("SO_ERROR");
#endif
	  /* no break; go on */	  
	default:
	  __port_closed = 1;
	  socket_close(soc);
	  return  -1;
	}
    }
  block_socket(soc);
  return soc;
}


int open_sock_opt_hn(hostname, port, type, protocol, timeout)
 const char * hostname; 
 unsigned int port; 
 int type;
 int protocol;
 int timeout;
{
 struct sockaddr_in addr;
  
  bzero((void*)&addr, sizeof(addr));
  addr.sin_family=AF_INET;
  addr.sin_port=htons((unsigned short)port);
  addr.sin_addr = nn_resolve(hostname);
  if (addr.sin_addr.s_addr == INADDR_NONE || addr.sin_addr.s_addr == 0)
    {
      fprintf(stderr, "open_sock_opt_hn: invalid socket address\n");
      return  -1;
    }
   
  return open_socket(&addr, port, type, protocol, timeout);
}


int open_sock_tcp_hn(hostname, port)
 const char * hostname;
 unsigned int port;
{
  return open_sock_opt_hn(hostname, port, SOCK_STREAM, IPPROTO_TCP, TIMEOUT);
}


int open_sock_tcp(args, port, timeout)
 struct arglist * args; 
 unsigned int port;
 int timeout;
{
  char name[32];
  int ret;
  int type;
  

  /*
   * If we timed out against this port in the past, there's no need
   * to scan it again
   */
  snprintf(name, sizeof(name), "/tmp/ConnectTimeout/TCP/%d", port);
  if ( plug_get_key ( args, name, &type ) ) 
	return -1;


  errno = 0;
  ret  = open_sock_option(args, port, SOCK_STREAM,IPPROTO_TCP, timeout);
  if ( ret < 0 && errno == ETIMEDOUT )
    plug_set_key( args, name, ARG_INT, (void*)1); 

  return ret;
}


int open_sock_udp(args, port)
 struct arglist * args;
 unsigned int port;
{
  return open_sock_option(args, port, SOCK_DGRAM, IPPROTO_UDP, 0);
}


struct in_addr _socket_get_next_source_addr(struct in_addr * addr)
{
  static struct in_addr * src_addrs = NULL;
  static int current_src_addr = 0;
  static pid_t current_src_addr_pid = 0;
  static int num_addrs = 0;
  struct in_addr ret;
  pid_t mypid;
  
  if( current_src_addr < 0 )
  {
   ret.s_addr = INADDR_ANY;
   return ret;
  }
  
  
  
  if ( src_addrs == NULL && current_src_addr == 0 )
  {
    src_addrs = addr;
    if( src_addrs == NULL ) 
    {
     ret.s_addr = INADDR_ANY;
     current_src_addr = -1;
     return ret;
    }    	
   
   num_addrs = -1;
   while(src_addrs[++num_addrs].s_addr != 0 ) ;
  }
  
  
  mypid = getpid();
  if ( current_src_addr_pid != mypid )
   {
    current_src_addr_pid = mypid;
    current_src_addr = lrand48() % ( num_addrs ) ;
    if ( src_addrs[current_src_addr].s_addr == 0 ) current_src_addr = 0;
   }
  
  return src_addrs[current_src_addr];
}

struct in_addr socket_get_next_source_addr()
{
 return _socket_get_next_source_addr(NULL);
}

int set_socket_source_addr(int soc, int port)
{ 
  struct sockaddr_in bnd;
  int opt = 1;  
  
  struct in_addr src = _socket_get_next_source_addr(NULL);
  
  if( src.s_addr == INADDR_ANY && port == 0 ) /* No need to bind() */
  	return 0;
   
  setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, (void*)&opt, sizeof(int));
  bzero(&bnd, sizeof(bnd));
  
   
   
   bnd.sin_port = htons(port);
   bnd.sin_addr = src;
   bnd.sin_family = AF_INET;
  
  if( bind(soc, (struct sockaddr*)&bnd, sizeof(bnd)) < 0 )
  { 
   return -1;
  }
  
  return 0;
}

void socket_source_init(struct in_addr * addr)
{
 (void) _socket_get_next_source_addr(addr);
}


int open_sock_option(args, port, type, protocol, timeout)
 struct arglist * args;
 unsigned int port;
 int type;
 int protocol;
 int timeout;
{
  struct sockaddr_in addr;
  struct in_addr * t;

#if 0
  /* 
   * MA 2004-08-15: IMHO, as this is often (always?) tested in the NASL scripts
   * this should not be here. 
   * If it has to be somewhere else, I'd rather put it in libnasl (and add
   * a parameter to "force" the connection)
   */
  if(host_get_port_state(args, port)<=0)return(-1);
#endif
  bzero((void*)&addr, sizeof(addr));
  addr.sin_family=AF_INET;
  addr.sin_port=htons((unsigned short)port);
  t = plug_get_host_ip(args);
  if(!t)
  {
   fprintf(stderr, "ERROR ! NO ADDRESS ASSOCIATED WITH NAME\n");
   arg_dump(args, 0);
   return(-1);
  }
  addr.sin_addr = *t;
  if (addr.sin_addr.s_addr == INADDR_NONE)
    return(-1);
    
  return open_socket(&addr, port, type, protocol, timeout);
}


/* This function reads a text from the socket stream into the
   argument buffer, always appending a '\0' byte.  The return
   value is the number of bytes read, without the trailing '\0'.
 */


int recv_line(soc, buf, bufsiz)
 int soc;
 char * buf;
 size_t bufsiz;
{
  int n, ret = 0;
  
  /*
   * Dirty SSL hack
   */
  if(NESSUS_STREAM(soc))
  {
   buf[0] = '\0';
   
   do
   {
    n = read_stream_connection_min (soc, buf + ret, 1, 1);
    switch (n)
    {
     case -1 :
       if(ret == 0)
        return -1;
       else 
        return ret;
       break;
     
     case 0:
       return ret;
       break;
      
      default :
      	ret ++;
    }
   }
   while (buf [ret-1] != '\0' && buf [ret-1] != '\n' && ret < bufsiz) ;
   
   if(ret > 0 )
   {
   if (buf[ret - 1] != '\0')
	{
	if ( ret < bufsiz ) 
		buf[ ret ] = '\0';
	else 
		buf [ bufsiz - 1 ] = '\0';
	}
   }
   return ret;  
  }
  else
  {
   fd_set rd;
   struct timeval tv;
   
   do
   {
      int e;
 again:
      errno = 0;
      FD_ZERO(&rd);
      FD_SET(soc, &rd);
      tv.tv_sec = 5;
      tv.tv_usec = 0;
      e = select(soc+1, &rd, NULL, NULL, &tv); 
      if( e < 0 && errno == EINTR) goto again;
      if( e > 0 )
      {
       n = recv(soc, buf + ret, 1, 0);
       switch(n)
       {
        case -1 :
	 if ( errno == EINTR ) continue;
	 if(ret == 0)
	  return -1;
	 else
	  return ret;
	 break;  
       case 0 :
         return ret;
       	 break;
       default:
         ret ++;	
       }
      } 
      else break;
      tv.tv_sec = 1;
      tv.tv_usec = 0;
    } while(buf[ret -1 ] != '\0' && buf[ret -1 ] != '\n' && ret < bufsiz);
    
    if(ret > 0)
    {
    if(buf[ret - 1] != '\0')
      {
	if ( ret < bufsiz )
	      	buf[ret] = '\0';
	else
		buf[bufsiz - 1] = '\0';
      }
    }
  }
  return ret;
} 

int
socket_close(soc)
int soc;
{
#if defined NESSUS_CNX_LOCK
  if (lock_cnt > 0)
    if (-- lock_cnt == 0)
      {
	if (flock(lock_fd, LOCK_UN) < 0)
	  nessus_perror(NESSUS_CNX_LOCK);
	if (close(lock_fd) < 0)
	  nessus_perror(NESSUS_CNX_LOCK);
	lock_fd = -1;
      }
#endif  
  return close(soc);
}

/*
 * auth_printf()
 *
 * Writes data to the global socket of the thread
 */
void
auth_printf(struct arglist * globals, char * data, ...)
{
  va_list param;
  char buffer[65535];
  
  bzero(buffer, sizeof(buffer));

  va_start(param, data);
  vsnprintf(buffer, sizeof(buffer) - 1, data, param);
  
  va_end(param);
  auth_send(globals, buffer);
}                    


void
auth_send(struct arglist * globals, char * data)
{
 int soc = (int)arg_get_value(globals, "global_socket");
 int confirm = (int)arg_get_value(globals, "confirm");
 int n = 0;
 int length;
 int sent = 0;

 if(soc < 0)
  return;

#ifndef NESSUSNT
 signal(SIGPIPE, _exit);
#endif
 length = strlen(data);
 while(sent < length)
 {
 n = nsend(soc, data+sent, length-sent, 0);
 if(n < 0)
 {
  if((errno == ENOMEM)
#ifdef ENOBUFS  
   ||(errno==ENOBUFS)
#endif   
   )
   n = 0;
  else
   {
   nessus_perror("nsend");
   goto out;
   }
 }
 else sent+=n;
 }
 
 if(confirm)
 {
  /*
   * If confirm is set, then we are a son
   * trying to report some message to our busy
   * father. So we wait until he told us he
   * took care of it
   */
  char n;
  read_stream_connection_min(soc, &n, 1, 1);
 }
out:
#ifndef NESSUSNT
  signal(SIGPIPE, SIG_IGN);
#else
 ;
#endif
}

/*
 * auth_gets()
 *
 * Reads data from the global socket of the thread
 */
char *
auth_gets(globals, buf, bufsiz)
     struct arglist * globals;
     char * buf;
     size_t bufsiz;
{
  int soc = (int)arg_get_value(globals, "global_socket");
  int n;
  /* bzero(buf, bufsiz); */
  n = recv_line(soc, buf, bufsiz);
  if(n <= 0)
	  return NULL;
  
  return(buf);
}


/*
 * Select() routines
 */
 
int
stream_zero(set)
 fd_set * set;
{ 
 FD_ZERO(set);
 return 0;
}

int
stream_set(fd, set)
 int fd;
 fd_set * set;
{
 int soc = nessus_get_socket_from_connection(fd);
 if(soc >= 0)
  FD_SET(soc, set);
 return soc;
}

int
stream_isset(fd, set)
 int fd;
 fd_set * set;
{
 return FD_ISSET(nessus_get_socket_from_connection(fd), set);
}

int
fd_is_stream(fd)
     int	fd;
{
  return NESSUS_STREAM(fd);	/* Should probably be smarter... */
}


int 
stream_get_buffer_sz ( int fd )
{
  nessus_connection	*p;
  if (! NESSUS_STREAM(fd))
    return -1;
  p = &(connections[fd - NESSUS_FD_OFF]);
  return p->bufsz;
}


int
stream_set_buffer(fd, sz)
     int	fd, sz;
{
  nessus_connection	*p;
  char			*b;

  if (! NESSUS_STREAM(fd))
    return -1;

  p = &(connections[fd - NESSUS_FD_OFF]);
  if (sz < p->bufcnt)
      return -1;		/* Do not want to lose data */

  if (sz == 0)
    {
      efree(&p->buf);
      p->bufsz = 0;
      return 0;
    }
  else if (p->buf == 0)
    {
      p->buf = malloc(sz);
      if (p->buf == NULL)
	return -1;
      p->bufsz = sz;
      p->bufptr = 0;
      p->bufcnt = 0;
      return 0;
    }
  else
    {
      if (p->bufcnt > 0)
	{
	  memmove(p->buf, p->buf + p->bufptr, p->bufcnt);
	  p->bufptr = 0;
	}
      b = realloc(p->buf, sz);
      if (b == NULL)
	return -1;
      p->bufsz = sz;
      return 0;
    }
  /*NOTREACHED*/
}



/*------------------------------------------------------------------*/


int os_send(int soc, void * buf, int len, int opt )
{
 char * buf0 = (char*)buf;
 int e, n;
 for ( n = 0 ; n < len ; ) 
 {
  errno = 0;
  e = send(soc, buf0 + n , len -  n, opt);
  if ( e < 0 && errno == EINTR ) continue; 
  else if ( e <= 0 ) return -1;
  else n += e;
 }
 return n;
}

int os_recv(int soc, void * buf, int len, int opt )
{
 char * buf0 = (char*)buf;
 int e, n;
 for ( n = 0 ; n < len ; ) 
 {
  errno = 0;
  e = recv(soc, buf0 + n , len -  n, opt);
  if ( e < 0 && errno == EINTR ) continue; 
  else if ( e <= 0 ) return -1;
  else n += e;
 }
 return n;
}


/* 
 * internal_send() / internal_recv() :
 *
 * When processes are passing messages to each other, the format is
 * <length><msg>, with <length> being a long integer. The functions
 * internal_send() and internal_recv() encapsulate and decapsulate
 * the messages themselves. 
 */
int internal_send(int soc, char * data, int msg_type )
{
 int len;
 int e;
 int ack;
 
 if ( data == NULL )
	data = "";

 e = os_send(soc, &msg_type, sizeof(len), 0 );
 if ( e < 0 ) return -1;

 if ( (msg_type & INTERNAL_COMM_MSG_TYPE_CTRL) == 0 )
  {
 len = strlen(data);

 e = os_send(soc, &len, sizeof(len), 0 );
 if ( e < 0 ) return -1;
 e = os_send(soc, data, len, 0 );
 if ( e < 0 ) return -1;
 }

 e = os_recv(soc, &ack, sizeof(ack), 0);
 if ( e < 0 ){
	fprintf(stderr, "internal_send->os_recv(%d): %s\n",soc, strerror(errno));
	return -1;
	}

 return 0;
}


int internal_recv(int soc, char ** data, int * data_sz, int * msg_type )
{
 int len = 0;
 int e;
 char * buf = *data;
 int    sz  = *data_sz;
 int type;
 int ack;
 
 if ( buf == NULL )
 {
  sz = 65535;
  buf = emalloc ( sz );
 }

   
 e = os_recv(soc, &type, sizeof(type), 0 );
 if ( e < 0 ) goto error;

 if ( (type & INTERNAL_COMM_MSG_TYPE_CTRL) == 0 )
 {
 e = os_recv(soc, &len, sizeof(len), 0);
 if ( e < 0 ) goto error;
 
 if ( len >= sz )
 {
  sz = len + 1;
  buf = erealloc( buf, sz );
 }

 if ( len > 0 )
 {
 e = os_recv(soc, buf,len, 0);
 if ( e < 0 ) goto error;
 buf[len] = '\0';
 }

 if ( data != NULL )
 	*data = buf;
 if ( data_sz != NULL )
 	*data_sz = sz;
 }
 
 *msg_type = type;
 ack = INTERNAL_COMM_MSG_TYPE_CTRL | INTERNAL_COMM_CTRL_ACK;
 e = os_send(soc, &ack, sizeof(ack), 0);
 if ( e < 0 ) goto error;

 
 return len;
error:
 efree(&buf);
 *data = NULL;
 *data_sz = 0;
 return -1;
}


int stream_pending(int fd)
{
  nessus_connection * fp;
 if ( ! NESSUS_STREAM(fd) )
 {
  errno = EINVAL;
  return -1;
 }
 fp = &(connections[fd - NESSUS_FD_OFF]);

 if ( fp->bufcnt )
        return fp->bufcnt;
 else if ( fp->transport != NESSUS_ENCAPS_IP )
        return gnutls_record_check_pending(fp->tls_session);
 return 0;
}