File: osscan2.cc

package info (click to toggle)
nmap 6.00-0.3+deb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 55,576 kB
  • sloc: ansic: 108,190; cpp: 60,191; sh: 19,314; python: 16,531; xml: 9,428; makefile: 2,473; perl: 1,980; yacc: 608; lex: 469; asm: 372
file content (3638 lines) | stat: -rw-r--r-- 113,106 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
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
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638

/***************************************************************************
 * osscan2.cc -- Routines used for 2nd Generation OS detection via         *
 * TCP/IP fingerprinting.  * For more information on how this works in     *
 * Nmap, see http://nmap.org/osdetect/                                     *
 *                                                                         *
 ***********************IMPORTANT NMAP LICENSE TERMS************************
 *                                                                         *
 * The Nmap Security Scanner is (C) 1996-2012 Insecure.Com LLC. Nmap is    *
 * also a registered trademark of Insecure.Com LLC.  This program is free  *
 * software; you may redistribute and/or modify it under the terms of the  *
 * GNU General Public License as published by the Free Software            *
 * Foundation; Version 2 with the clarifications and exceptions described  *
 * below.  This guarantees your right to use, modify, and redistribute     *
 * this software under certain conditions.  If you wish to embed Nmap      *
 * technology into proprietary software, we sell alternative licenses      *
 * (contact sales@insecure.com).  Dozens of software vendors already       *
 * license Nmap technology such as host discovery, port scanning, OS       *
 * detection, version detection, and the Nmap Scripting Engine.            *
 *                                                                         *
 * Note that the GPL places important restrictions on "derived works", yet *
 * it does not provide a detailed definition of that term.  To avoid       *
 * misunderstandings, we interpret that term as broadly as copyright law   *
 * allows.  For example, we consider an application to constitute a        *
 * "derivative work" for the purpose of this license if it does any of the *
 * following:                                                              *
 * o Integrates source code from Nmap                                      *
 * o Reads or includes Nmap copyrighted data files, such as                *
 *   nmap-os-db or nmap-service-probes.                                    *
 * o Executes Nmap and parses the results (as opposed to typical shell or  *
 *   execution-menu apps, which simply display raw Nmap output and so are  *
 *   not derivative works.)                                                *
 * o Integrates/includes/aggregates Nmap into a proprietary executable     *
 *   installer, such as those produced by InstallShield.                   *
 * o Links to a library or executes a program that does any of the above   *
 *                                                                         *
 * The term "Nmap" should be taken to also include any portions or derived *
 * works of Nmap, as well as other software we distribute under this       *
 * license such as Zenmap, Ncat, and Nping.  This list is not exclusive,   *
 * but is meant to clarify our interpretation of derived works with some   *
 * common examples.  Our interpretation applies only to Nmap--we don't     *
 * speak for other people's GPL works.                                     *
 *                                                                         *
 * If you have any questions about the GPL licensing restrictions on using *
 * Nmap in non-GPL works, we would be happy to help.  As mentioned above,  *
 * we also offer alternative license to integrate Nmap into proprietary    *
 * applications and appliances.  These contracts have been sold to dozens  *
 * of software vendors, and generally include a perpetual license as well  *
 * as providing for priority support and updates.  They also fund the      *
 * continued development of Nmap.  Please email sales@insecure.com for     *
 * further information.                                                    *
 *                                                                         *
 * As a special exception to the GPL terms, Insecure.Com LLC grants        *
 * permission to link the code of this program with any version of the     *
 * OpenSSL library which is distributed under a license identical to that  *
 * listed in the included docs/licenses/OpenSSL.txt file, and distribute   *
 * linked combinations including the two. You must obey the GNU GPL in all *
 * respects for all of the code used other than OpenSSL.  If you modify    *
 * this file, you may extend this exception to your version of the file,   *
 * but you are not obligated to do so.                                     *
 *                                                                         *
 * If you received these files with a written license agreement or         *
 * contract stating terms other than the terms above, then that            *
 * alternative license agreement takes precedence over these comments.     *
 *                                                                         *
 * Source is provided to this software because we believe users have a     *
 * right to know exactly what a program is going to do before they run it. *
 * This also allows you to audit the software for security holes (none     *
 * have been found so far).                                                *
 *                                                                         *
 * Source code also allows you to port Nmap to new platforms, fix bugs,    *
 * and add new features.  You are highly encouraged to send your changes   *
 * to nmap-dev@insecure.org for possible incorporation into the main       *
 * distribution.  By sending these changes to Fyodor or one of the         *
 * Insecure.Org development mailing lists, or checking them into the Nmap  *
 * source code repository, it is understood (unless you specify otherwise) *
 * that you are offering the Nmap Project (Insecure.Com LLC) the           *
 * unlimited, non-exclusive right to reuse, modify, and relicense the      *
 * code.  Nmap will always be available Open Source, but this is important *
 * because the inability to relicense code has caused devastating problems *
 * for other Free Software projects (such as KDE and NASM).  We also       *
 * occasionally relicense the code to third parties as discussed above.    *
 * If you wish to specify special license conditions of your               *
 * contributions, just say so when you send them.                          *
 *                                                                         *
 * This program is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of              *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *
 * General Public License v2.0 for more details at                         *
 * http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file       *
 * included with Nmap.                                                     *
 *                                                                         *
 ***************************************************************************/

/* $Id: osscan2.cc 28192 2012-03-01 06:53:35Z fyodor $ */

#include "osscan.h"
#include "osscan2.h"
#include "timing.h"
#include "NmapOps.h"
#include "Target.h"
#include "utils.h"
#include "FPEngine.h"
#include <dnet.h>

#include "struct_ip.h"

#include <list>

using namespace std;
extern NmapOps o;

/* 8 options:
 *  0~5: six options for SEQ/OPS/WIN/T1 probes.
 *  6:   ECN probe.
 *  7-12:   T2~T7 probes.
 *
 * option 0: WScale (10), Nop, MSS (1460), Timestamp, SackP
 * option 1: MSS (1400), WScale (0), SackP, T(0xFFFFFFFF,0x0), EOL
 * option 2: T(0xFFFFFFFF, 0x0), Nop, Nop, WScale (5), Nop, MSS (640)
 * option 3: SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
 * option 4: MSS (536), SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
 * option 5: MSS (265), SackP, T(0xFFFFFFFF,0x0)
 * option 6: WScale (10), Nop, MSS (1460), SackP, Nop, Nop
 * option 7-11: WScale (10), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP
 * option 12: WScale (15), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP
 */
static struct {
  u8* val;
  int len;
} prbOpts[] = {
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x05\xb4\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x02\x04\x05\x78\x03\x03\x00\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x00", 20},
  {(u8*) "\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x01\x01\x03\x03\x05\x01\x02\x04\x02\x80", 20},
  {(u8*) "\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 16},
  {(u8*) "\x02\x04\x02\x18\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 20},
  {(u8*) "\x02\x04\x01\x09\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00", 16},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x05\xb4\x04\x02\x01\x01", 12},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
  {(u8*) "\x03\x03\x0f\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20}
};

/* TCP Window sizes. Numbering is the same as for prbOpts[] */
u16 prbWindowSz[] = { 1, 63, 4, 4, 16, 512, 3, 128, 256, 1024, 31337, 32768, 65535 };

/* Current time. It is globally accessible so it can save calls to gettimeofday() */
static struct timeval now;

/* Global to store performance info */
struct scan_performance_vars perf;


/******************************************************************************
 * Miscellaneous functions                                                    *
 ******************************************************************************/

/* Fill in a struct AVal with a value based on the IP ID sequence generation
   class (one of the IPID_SEQ_* constants). If ipid_seqclass is such that the
   test result should be omitted, the function returns NULL and doesn't modify
   *av. Otherwise, it returns av after filling in the information. */
static struct AVal *make_aval_ipid_seq(struct AVal *av, const char *attribute,
                                       int ipid_seqclass, int ipids[NUM_SEQ_SAMPLES]) {
  switch (ipid_seqclass) {
  case IPID_SEQ_CONSTANT:
    av->value = string_pool_sprintf("%X", ipids[0]);
    break;
  case IPID_SEQ_INCR:
    av->value = "I";
    break;
  case IPID_SEQ_BROKEN_INCR:
    av->value = "BI";
    break;
  case IPID_SEQ_RPI:
    av->value = "RI";
    break;
  case IPID_SEQ_RD:
    av->value = "RD";
    break;
  case IPID_SEQ_ZERO:
    av->value = "Z";
    break;
  default:
    /* Signal to omit test result. */
    return NULL;
    break;
  }

  av->attribute = string_pool_insert(attribute);

  return av;
}


/* Returns a guess about the original TTL based on an observed TTL value.
 * This function assumes that the target from which we received the packet was
 * less than 32 hops away. Also, note that although some systems use an
 * initial TTL of 60, this function rounds that to 64, as both values
 * cannot be reliably distinguished based on a simple observed hop count. */
int get_initial_ttl_guess(u8 ttl) {
  if (ttl <= 32)
    return 32;
  else if (ttl <= 64)
    return 64;
  else if (ttl <= 128)
    return 128;
  else
    return 255;
}


/* This function takes an array of "numSamples" IP IDs and analyzes
 them to determine their sequenceability classification.  It returns
 one of the IPID_SEQ_* classifications defined in nmap.h .  If the
 function cannot determine the sequence, IPID_SEQ_UNKNOWN is returned.
 This islocalhost argument is a boolean specifying whether these
 numbers were generated by scanning localhost.  NOTE: the "ipids" argument
 may be modified if localhost is set to true. */
int get_ipid_sequence(int numSamples, int *ipids, int islocalhost) {
  u16 ipid_diffs[32];
  int i, j, k;
  int allipideqz = 1;  /* Flag that means "All IP.IDs returned during sequencing
                        * are zero. This is unset if we find a nonzero */

  assert(numSamples < (int) (sizeof(ipid_diffs) / 2));
  if (numSamples < 2)
    return IPID_SEQ_UNKNOWN;

  for (i = 1; i < numSamples; i++) {
    if (ipids[i - 1] != 0 || ipids[i] != 0)
      allipideqz = 0; /* All IP.ID values do *NOT* equal zero */

    if (ipids[i - 1] <= ipids[i]) {
        ipid_diffs[i - 1] = ipids[i] - ipids[i - 1];
    } else {
        ipid_diffs[i - 1] = (u16) (ipids[i] - ipids[i - 1] + 65536);
    }

  /* Random */
  if (numSamples > 2 && ipid_diffs[i - 1] > 20000)
      return IPID_SEQ_RD;
  }

  /* ZERO */
  if (allipideqz)
    return IPID_SEQ_ZERO;

  if (islocalhost) {
    int allgto = 1; /* ALL diffs greater than one */

    for (i = 0; i < numSamples - 1; i++) {
      if (ipid_diffs[i] < 2) {
        allgto = 0; break;
      }
    }

    if (allgto) {
      for (i = 0; i < numSamples - 1; i++) {
        if (ipid_diffs[i] % 256 == 0) /* Stupid MS */
          ipid_diffs[i] -= 256;
        else
          ipid_diffs[i]--; /* Because on localhost the RST sent back use an IPID */
      }
    }
  }

  /* Constant */
  j = 1; /* j is a flag meaning "all differences seen are zero" */
  for (i = 0; i < numSamples - 1; i++) {
    if (ipid_diffs[i] != 0) {
        j = 0;
    break;
    }
  }
  if (j) {
    return IPID_SEQ_CONSTANT;
  }

  /* Random Positive Increments */
  for (i = 0; i < numSamples - 1; i++) {
    if (ipid_diffs[i] > 1000 &&
        (ipid_diffs[i] % 256 != 0 ||
        (ipid_diffs[i] % 256 == 0 && ipid_diffs[i] >= 25600))) {
      return IPID_SEQ_RPI;
      }
    }

  j = 1; /* j is a flag meaning "all differences seen are < 10" */
  k = 1; /* k is a flag meaning "all difference seen are multiples of 256 and
          * no greater than 5120" */
  for (i = 0; i < numSamples - 1; i++) {
    if (k && (ipid_diffs[i] > 5120 || ipid_diffs[i] % 256 != 0)) {
      k = 0;
    }

    if (j && ipid_diffs[i] > 9) {
      j = 0;
    }
  }

  /* Broken Increment */
  if (k == 1) {
    return IPID_SEQ_BROKEN_INCR;
  }

  /* Incremental */
  if (j == 1)
    return IPID_SEQ_INCR;

  return IPID_SEQ_UNKNOWN;
}


/* Start the timeout clocks of any targets that aren't already timedout */
static void startTimeOutClocks(OsScanInfo *OSI) {
  list<HostOsScanInfo *>::iterator hostI;

  gettimeofday(&now, NULL);
  for (hostI = OSI->incompleteHosts.begin();
       hostI != OSI->incompleteHosts.end(); hostI++) {
    if (!(*hostI)->target->timedOut(NULL))
      (*hostI)->target->startTimeOutClock(&now);
  }
}


/** Sets up the pcap descriptor in HOS (obtains a descriptor and sets the
 * appropriate BPF filter, based on the supplied list of targets). */
static void begin_sniffer(HostOsScan *HOS, vector<Target *> &Targets) {
  char pcap_filter[2048];
  /* 20 IPv6 addresses is max (45 byte addy + 14 (" or src host ")) * 20 == 1180 */
  char dst_hosts[1200];
  int filterlen = 0;
  int len;
  unsigned int targetno;
  bool doIndividual = Targets.size() <= 20; // Don't bother IP limits if scanning huge # of hosts
  pcap_filter[0] = '\0';

  /* If we have 20 or less targets, build a list of addresses so we can set
   * an explicit BPF filter */
  if (doIndividual) {
    for (targetno = 0; targetno < Targets.size(); targetno++) {
      len = Snprintf(dst_hosts + filterlen,
                     sizeof(dst_hosts) - filterlen,
                     "%ssrc host %s", (targetno == 0)? "" : " or ",
                     Targets[targetno]->targetipstr());
      if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
        fatal("ran out of space in dst_hosts");
      filterlen += len;
    }
    len = Snprintf(dst_hosts + filterlen, sizeof(dst_hosts) - filterlen, ")))");
    if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
      fatal("ran out of space in dst_hosts");
  }

  /* Open a network interface for packet capture */
  HOS->pd = my_pcap_open_live(Targets[0]->deviceName(), 8192,
    o.spoofsource ? 1 : 0, pcap_selectable_fd_valid() ? 200 : 2);
  if (HOS->pd == NULL)
    fatal("%s", PCAP_OPEN_ERRMSG);

  /* Build the final BPF filter */
  if (doIndividual)
    len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s and (icmp or (tcp and (%s",
                   inet_ntoa(Targets[0]->v4source()), dst_hosts);
  else
    len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s and (icmp or tcp)",
                   inet_ntoa(Targets[0]->v4source()));
  if (len < 0 || len >= (int) sizeof(pcap_filter))
    fatal("ran out of space in pcap filter");

  /* Compile and apply the filter to the pcap descriptor */
  if (o.debugging)
    log_write(LOG_PLAIN, "Packet capture filter (device %s): %s\n", Targets[0]->deviceFullName(), pcap_filter);
  set_pcap_filter(Targets[0]->deviceFullName(), HOS->pd, pcap_filter);

  return;
}


/* Sets everything up so the current round can be performed. This includes
 * reinitializing some variables of the supplied objects and deleting
 * some old information. */
static void startRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;

  /* Reinitial some parameters of the scan system. */
  HOS->reInitScanSystem();

  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
    hsi = *hostI;
    if (hsi->FPs[roundNum]) {
      delete hsi->FPs[roundNum];
      hsi->FPs[roundNum] = NULL;
    }
    hsi->hss->initScanStats();
  }
}

/* Run the sequence generation tests (6 TCP probes sent 100ms apart) */
static void doSeqTests(OsScanInfo *OSI, HostOsScan *HOS) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;
  HostOsScanStats *hss = NULL;
  unsigned int unableToSend = 0;  /* # of times in a row that hosts were unable to send probe */
  unsigned int expectReplies = 0;
  long to_usec = 0;
  int timeToSleep = 0;
  struct ip *ip = NULL;
  struct link_header linkhdr;
  struct sockaddr_storage ss;
  unsigned int bytes = 0;
  struct timeval rcvdtime;
  struct timeval stime;
  struct timeval tmptv;
  bool timedout = false;
  bool thisHostGood = false;
  bool foundgood = false;
  bool goodResponse = false;
  int numProbesLeft = 0;

  memset(&stime, 0, sizeof(stime));
  memset(&tmptv, 0, sizeof(tmptv));

  /* For each host, build a list of sequence probes to send */
  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
    hsi = *hostI;
    hss = hsi->hss;
    HOS->buildSeqProbeList(hss);
  }

  /* Iterate until we have sent all the probes */
  do {
    if (timeToSleep > 0) {
      if (o.debugging > 1)
        log_write(LOG_PLAIN, "Sleep %dus for next sequence probe\n", timeToSleep);
      usleep(timeToSleep);
    }

    gettimeofday(&now, NULL);
    expectReplies = 0;
    unableToSend = 0;

    if (o.debugging > 2) {
      for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
        hss = (*hostI)->hss;
        log_write(LOG_PLAIN, "Host %s. ProbesToSend %d: \tProbesActive %d\n",
                  hss->target->targetipstr(), hss->numProbesToSend(),
                  hss->numProbesActive());
      }
    }

    /* Send a seq probe to each host. */
    while (unableToSend < OSI->numIncompleteHosts() && HOS->stats->sendOK()) {
      hsi = OSI->nextIncompleteHost();
      hss = hsi->hss;
      gettimeofday(&now, NULL);
      if (hss->numProbesToSend()>0 && HOS->hostSeqSendOK(hss, NULL)) {
        HOS->sendNextProbe(hss);
        expectReplies++;
        unableToSend = 0;
      } else {
        unableToSend++;
      }
    }

    HOS->stats->num_probes_sent_at_last_wait = HOS->stats->num_probes_sent;

    gettimeofday(&now, NULL);

    /* Count the pcap wait time. */
    if (!HOS->stats->sendOK()) {
      TIMEVAL_MSEC_ADD(stime, now, 1000);

      for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
        if (HOS->nextTimeout((*hostI)->hss, &tmptv)) {
          if (TIMEVAL_SUBTRACT(tmptv, stime) < 0)
            stime = tmptv;
        }
      }
    } else {
      foundgood = false;
      for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
        thisHostGood = HOS->hostSeqSendOK((*hostI)->hss, &tmptv);
        if (thisHostGood) {
          stime = tmptv;
          foundgood = true;
          break;
        }

        if (!foundgood || TIMEVAL_SUBTRACT(tmptv, stime) < 0) {
          stime = tmptv;
          foundgood = true;
        }
      }
    }

    do {
      to_usec = TIMEVAL_SUBTRACT(stime, now);
      if (to_usec < 2000)
        to_usec = 2000;

      if (o.debugging > 2)
        log_write(LOG_PLAIN, "pcap wait time is %ld.\n", to_usec);

      ip = (struct ip*) readipv4_pcap(HOS->pd, &bytes, to_usec, &rcvdtime, &linkhdr, true);

      gettimeofday(&now, NULL);

      if (!ip && TIMEVAL_SUBTRACT(stime, now) < 0) {
        timedout = true;
        break;
      } else if (!ip) {
        continue;
      }

      if (TIMEVAL_SUBTRACT(now, stime) > 200000) {
        /* While packets are still being received, I'll be generous and give
           an extra 1/5 sec.  But we have to draw the line somewhere */
        timedout = true;
      }

      if (bytes < (4 * ip->ip_hl) + 4U)
        continue;

      memset(&ss, 0, sizeof(ss));
      ((struct sockaddr_in *) &ss)->sin_addr.s_addr = ip->ip_src.s_addr;
      ss.ss_family = AF_INET;
      hsi = OSI->findIncompleteHost(&ss);
      if (!hsi)
        continue; /* Not from one of our targets. */
      setTargetMACIfAvailable(hsi->target, &linkhdr, &ss, 0);

      goodResponse = HOS->processResp(hsi->hss, ip, bytes, &rcvdtime);

      if (goodResponse)
        expectReplies--;

    } while (!timedout && expectReplies > 0);

    /* Remove any timeout hosts during the scan. */
    OSI->removeCompletedHosts();

    numProbesLeft = 0;
    for (hostI = OSI->incompleteHosts.begin();
        hostI != OSI->incompleteHosts.end(); hostI++) {
      hss = (*hostI)->hss;
      HOS->updateActiveSeqProbes(hss);
      numProbesLeft += hss->numProbesToSend();
      numProbesLeft += hss->numProbesActive();
    }

    gettimeofday(&now, NULL);

    if (expectReplies == 0) {
      timeToSleep = TIMEVAL_SUBTRACT(stime, now);
    } else {
      timeToSleep = 0;
    }

  } while (numProbesLeft > 0);

}


/* TCP, UDP, ICMP Tests */
static void doTUITests(OsScanInfo *OSI, HostOsScan *HOS) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;
  HostOsScanStats *hss = NULL;
  unsigned int unableToSend; /* # of times in a row that hosts were unable to send probe */
  unsigned int expectReplies;
  long to_usec;
  int timeToSleep = 0;

  struct ip *ip = NULL;
  struct link_header linkhdr;
  struct sockaddr_storage ss;
  unsigned int bytes;
  struct timeval rcvdtime;

  struct timeval stime, tmptv;

  bool timedout = false;
  bool thisHostGood;
  bool foundgood;
  bool goodResponse;
  int numProbesLeft = 0;

  memset(&stime, 0, sizeof(stime));
  memset(&tmptv, 0, sizeof(tmptv));

  for (hostI = OSI->incompleteHosts.begin();
      hostI != OSI->incompleteHosts.end(); hostI++) {
    hsi = *hostI;
    hss = hsi->hss;
    HOS->buildTUIProbeList(hss);
  }

  do {

    if (timeToSleep > 0) {
      if (o.debugging > 1) {
        log_write(LOG_PLAIN, "Time to sleep %d. Sleeping. \n", timeToSleep);
      }

      usleep(timeToSleep);
    }

    gettimeofday(&now, NULL);
    expectReplies = 0;
    unableToSend = 0;

    if (o.debugging > 2) {
      for (hostI = OSI->incompleteHosts.begin();
          hostI != OSI->incompleteHosts.end(); hostI++) {
        hss = (*hostI)->hss;
        log_write(LOG_PLAIN, "Host %s. ProbesToSend %d: \tProbesActive %d\n",
                  hss->target->targetipstr(), hss->numProbesToSend(),
                  hss->numProbesActive());
      }
    }

    while (unableToSend < OSI->numIncompleteHosts() && HOS->stats->sendOK()) {
      hsi = OSI->nextIncompleteHost();
      hss = hsi->hss;
      gettimeofday(&now, NULL);
      if (hss->numProbesToSend()>0 && HOS->hostSendOK(hss, NULL)) {
        HOS->sendNextProbe(hss);
        expectReplies++;
        unableToSend = 0;
      } else {
        unableToSend++;
      }
    }

    HOS->stats->num_probes_sent_at_last_wait = HOS->stats->num_probes_sent;

    gettimeofday(&now, NULL);

    /* Count the pcap wait time. */
    if (!HOS->stats->sendOK()) {
      TIMEVAL_MSEC_ADD(stime, now, 1000);

      for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end();
          hostI++) {
        if (HOS->nextTimeout((*hostI)->hss, &tmptv)) {
          if (TIMEVAL_SUBTRACT(tmptv, stime) < 0)
            stime = tmptv;
        }
      }
    }
    else {
      foundgood = false;
      for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
        thisHostGood = HOS->hostSendOK((*hostI)->hss, &tmptv);
        if (thisHostGood) {
          stime = tmptv;
          foundgood = true;
          break;
        }

        if (!foundgood || TIMEVAL_SUBTRACT(tmptv, stime) < 0) {
          stime = tmptv;
          foundgood = true;
        }
      }
    }

    do {
      to_usec = TIMEVAL_SUBTRACT(stime, now);
      if (to_usec < 2000) to_usec = 2000;

      if (o.debugging > 2)
        log_write(LOG_PLAIN, "pcap wait time is %ld.\n", to_usec);

      ip = (struct ip*) readipv4_pcap(HOS->pd, &bytes, to_usec, &rcvdtime, &linkhdr, true);

      gettimeofday(&now, NULL);

      if (!ip && TIMEVAL_SUBTRACT(stime, now) < 0) {
        timedout = true;
        break;
      } else if (!ip) {
        continue;
      }

      if (TIMEVAL_SUBTRACT(now, stime) > 200000) {
        /* While packets are still being received, I'll be generous and give
           an extra 1/5 sec.  But we have to draw the line somewhere */
        timedout = true;
      }

      if (bytes < (4 * ip->ip_hl) + 4U)
        continue;

      memset(&ss, 0, sizeof(ss));
      ((struct sockaddr_in *) &ss)->sin_addr.s_addr = ip->ip_src.s_addr;
      ss.ss_family = AF_INET;
      hsi = OSI->findIncompleteHost(&ss);
      if (!hsi)
        continue; /* Not from one of our targets. */
      setTargetMACIfAvailable(hsi->target, &linkhdr, &ss, 0);

      goodResponse = HOS->processResp(hsi->hss, ip, bytes, &rcvdtime);

      if (goodResponse)
        expectReplies--;

    } while (!timedout && expectReplies > 0);

    /* Remove any timeout hosts during the scan. */
    OSI->removeCompletedHosts();

    numProbesLeft = 0;
    for (hostI = OSI->incompleteHosts.begin();
        hostI != OSI->incompleteHosts.end(); hostI++) {
      hss = (*hostI)->hss;
      HOS->updateActiveTUIProbes(hss);
      numProbesLeft += hss->numProbesToSend();
      numProbesLeft += hss->numProbesActive();
    }

    gettimeofday(&now, NULL);

    if (expectReplies == 0) {
      timeToSleep = TIMEVAL_SUBTRACT(stime, now);
    } else {
      timeToSleep = 0;
    }

  } while (numProbesLeft > 0);
}


static void endRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;
  int distance = -1;
  enum dist_calc_method distance_calculation_method = DIST_METHOD_NONE;

  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
    distance = -1;
    hsi = *hostI;
    HOS->makeFP(hsi->hss);

    hsi->FPs[roundNum] = hsi->hss->getFP();
    hsi->FPR->FPs[roundNum] = hsi->FPs[roundNum];
    hsi->FPR->numFPs = roundNum + 1;
    double tr = hsi->hss->timingRatio();
    hsi->target->FPR->maxTimingRatio = MAX(hsi->target->FPR->maxTimingRatio, tr);
    match_fingerprint(hsi->FPs[roundNum], &hsi->FP_matches[roundNum],
                      o.reference_FPs, OSSCAN_GUESS_THRESHOLD);

    if (hsi->FP_matches[roundNum].overall_results == OSSCAN_SUCCESS &&
        hsi->FP_matches[roundNum].num_perfect_matches > 0) {
      memcpy(&(hsi->target->seq), &hsi->hss->si, sizeof(struct seq_info));
      if (roundNum > 0) {
        if (o.verbose)
          log_write(LOG_STDOUT, "WARNING:  OS didn't match until try #%d\n", roundNum + 1);
      }
      match_fingerprint(hsi->FPR->FPs[roundNum], hsi->FPR,
                        o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
      hsi->isCompleted = true;
    }

    if (islocalhost(hsi->target->TargetSockAddr())) {
      /* scanning localhost */
      distance = 0;
      distance_calculation_method = DIST_METHOD_LOCALHOST;
    } else if (hsi->target->MACAddress()) {
      /* on the same network segment */
      distance = 1;
      distance_calculation_method = DIST_METHOD_DIRECT;
    } else if (hsi->hss->distance!=-1) {
      distance = hsi->hss->distance;
      distance_calculation_method = DIST_METHOD_ICMP;
    }

    hsi->target->distance = hsi->target->FPR->distance = distance;
    hsi->target->distance_calculation_method = distance_calculation_method;
    hsi->target->FPR->distance_guess = hsi->hss->distance_guess;

  }
  OSI->removeCompletedHosts();
}


static void findBestFPs(OsScanInfo *OSI) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;
  int i;

  double bestacc;
  int bestaccidx;

  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
    hsi = *hostI;
    memcpy(&(hsi->target->seq), &hsi->hss->si, sizeof(struct seq_info));

    /* Now lets find the best match */
    bestacc = 0;
    bestaccidx = 0;
    for (i = 0; i < hsi->FPR->numFPs; i++) {
      if (hsi->FP_matches[i].overall_results == OSSCAN_SUCCESS &&
          hsi->FP_matches[i].num_matches > 0 &&
          hsi->FP_matches[i].accuracy[0] > bestacc) {
        bestacc = hsi->FP_matches[i].accuracy[0];
        bestaccidx = i;
        if (hsi->FP_matches[i].num_perfect_matches)
          break;
      }
    }

    // Now we redo the match, since target->FPR has various data (such as
    // target->FPR->numFPs) which is not in FP_matches[bestaccidx].  This is
    // kinda ugly.
    match_fingerprint(hsi->FPR->FPs[bestaccidx], (FingerPrintResultsIPv4 *) hsi->target->FPR,
                      o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
  }
}


static void printFP(OsScanInfo *OSI) {
  list<HostOsScanInfo *>::iterator hostI;
  HostOsScanInfo *hsi = NULL;
  FingerPrintResultsIPv4 *FPR;

  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
    hsi = *hostI;
    FPR = hsi->FPR;

    log_write(LOG_NORMAL|LOG_SKID_NOXLT|LOG_STDOUT,
          "No OS matches for %s by new os scan system.\n\nTCP/IP fingerprint:\n%s",
          hsi->target->targetipstr(),
          mergeFPs(FPR->FPs, FPR->numFPs, true,
               hsi->target->TargetSockAddr(), hsi->target->distance,
               hsi->target->distance_calculation_method,
               hsi->target->MACAddress(),
               FPR->osscan_opentcpport, FPR->osscan_closedtcpport,
               FPR->osscan_closedudpport, false));
  }
}


/* Goes through every unmatched host in OSI.  If a host has completed
   the maximum number of OS detection tries allowed for it without
   matching, it is transferred to the passed in unMatchedHosts list.
   Returns the number of hosts moved to unMatchedHosts. */
static int expireUnmatchedHosts(OsScanInfo *OSI, list<HostOsScanInfo *> *unMatchedHosts) {
  list<HostOsScanInfo *>::iterator hostI, nextHost;
  int hostsRemoved = 0;
  HostOsScanInfo *HOS;

  gettimeofday(&now, NULL);
  for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI = nextHost) {
    HOS = *hostI;
    nextHost = hostI;
    nextHost++;

    int max_tries = o.maxOSTries(); /* The amt. if print is suitable for submission */
    if (HOS->target->FPR->OmitSubmissionFP())
      max_tries = min(max_tries, STANDARD_OS2_TRIES);

    if (HOS->FPR->numFPs >= max_tries) {
      /* We've done all the OS2 tries we're going to do ... move this
     to unMatchedHosts */
      HOS->target->stopTimeOutClock(&now);
      OSI->incompleteHosts.erase(hostI);
      /* We need to adjust nextI if necessary */
      OSI->resetHostIterator();
      hostsRemoved++;
      unMatchedHosts->push_back(HOS);
    }
  }
  return hostsRemoved;
}


/******************************************************************************
 * Implementation of class OFProbe                                            *
 ******************************************************************************/

OFProbe::OFProbe() {
  type = OFP_UNSET;
  subid = 0;
  tryno = -1;
  retransmitted = false;
  memset(&sent, 0, sizeof(sent));
  memset(&prevSent, 0, sizeof(prevSent));
}


const char *OFProbe::typestr() {
  switch (type) {
  case OFP_UNSET:
    return "OFP_UNSET";
  case OFP_TSEQ:
    return "OFP_TSEQ";
  case OFP_TOPS:
    return "OFP_TOPS";
  case OFP_TECN:
    return "OFP_TECN";
  case OFP_T1_7:
    return "OFP_T1_7";
  case OFP_TUDP:
    return "OFP_TUDP";
  case OFP_TICMP:
    return "OFP_TICMP";
  default:
    assert(false);
    return "ERROR";
  }
}


/******************************************************************************
 * Implementation of class HostOsScanStats                                    *
 ******************************************************************************/

HostOsScanStats::HostOsScanStats(Target * t) {
  int i;

  target = t;
  FP = NULL;

  memset(&si, 0, sizeof(si));
  memset(&ipid, 0, sizeof(ipid));

  openTCPPort = -1;
  closedTCPPort = -1;
  closedUDPPort = -1;

  num_probes_sent = 0;
  sendDelayMs = MAX(o.scan_delay, OS_PROBE_DELAY);
  lastProbeSent = now;

  /* Timing */
  timing.cwnd = perf.host_initial_cwnd;
  timing.ssthresh = perf.initial_ssthresh; /* Will be reduced if any packets are dropped anyway */
  timing.num_replies_expected = 0;
  timing.num_replies_received = 0;
  timing.num_updates = 0;
  gettimeofday(&timing.last_drop, NULL);

  for (i = 0; i < NUM_FPTESTS; i++)
    FPtests[i] = NULL;
  for (i = 0; i < 6; i++) {
    TOps_AVs[i] = NULL;
    TWin_AVs[i] = NULL;
  }

  icmpEchoReply = NULL;

  distance = -1;
  distance_guess = -1;
}


HostOsScanStats::~HostOsScanStats() {
  int i;

  for (i = 0; i < NUM_FPTESTS; i++) {
    if (FPtests[i] != NULL)
      delete FPtests[i];
  }
  for (i = 0; i < 6; i++) {
    if (TOps_AVs[i])
      free(TOps_AVs[i]);
    if (TWin_AVs[i])
      free(TWin_AVs[i]);
  }

  while (!probesToSend.empty()) {
    delete probesToSend.front();
    probesToSend.pop_front();
  }

  while (!probesActive.empty()) {
    delete probesActive.front();
    probesActive.pop_front();
  }

  if (icmpEchoReply) free(icmpEchoReply);
}


void HostOsScanStats::initScanStats() {
  Port *tport = NULL;
  Port port;
  int i;

  /* Lets find an open port to use if we don't already have one */
  openTCPPort = -1;
  /*  target->FPR->osscan_opentcpport = -1;
  target->FPR->osscan_closedtcpport = -1;
  target->FPR->osscan_closedudpport = -1; */

  if (target->FPR->osscan_opentcpport > 0)
    openTCPPort = target->FPR->osscan_opentcpport;
  else if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_OPEN))) {
    openTCPPort = tport->portno;
    /* If it is zero, let's try another one if there is one ) */
    if (tport->portno == 0)
      if ((tport = target->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_OPEN)))
        openTCPPort = tport->portno;

    target->FPR->osscan_opentcpport = openTCPPort;
  }

  /* Now we should find a closed TCP port */
  if (target->FPR->osscan_closedtcpport > 0)
    closedTCPPort = target->FPR->osscan_closedtcpport;
  else if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_CLOSED))) {
    closedTCPPort = tport->portno;

    /* If it is zero, let's try another one if there is one ) */
    if (tport->portno == 0)
      if ((tport = target->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_CLOSED)))
        closedTCPPort = tport->portno;

    target->FPR->osscan_closedtcpport = closedTCPPort;
  } else if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_UNFILTERED))) {
    /* Well, we will settle for unfiltered */
    closedTCPPort = tport->portno;
    /* But again we'd prefer not to have zero */
    if (tport->portno == 0)
      if ((tport = target->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_UNFILTERED)))
        closedTCPPort = tport->portno;
  } else {
    /* We'll just have to pick one at random :( */
    closedTCPPort = (get_random_uint() % 14781) + 30000;
  }

  /* Now we should find a closed UDP port */
  if (target->FPR->osscan_closedudpport > 0)
    closedUDPPort = target->FPR->osscan_closedudpport;
  else if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_CLOSED))) {
    closedUDPPort = tport->portno;
    /* Not zero, if possible */
    if (tport->portno == 0)
      if ((tport = target->ports.nextPort(tport, &port, IPPROTO_UDP, PORT_CLOSED)))
        closedUDPPort = tport->portno;
    target->FPR->osscan_closedudpport = closedUDPPort;
  } else if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_UNFILTERED))) {
    /* Well, we will settle for unfiltered */
    closedUDPPort = tport->portno;
    /* But not zero, please */
    if (tport->portno == 0)
      if ((tport = target->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_UNFILTERED)))
        closedUDPPort = tport->portno;
  } else {
    /* Pick one at random.  Shrug. */
    closedUDPPort = (get_random_uint() % 14781) + 30000;
  }

  FP = NULL;
  for (i = 0; i < NUM_FPTESTS; i++) {
    if (FPtests[i] != NULL)
      delete FPtests[i];
    FPtests[i] = NULL;
  }
  for (i = 0; i < 6; i++) {
    if (TOps_AVs[i])
      free(TOps_AVs[i]);
    if (TWin_AVs[i])
      free(TWin_AVs[i]);
    TOps_AVs[i] = NULL;
    TWin_AVs[i] = NULL;
  }

  TOpsReplyNum = 0;
  TWinReplyNum = 0;

  lastipid = 0;
  memset(&si, 0, sizeof(si));

  for (i = 0; i < NUM_SEQ_SAMPLES; i++) {
    ipid.tcp_ipids[i] = -1;
    ipid.tcp_closed_ipids[i] = -1;
    ipid.icmp_ipids[i] = -1;
  }

  memset(&seq_send_times, 0, sizeof(seq_send_times));

  if (icmpEchoReply) {
    free(icmpEchoReply);
    icmpEchoReply = NULL;
  }
  storedIcmpReply = -1;

  memset(&upi, 0, sizeof(upi));
}


/* Fill in an eth_nfo struct with the appropriate source and destination MAC
   addresses and a given Ethernet handle. The return value is suitable to pass
   to send_ip_packet: if ethsd is NULL, returns NULL; otherwise returns eth. */
struct eth_nfo *HostOsScanStats::fill_eth_nfo(struct eth_nfo *eth, eth_t *ethsd) const {
  if (ethsd == NULL)
    return NULL;

  memcpy(eth->srcmac, target->SrcMACAddress(), sizeof(eth->srcmac));
  memcpy(eth->dstmac, target->NextHopMACAddress(), sizeof(eth->srcmac));
  eth->ethsd = ethsd;
  eth->devname[0] = '\0';

  return eth;
}


/* Add a probe to the probe list. */
void HostOsScanStats::addNewProbe(OFProbeType type, int subid) {
  OFProbe *probe = new OFProbe();
  probe->type = type;
  probe->subid = subid;
  probesToSend.push_back(probe);
}


/* Remove a probe from the probesActive. */
void HostOsScanStats::removeActiveProbe(list<OFProbe *>::iterator probeI) {
  OFProbe *probe = *probeI;
  probesActive.erase(probeI);
  delete probe;
}


/* Get an active probe from active probe list identified by probe type
   and subid.  Returns probesActive.end() if there isn't one */
list<OFProbe *>::iterator HostOsScanStats::getActiveProbe(OFProbeType type, int subid) {
  list<OFProbe *>::iterator probeI;
  OFProbe *probe = NULL;

  for (probeI = probesActive.begin(); probeI != probesActive.end(); probeI++) {
    probe = *probeI;
    if (probe->type == type && probe->subid == subid)
      break;
  }

  if (probeI == probesActive.end()) {
    /* not found!? */
    if (o.debugging > 1)
      log_write(LOG_PLAIN, "Probe doesn't exist! Probe type: %d. Probe subid: %d\n", type, subid);
    return probesActive.end();
  }

  return probeI;
}


/* Move a probe from probesToSend to probesActive. */
void HostOsScanStats::moveProbeToActiveList(list<OFProbe *>::iterator probeI) {
  probesActive.push_back(*probeI);
  probesToSend.erase(probeI);
}


/* Move a probe from probesActive to probesToSend. */
void HostOsScanStats::moveProbeToUnSendList(list<OFProbe *>::iterator probeI) {
  probesToSend.push_back(*probeI);
  probesActive.erase(probeI);
}


 /* Compute the ratio of amount of time taken between sending 1st TSEQ
    probe and 1st ICMP probe compared to the amount of time it should
    have taken.  Ratios far from 1 can cause bogus results */
double HostOsScanStats::timingRatio() {
  if (openTCPPort < 0)
    return 0;
  int msec_ideal = OS_SEQ_PROBE_DELAY * (NUM_SEQ_SAMPLES - 1);
  int msec_taken = TIMEVAL_MSEC_SUBTRACT(seq_send_times[NUM_SEQ_SAMPLES -1 ], seq_send_times[0]);
  if (o.debugging) {
    log_write(LOG_PLAIN, "OS detection timingRatio() == (%.3f - %.3f) * 1000 / %d == %.3f\n",
              seq_send_times[NUM_SEQ_SAMPLES - 1].tv_sec + seq_send_times[NUM_SEQ_SAMPLES - 1].tv_usec / 1000000.0, seq_send_times[0].tv_sec + (float) seq_send_times[0].tv_usec / 1000000.0, msec_ideal, (float) msec_taken / msec_ideal);
  }
  return (double) msec_taken / msec_ideal;
}


/******************************************************************************
 * Implementation of class HostOsScan                                         *
 ******************************************************************************/

/* If there are pending probe timeouts, fills in when with the time of
 * the earliest one and returns true.  Otherwise returns false and
 * puts now in when. */
bool HostOsScan::nextTimeout(HostOsScanStats *hss, struct timeval *when) {
  assert(hss);
  struct timeval probe_to, earliest_to;
  list<OFProbe *>::iterator probeI;
  bool firstgood = true;

  assert(when);
  memset(&probe_to, 0, sizeof(probe_to));
  memset(&earliest_to, 0, sizeof(earliest_to));

  for (probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI++) {
    TIMEVAL_ADD(probe_to, (*probeI)->sent, timeProbeTimeout(hss));
    if (firstgood || TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
      earliest_to = probe_to;
      firstgood = false;
    }
  }

  *when = (firstgood)? now : earliest_to;
  return (firstgood)? false : true;
}


void HostOsScan::adjust_times(HostOsScanStats *hss, OFProbe *probe, struct timeval *rcvdtime) {
  assert(hss);
  assert(probe);

  /* Adjust timing */
  if (rcvdtime) {
    adjust_timeouts2(&(probe->sent), rcvdtime, &(hss->target->to));
    adjust_timeouts2(&(probe->sent), rcvdtime, &(stats->to));
  }

  stats->timing.num_replies_expected++;
  stats->timing.num_updates++;

  hss->timing.num_replies_expected++;
  hss->timing.num_updates++;

  /* Notice a drop if
     1. We get a response to a retransmitted probe (meaning the first reply was
        dropped), or
     2. We get no response after a timeout (rcvdtime == NULL). */
  if (probe->tryno > 0 || rcvdtime == NULL) {
    if (o.debugging > 1) {
      if (probe->tryno > 0) {
        log_write(LOG_PLAIN, "OS scan DROPPED probe to %s detected (tryno %d)\n",
          hss->target->targetipstr(), probe->tryno);
      } else {
        log_write(LOG_PLAIN, "OS scan DROPPED probe to %s detected (rcvdtime == NULL)\n",
          hss->target->targetipstr());
      }
    }
    if (TIMEVAL_AFTER(probe->sent, hss->timing.last_drop))
      hss->timing.drop(hss->numProbesActive(), &perf, &now);
    if (TIMEVAL_AFTER(probe->sent, stats->timing.last_drop))
      stats->timing.drop_group(stats->num_probes_active, &perf, &now);
  }

  /* Increase the window for a positive reply. This can overlap with case (1)
     above. */
  if (rcvdtime != NULL) {
    stats->timing.ack(&perf);
    hss->timing.ack(&perf);
  }
}


HostOsScan::HostOsScan(Target *t) {
  pd = NULL;
  rawsd = -1;
  ethsd = NULL;

  if ((o.sendpref & PACKET_SEND_ETH) &&  t->ifType() == devt_ethernet) {
    if ((ethsd = eth_open_cached(t->deviceName())) == NULL)
      fatal("%s: Failed to open ethernet device (%s)", __func__, t->deviceName());
    rawsd = -1;
  } else {
    /* Init our raw socket */
#ifdef WIN32
    win32_fatal_raw_sockets(t->deviceName());
#endif
    if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
      pfatal("socket troubles in %s", __func__);
    unblock_socket(rawsd);
    broadcast_socket(rawsd);
#ifndef WIN32
    sethdrinclude(rawsd);
#endif
    ethsd = NULL;
  }

  tcpPortBase = o.magic_port_set? o.magic_port : o.magic_port + get_random_u8();
  udpPortBase = o.magic_port_set? o.magic_port : o.magic_port + get_random_u8();
  reInitScanSystem();

  stats = new ScanStats();
}


HostOsScan::~HostOsScan() {
  if (rawsd >= 0) {
    close(rawsd);
    rawsd = -1;
  }
  if (pd) {
    pcap_close(pd);
    pd = NULL;
  }
  /*
   * No need to close ethsd due to caching
   * if (ethsd) {
   *   eth_close(ethsd);
   *   ethsd = NULL;
   * }
   */
  delete stats;
}


void HostOsScan::reInitScanSystem() {
  tcpSeqBase = get_random_u32();
  tcpAck = get_random_u32();
  tcpMss = 265;
  icmpEchoId = get_random_u16();
  icmpEchoSeq = 295;
  udpttl = (time(NULL) % 14) + 51;
}


/* Initiate seq probe list */
void HostOsScan::buildSeqProbeList(HostOsScanStats *hss) {
  assert(hss);
  int i;
  if (hss->openTCPPort == -1)
    return;
  if (hss->FP_TSeq)
    return;

  for (i = 0; i < NUM_SEQ_SAMPLES; i++)
    hss->addNewProbe(OFP_TSEQ, i);
}


/* Update the seq probes in the active probe list and remove the ones that have
 * timed out. */
void HostOsScan::updateActiveSeqProbes(HostOsScanStats *hss) {
  assert(hss);
  list<OFProbe *>::iterator probeI, nxt;
  OFProbe *probe = NULL;

  for (probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI = nxt) {
    nxt = probeI;
    nxt++;
    probe = *probeI;

    /* Is the probe timedout? */
    if (TIMEVAL_SUBTRACT(now, probe->sent) > (long) timeProbeTimeout(hss)) {
      hss->removeActiveProbe(probeI);
      assert(stats->num_probes_active > 0);
      stats->num_probes_active--;
    }
  }
}


/* Initialize the normal TCP/UDP/ICMP probe list */
void HostOsScan::buildTUIProbeList(HostOsScanStats *hss) {
  assert(hss);
  int i;

  /* The order of these probes are important for ipid generation
   * algorithm test and should not be changed.
   *
   * At doSeqTests we sent 6 TSeq probes to generate 6 tcp replies,
   * and here we follow with 3 probes to generate 3 icmp replies. In
   * this way we can expect to get "good" IPid sequence.
   *
   * **** Should be done in a more elegant way. *****
   */

  /* ticmp */
  if (!hss->FP_TIcmp) {
    for (i = 0; i < 2; i++) {
      hss->addNewProbe(OFP_TICMP, i);
    }
  }

  /* tudp */
  if (!hss->FP_TUdp) {
    hss->addNewProbe(OFP_TUDP, 0);
  }

  if (hss->openTCPPort != -1) {
    /* tops/twin probes. We send the probe again if we didn't get a
       response by the corresponding seq probe. */
    if (!hss->FP_TOps || !hss->FP_TWin) {
      for (i = 0; i < 6; i++) {
        if (!hss->TOps_AVs[i] || !hss->TWin_AVs[i])
          hss->addNewProbe(OFP_TOPS, i);
      }
    }

    /* tecn */
    if (!hss->FP_TEcn) {
      hss->addNewProbe(OFP_TECN, 0);
    }

    /* t1_7: t1_t4 */
    for (i = 0; i < 4; i++) {
      if (!hss->FPtests[FP_T1_7_OFF + i]) {
        hss->addNewProbe(OFP_T1_7, i);
      }
    }
  }

  /* t1_7: t5_t7 */
  for (i = 4; i < 7; i++) {
    if (!hss->FPtests[FP_T1_7_OFF + i]) {
      hss->addNewProbe(OFP_T1_7, i);
    }
  }
}


/* Update the probes in the active probe list:
 * 1) Remove the expired probes (timedout and reached the retry limit);
 * 2) Move timedout probes to probeNeedToSend; */
void HostOsScan::updateActiveTUIProbes(HostOsScanStats *hss) {
  assert(hss);
  list<OFProbe *>::iterator probeI, nxt;
  OFProbe *probe = NULL;

  for (probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI = nxt) {
    nxt = probeI;
    nxt++;
    probe = *probeI;

    if (TIMEVAL_SUBTRACT(now, probe->sent) > (long) timeProbeTimeout(hss)) {
      if (probe->tryno >= 3) {
        /* The probe is expired. */
        hss->removeActiveProbe(probeI);
        assert(stats->num_probes_active > 0);
        stats->num_probes_active--;
      }
      else {
        /* It is timedout, move it to the sendlist */
        hss->moveProbeToUnSendList(probeI);
        assert(stats->num_probes_active > 0);
        stats->num_probes_active--;
      }
    }
  }
}


/* Check whether the host is sendok. If not, fill _when_ with the time
 * when it will be sendOK and return false; else, fill it with now and
 * return true. */
bool HostOsScan::hostSendOK(HostOsScanStats *hss, struct timeval *when) {
  assert(hss);
  list<OFProbe *>::iterator probeI;
  int packTime;
  struct timeval probe_to, earliest_to, sendTime;
  long tdiff;

  if (hss->target->timedOut(&now)) {
    if (when)
      *when = now;
    return false;
  }

  if (hss->sendDelayMs > 0) {
    packTime = TIMEVAL_MSEC_SUBTRACT(now, hss->lastProbeSent);
    if (packTime < (int) hss->sendDelayMs) {
      if (when) {
        TIMEVAL_MSEC_ADD(*when, hss->lastProbeSent, hss->sendDelayMs);
      }
      return false;
    }
  }

  if (hss->timing.cwnd >= hss->numProbesActive() + .5) {
    if (when)
      *when = now;
    return true;
  }

  if (!when)
    return false;

  TIMEVAL_MSEC_ADD(earliest_to, now, 10000);

  /* Any timeouts coming up? */
  for (probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI++) {
    TIMEVAL_MSEC_ADD(probe_to, (*probeI)->sent, timeProbeTimeout(hss) / 1000);
    if (TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
      earliest_to = probe_to;
    }
  }

  // Will any scan delay affect this?
  if (hss->sendDelayMs > 0) {
    TIMEVAL_MSEC_ADD(sendTime, hss->lastProbeSent, hss->sendDelayMs);
    if (TIMEVAL_MSEC_SUBTRACT(sendTime, now) < 0)
      sendTime = now;
    tdiff = TIMEVAL_MSEC_SUBTRACT(earliest_to, sendTime);

    /* Timeouts previous to the sendTime requirement are pointless,
       and those later than sendTime are not needed if we can send a
       new packet at sendTime */
    if (tdiff < 0) {
      earliest_to = sendTime;
    } else {
      if (tdiff > 0 && hss->timing.cwnd > hss->numProbesActive() + .5) {
        earliest_to = sendTime;
      }
    }
  }

  *when = earliest_to;
  return false;
}


/* Check whether it is OK to send the next seq probe to the host. If
 * not, fill param "when" with the time when it will be sendOK and return
 * false; else, fill it with now and return true. */
bool HostOsScan::hostSeqSendOK(HostOsScanStats *hss, struct timeval *when) {
  assert(hss);
  list<OFProbe *>::iterator probeI;
  int packTime = 0, maxWait = 0;
  struct timeval probe_to, earliest_to, sendTime;
  long tdiff;

  if (hss->target->timedOut(&now)) {
    if (when)
      *when = now;
    return false;
  }

  packTime = TIMEVAL_SUBTRACT(now, hss->lastProbeSent);

  /*
   * If the user insist a larger sendDelayMs, use it. But
   * the seq result may be inaccurate.
   */
  maxWait = MAX(OS_SEQ_PROBE_DELAY * 1000, hss->sendDelayMs * 1000);
  if (packTime < maxWait) {
    if (when) {
      TIMEVAL_ADD(*when, hss->lastProbeSent, maxWait);
    }
    return false;
  }

  if (hss->timing.cwnd >= hss->numProbesActive() + .5) {
    if (when)
      *when = now;
    return true;
  }

  if (!when)
    return false;

  TIMEVAL_MSEC_ADD(earliest_to, now, 10000);

  /* Any timeouts coming up? */
  for (probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI++) {
    TIMEVAL_MSEC_ADD(probe_to, (*probeI)->sent, timeProbeTimeout(hss) / 1000);
    if (TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
      earliest_to = probe_to;
    }
  }

  TIMEVAL_ADD(sendTime, hss->lastProbeSent, maxWait);
  if (TIMEVAL_SUBTRACT(sendTime, now) < 0)
    sendTime = now;
  tdiff = TIMEVAL_SUBTRACT(earliest_to, sendTime);

  /* Timeouts previous to the sendTime requirement are pointless,
     and those later than sendTime are not needed if we can send a
     new packet at sendTime */
  if (tdiff < 0) {
    earliest_to = sendTime;
  } else {
    if (tdiff > 0 && hss->timing.cwnd > hss->numProbesActive() + .5) {
      earliest_to = sendTime;
    }
  }

  *when = earliest_to;
  return false;
}


unsigned long HostOsScan::timeProbeTimeout(HostOsScanStats *hss) {
  assert(hss);
  if (hss->target->to.srtt > 0) {
    /* We have at least one timing value to use.  Good enough, I suppose */
    return hss->target->to.timeout;
  } else if (stats->to.srtt > 0) {
    /* OK, we'll use this one instead */
    return stats->to.timeout;
  } else {
    return hss->target->to.timeout; /* It comes with a default */
  }
}


void HostOsScan::sendNextProbe(HostOsScanStats *hss) {
  assert(hss);
  list<OFProbe *>::iterator probeI;
  OFProbe *probe = NULL;

  if (hss->probesToSend.empty())
    return;

  probeI = hss->probesToSend.begin();
  probe = *probeI;

  switch (probe->type) {
  case OFP_TSEQ:
    sendTSeqProbe(hss, probe->subid);
    break;
  case OFP_TOPS:
    sendTOpsProbe(hss, probe->subid);
    break;
  case OFP_TECN:
    sendTEcnProbe(hss);
    break;
  case OFP_T1_7:
    sendT1_7Probe(hss, probe->subid);
    break;
  case OFP_TICMP:
    sendTIcmpProbe(hss, probe->subid);
    break;
  case OFP_TUDP:
    sendTUdpProbe(hss, probe->subid);
    break;
  default:
    assert(false);
  }

  probe->tryno++;
  if (probe->tryno > 0) {
    /* This is a retransmission */
    probe->retransmitted = true;
    probe->prevSent = probe->sent;
  }
  probe->sent = now;

  hss->lastProbeSent = now;
  hss->num_probes_sent++;
  stats->num_probes_sent++;

  hss->moveProbeToActiveList(probeI);
  stats->num_probes_active++;

  if (o.debugging > 1) {
    log_write(LOG_PLAIN, "Send probe (type: %s, subid: %d) to %s\n",
              probe->typestr(), probe->subid, hss->target->targetipstr());
  }

}


void HostOsScan::sendTSeqProbe(HostOsScanStats *hss, int probeNo) {
  assert(hss);
  assert(probeNo >= 0 && probeNo < NUM_SEQ_SAMPLES);

  if (hss->openTCPPort == -1)
    return;

  send_tcp_probe(hss, o.ttl, false, NULL, 0,
                 tcpPortBase + probeNo, hss->openTCPPort,
                 tcpSeqBase + probeNo, tcpAck,
                 0, TH_SYN, prbWindowSz[probeNo], 0,
                 prbOpts[probeNo].val, prbOpts[probeNo].len, NULL, 0);

  hss->seq_send_times[probeNo] = now;
}


void HostOsScan::sendTOpsProbe(HostOsScanStats *hss, int probeNo) {
  assert(hss);
  assert(probeNo >= 0 && probeNo < NUM_SEQ_SAMPLES);

  if (hss->openTCPPort == -1)
    return;

  send_tcp_probe(hss, o.ttl, false, NULL, 0,
                 tcpPortBase + NUM_SEQ_SAMPLES + probeNo, hss->openTCPPort,
                 tcpSeqBase, tcpAck,
                 0, TH_SYN, prbWindowSz[probeNo], 0,
                 prbOpts[probeNo].val, prbOpts[probeNo].len, NULL, 0);
}


void HostOsScan::sendTEcnProbe(HostOsScanStats *hss) {
  assert(hss);

  if (hss->openTCPPort == -1)
    return;

  send_tcp_probe(hss, o.ttl, false, NULL, 0,
                 tcpPortBase + NUM_SEQ_SAMPLES + 6, hss->openTCPPort,
                 tcpSeqBase, 0,
                 8, TH_CWR|TH_ECE|TH_SYN, prbWindowSz[6], 63477,
                 prbOpts[6].val, prbOpts[6].len, NULL, 0);
}


void HostOsScan::sendT1_7Probe(HostOsScanStats *hss, int probeNo) {
  assert(hss);
  assert(probeNo >=0 && probeNo < 7);

  int port_base = tcpPortBase + NUM_SEQ_SAMPLES + 7;

  switch (probeNo) {
  case 0: /* T1 */
    /* T1 is normally filled in by sendTSeqProbe so this case doesn't happen. In
       case all six Seq probes failed, this one will be re-sent. It is the same
       as the first probe sent by sendTSeqProbe. */
    if (hss->openTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, false, NULL, 0,
                   port_base, hss->openTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_SYN, prbWindowSz[0], 0,
                   prbOpts[0].val, prbOpts[0].len, NULL, 0);
    break;
  case 1: /* T2 */
    if (hss->openTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, true, NULL, 0,
                   port_base + 1, hss->openTCPPort,
                   tcpSeqBase, tcpAck,
                   0, 0, prbWindowSz[7], 0,
                   prbOpts[7].val, prbOpts[7].len, NULL, 0);
    break;
  case 2: /* T3 */
    if (hss->openTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, false, NULL, 0,
                   port_base + 2, hss->openTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_SYN|TH_FIN|TH_URG|TH_PUSH, prbWindowSz[8], 0,
                   prbOpts[8].val, prbOpts[8].len, NULL, 0);
    break;
  case 3: /* T4 */
    if (hss->openTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, true, NULL, 0,
                   port_base + 3, hss->openTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_ACK, prbWindowSz[9], 0,
                   prbOpts[9].val, prbOpts[9].len, NULL, 0);
    break;
  case 4: /* T5 */
    if (hss->closedTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, false, NULL, 0,
                   port_base + 4, hss->closedTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_SYN, prbWindowSz[10], 0,
                   prbOpts[10].val, prbOpts[10].len, NULL, 0);
    break;
  case 5: /* T6 */
    if (hss->closedTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, true, NULL, 0,
                   port_base + 5, hss->closedTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_ACK, prbWindowSz[11], 0,
                   prbOpts[11].val, prbOpts[11].len, NULL, 0);
    break;
  case 6: /* T7 */
    if (hss->closedTCPPort == -1)
      return;
    send_tcp_probe(hss, o.ttl, false, NULL, 0,
                   port_base + 6, hss->closedTCPPort,
                   tcpSeqBase, tcpAck,
                   0, TH_FIN|TH_PUSH|TH_URG, prbWindowSz[12], 0,
                   prbOpts[12].val, prbOpts[12].len, NULL, 0);
  }
}


void HostOsScan::sendTIcmpProbe(HostOsScanStats *hss, int probeNo) {
  assert(hss);
  assert(probeNo >= 0 && probeNo < 2);
  if (probeNo == 0) {
    send_icmp_echo_probe(hss, IP_TOS_DEFAULT,
                         true, 9, icmpEchoId, icmpEchoSeq, 120);
  }
  else {
    send_icmp_echo_probe(hss, IP_TOS_RELIABILITY,
                         false, 0, icmpEchoId + 1, icmpEchoSeq + 1, 150);
  }
}


void HostOsScan::sendTUdpProbe(HostOsScanStats *hss, int probeNo) {
  assert(hss);
  if (hss->closedUDPPort == -1)
    return;
  send_closedudp_probe(hss, udpttl, udpPortBase + probeNo, hss->closedUDPPort);
}


bool HostOsScan::processResp(HostOsScanStats *hss, struct ip *ip, unsigned int len, struct timeval *rcvdtime) {
  struct ip *ip2;
  struct tcp_hdr *tcp;
  struct icmp *icmp;
  int testno;
  bool isPktUseful = false;
  list<OFProbe *>::iterator probeI;
  OFProbe *probe;

  if (len < 20 || len < (4 * ip->ip_hl) + 4U)
    return false;

  len -= 4 * ip->ip_hl;

  if (ip->ip_p == IPPROTO_TCP) {
    if (len < 20)
      return false;
    tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));
    if (len < (unsigned int)(4 * tcp->th_off))
      return false;
    testno = ntohs(tcp->th_dport) - tcpPortBase;

    if (testno >= 0 && testno < NUM_SEQ_SAMPLES) {
      /* TSeq */
      isPktUseful = processTSeqResp(hss, ip, testno);

      if (isPktUseful) {
        hss->ipid.tcp_ipids[testno] = ntohs(ip->ip_id);
        probeI = hss->getActiveProbe(OFP_TSEQ, testno);
        /* printf("tcp ipid = %d\n", ntohs(ip->ip_id)); */
      }

      /* Use the seq response to do other tests. We don't care if it
       * is useful for these tests.
       */
      if (testno == 0) {
        /* the first reply is used to do T1 */
        processT1_7Resp(hss, ip, 0);
      }
      if (testno < 6) {
        /* the 1th~6th replies are used to do TOps and TWin */
        processTOpsResp(hss, tcp, testno);
        processTWinResp(hss, tcp, testno);
      }

    } else if (testno >= NUM_SEQ_SAMPLES && testno < NUM_SEQ_SAMPLES + 6) {

      /* TOps/Twin */
      isPktUseful = processTOpsResp(hss, tcp, testno - NUM_SEQ_SAMPLES);
      isPktUseful |= processTWinResp(hss, tcp, testno - NUM_SEQ_SAMPLES);
      if (isPktUseful) {
        probeI = hss->getActiveProbe(OFP_TOPS, testno - NUM_SEQ_SAMPLES);
      }

    } else if (testno == NUM_SEQ_SAMPLES + 6) {

      /* TEcn */
      isPktUseful = processTEcnResp(hss, ip);
      if (isPktUseful) {
        probeI = hss->getActiveProbe(OFP_TECN, 0);
      }

    } else if (testno >= NUM_SEQ_SAMPLES + 7 && testno < NUM_SEQ_SAMPLES + 14) {

      isPktUseful = processT1_7Resp(hss, ip, testno - NUM_SEQ_SAMPLES - 7);

      if (isPktUseful) {
        probeI = hss->getActiveProbe(OFP_T1_7, testno - NUM_SEQ_SAMPLES - 7);

        /* Closed-port TCP IP ID sequence numbers (SEQ.CI). Uses T5, T6, and T7.
           T5 starts at NUM_SEQ_SAMPLES + 11. */
        if (testno >= NUM_SEQ_SAMPLES + 11 && testno < NUM_SEQ_SAMPLES + 14)
          hss->ipid.tcp_closed_ipids[testno - (NUM_SEQ_SAMPLES + 11)] = ntohs(ip->ip_id);
      }
    }
  }
  else if (ip->ip_p == IPPROTO_ICMP) {
    if (len < 8)
      return false;
    icmp = ((struct icmp *)(((char *) ip) + 4 * ip->ip_hl));

    /* Is it an icmp echo reply? */
    if (icmp->icmp_type == ICMP_ECHOREPLY) {
      testno = ntohs(icmp->icmp_id) - icmpEchoId;
      if (testno == 0 || testno == 1) {
        isPktUseful = processTIcmpResp(hss, ip, testno);
        if (isPktUseful) {
          probeI = hss->getActiveProbe(OFP_TICMP, testno);
        }

        if (isPktUseful && probeI != hss->probesActive.end() && !(*probeI)->retransmitted) { /* Retransmitted ipid is useless. */
          hss->ipid.icmp_ipids[testno] = ntohs(ip->ip_id);
          /* printf("icmp ipid = %d\n", ntohs(ip->ip_id)); */
        }
      }
    }

    /* Is it a destination port unreachable? */
    if (icmp->icmp_type == 3 && icmp->icmp_code == 3) {
      len -= 8; /* icmp destination unreachable header len. */
      if (len < 28)
        return false; /* must larger than an ip and an udp header length */
      ip2 = (struct ip*)((char *)icmp + 8);
      len -= 4 * ip2->ip_hl;
      if (len < 8)
        return false;

      isPktUseful = processTUdpResp(hss, ip);
      if (isPktUseful) {
        probeI = hss->getActiveProbe(OFP_TUDP, 0);
      }
    }

  }

  if (isPktUseful && probeI != hss->probesActive.end()) {
    probe = *probeI;

    if (rcvdtime)
      adjust_times(hss, probe, rcvdtime);

    if (o.debugging > 1) {
      log_write(LOG_PLAIN, "Got a valid response for probe (type: %s subid: %d) from %s\n",
            probe->typestr(), probe->subid, hss->target->targetipstr());
    }

    /* delete the probe. */
    hss->removeActiveProbe(probeI);
    assert(stats->num_probes_active > 0);
    stats->num_probes_active--;

    return true;
  }

  return false;
}


void HostOsScan::makeFP(HostOsScanStats *hss) {
  assert(hss);

  int i;
  struct AVal AV;
  std::vector<struct AVal>::iterator it;

  int ttl;

  if (!hss->FP_TSeq)
    makeTSeqFP(hss);

  if (!hss->FP_TOps)
    makeTOpsFP(hss);

  if (!hss->FP_TWin)
    makeTWinFP(hss);

  for (i = 3; i < NUM_FPTESTS; i++) {
    if (!hss->FPtests[i] &&
        ((i >= 3 && i <= 7 && hss->openTCPPort != -1) ||
         (i >= 8 && i <= 10 && hss->target->FPR->osscan_closedtcpport != -1) ||
         i >= 11)) {
      /* We create a Resp (response) attribute with value of N (no) because
         it is important here to note whether responses were or were not
         received */
      hss->FPtests[i] = new FingerTest;
      AV.attribute = "R";
      AV.value = "N";
      hss->FPtests[i]->results.push_back(AV);
      hss->FPtests[i]->name =  (i == 3)? "ECN" : (i == 4)? "T1" : (i == 5)? "T2" : (i == 6)? "T3" : (i == 7)? "T4" : (i == 8)? "T5" : (i == 9)? "T6" : (i == 10)? "T7" : (i == 11)? "U1" : "IE";
    }
    else if (hss->FPtests[i]) {
      /* Replace TTL with initial TTL. */
      for (it = hss->FPtests[i]->results.begin(); it != hss->FPtests[i]->results.end(); it++) {
        if (strcmp(it->attribute, "T") == 0) {
            /* Found TTL item. The value for this attribute is the
             * received TTL encoded in decimal. We replace it with the
             * initial TTL encoded in hex. */
            ttl = atoi(it->value);

            if (hss->distance_guess == -1)
                hss->distance_guess = get_initial_ttl_guess(ttl) - ttl;

            if (hss->distance != -1) {
                /* We've gotten response for the UDP probe and thus have
                   the "true" hop count. Add the received TTL to the hop
                   count to get the initial TTL. */
                it->value = string_pool_sprintf("%hX", ttl + hss->distance);
            } else {
                /* Guess the initial TTL value */
                it->attribute = "TG";
                it->value = string_pool_sprintf("%hX", get_initial_ttl_guess(ttl));
            }
            break;
        }
      }
    }
  }

  /* Link them up. */
  hss->FP = new FingerPrint;
  for (i = 0; i < NUM_FPTESTS; i++) {
    if (hss->FPtests[i] == NULL)
      continue;
    hss->FP->tests.push_back(*hss->FPtests[i]);
  }
}


/* Send a TCP probe. This takes care of decoys and filling in Ethernet
 * addresses if necessary. Used for the SEQ, OPS, WIN, ECN, and T1-T7 probes. */
int HostOsScan::send_tcp_probe(HostOsScanStats *hss,
                               int ttl, bool df, u8* ipopt, int ipoptlen,
                               u16 sport, u16 dport, u32 seq, u32 ack,
                               u8 reserved, u8 flags, u16 window, u16 urp,
                               u8 *options, int optlen,
                               char *data, u16 datalen) {
  struct eth_nfo eth, *ethptr;

  ethptr = hss->fill_eth_nfo(&eth, ethsd);

  return send_tcp_raw_decoys(rawsd, ethptr, hss->target->v4hostip(),
                             ttl, df, ipopt, ipoptlen, sport, dport, seq, ack,
                             reserved, flags, window, urp,
                             options, optlen, data, datalen);
}


/* Send an echo probe. This takes care of decoys and filling in Ethernet
 * addresses if necessary. Used for the IE probes. */
int HostOsScan::send_icmp_echo_probe(HostOsScanStats *hss,
                                     u8 tos, bool df, u8 pcode,
                                     unsigned short id, u16 seq, u16 datalen) {
  u8 *packet = NULL;
  u32 packetlen = 0;
  int decoy;
  int res = -1;
  struct eth_nfo eth, *ethptr;

  ethptr = hss->fill_eth_nfo(&eth, ethsd);

  for (decoy = 0; decoy < o.numdecoys; decoy++) {
    packet = build_icmp_raw(&o.decoys[decoy], hss->target->v4hostip(),
                            o.ttl, get_random_u16(), tos, df, NULL, 0, seq, id,
                            ICMP_ECHO, pcode, NULL, datalen, &packetlen);
    if (!packet)
      return -1;
    res = send_ip_packet(rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
    free(packet);
    if (res == -1)
      return -1;
  }

  return 0;
}


/* Send a UDP probe. This takes care of decoys and filling in Ethernet
 * addresses if necessary. Used for the U1 probe. */
int HostOsScan::send_closedudp_probe(HostOsScanStats *hss,
                                     int ttl, u16 sport, u16 dport) {
  static int myttl = 0;
  static u8 patternbyte = 0x43; /* character 'C' */
  static u16 id = 0x1042;
  u8 packet[328]; /* 20 IP hdr + 8 UDP hdr + 300 data */
  struct ip *ip = (struct ip *) packet;
  struct udp_hdr *udp = (struct udp_hdr *) (packet + sizeof(struct ip));
  struct in_addr *source;
  int datalen = 300;
  unsigned char *data = packet + 28;
  unsigned short realcheck; /* the REAL checksum */
  int res;
  int decoy;
  struct eth_nfo eth, *ethptr;

  ethptr = hss->fill_eth_nfo(&eth, ethsd);

  /* if (!patternbyte) patternbyte = (get_random_uint() % 60) + 65; */
  memset(data, patternbyte, datalen);

  /*  while (!id) id = get_random_uint(); */

  if (ttl == -1) {
    myttl = (time(NULL) % 14) + 51;
  } else {
    myttl = ttl;
  }

  /* check that required fields are there and not too silly */
  if (!sport || !dport) {
    error("%s: One or more of your parameters suck!", __func__);
    return 1;
  }

  for (decoy = 0; decoy < o.numdecoys; decoy++) {
    source = &o.decoys[decoy];

    memset((char *) packet, 0, sizeof(struct ip) + sizeof(struct udp_hdr));

    udp->uh_sport = htons(sport);
    udp->uh_dport = htons(dport);
    udp->uh_ulen = htons(8 + datalen);

    /* OK, now we should be able to compute a valid checksum */
    realcheck = ipv4_pseudoheader_cksum(source, hss->target->v4hostip(), IPPROTO_UDP,
                                        sizeof(struct udp_hdr) + datalen, (char *) udp);
#if STUPID_SOLARIS_CHECKSUM_BUG
    udp->uh_sum = sizeof(struct udp_hdr) + datalen;
#else
    udp->uh_sum = realcheck;
#endif

    /* Now for the ip header */
    ip->ip_v = 4;
    ip->ip_hl = 5;
    ip->ip_len = htons(sizeof(struct ip) + sizeof(struct udp_hdr) + datalen);
    ip->ip_id = htons(id);
    ip->ip_ttl = myttl;
    ip->ip_p = IPPROTO_UDP;
    ip->ip_src.s_addr = source->s_addr;
    ip->ip_dst.s_addr= hss->target->v4hostip()->s_addr;

    hss->upi.ipck = in_cksum((unsigned short *)ip, sizeof(struct ip));
#if HAVE_IP_IP_SUM
    ip->ip_sum = hss->upi.ipck;
#endif

    /* OK, now if this is the real she-bang (ie not a decoy) then
       we stick all the inph0 in our upi */
    if (decoy == o.decoyturn) {
      hss->upi.iptl = 28 + datalen;
      hss->upi.ipid = id;
      hss->upi.sport = sport;
      hss->upi.dport = dport;
      hss->upi.udpck = realcheck;
      hss->upi.udplen = 8 + datalen;
      hss->upi.patternbyte = patternbyte;
      hss->upi.target.s_addr = ip->ip_dst.s_addr;
    }

    if ((res = send_ip_packet(rawsd, ethptr, hss->target->TargetSockAddr(), packet, ntohs(ip->ip_len))) == -1)
      {
        gh_perror("send_ip_packet in %s", __func__);
        return 1;
      }
  }

  return 0;
}


/******************************************************************************
 * Implementation of class ScanStats                                          *
 ******************************************************************************/

ScanStats::ScanStats() {
  /* init timing val */
  timing.cwnd = perf.group_initial_cwnd;
  timing.ssthresh = perf.initial_ssthresh; /* Will be reduced if any packets are dropped anyway */
  timing.num_replies_expected = 0;
  timing.num_replies_received = 0;
  timing.num_updates = 0;
  gettimeofday(&timing.last_drop, NULL);

  initialize_timeout_info(&to);

  num_probes_active = 0;
  num_probes_sent = num_probes_sent_at_last_wait = 0;
}


/* Returns true if the os scan system says that sending is OK.*/
bool ScanStats::sendOK() {
  if (num_probes_sent - num_probes_sent_at_last_wait >= 50)
    return false;

  if (timing.cwnd < num_probes_active + 0.5)
    return false;

  return true;
}


/******************************************************************************
 * Implementation of class HostOsScan                                         *
 ******************************************************************************/

void HostOsScan::makeTSeqFP(HostOsScanStats *hss) {
  int i, j;
  u32 seq_diffs[NUM_SEQ_SAMPLES];
  u32 ts_diffs[NUM_SEQ_SAMPLES];
  float seq_rates[NUM_SEQ_SAMPLES];
  unsigned long time_usec_diffs[NUM_SEQ_SAMPLES];
  double seq_stddev = 0;
  double seq_rate = 0;
  double seq_avg_rate = 0;
  double avg_ts_hz = 0.0; /* Avg. amount that timestamps incr. each second */
  u32 seq_gcd = 1;
  int tcp_ipid_seqclass; /* TCP IPID SEQ TYPE defines in nmap.h */
  int tcp_closed_ipid_seqclass; /* TCP IPID SEQ TYPE defines in nmap.h */
  int icmp_ipid_seqclass; /* ICMP IPID SEQ TYPE defines in nmap.h */
  int good_tcp_ipid_num, good_tcp_closed_ipid_num, good_icmp_ipid_num;
  int tsnewval = 0;

  std::vector<struct AVal> seq_AVs;
  struct AVal AV;

  /* Need 8 AVals for SP, GCD, ISR, TI, CI, II, SS, TS. */
  seq_AVs.reserve(8);

  /* Now we make sure there are no gaps in our response array ... */
  for (i = 0, j = 0; i < NUM_SEQ_SAMPLES; i++) {
    if (hss->si.seqs[i] != 0) /* We found a good one */ {
      if (j < i) {
        hss->si.seqs[j] = hss->si.seqs[i];
        hss->si.ipids[j] = hss->si.ipids[i];
        hss->si.timestamps[j] = hss->si.timestamps[i];
        hss->seq_send_times[j] = hss->seq_send_times[i];
      }
      if (j > 0) {
        seq_diffs[j - 1] = MOD_DIFF(hss->si.seqs[j], hss->si.seqs[j - 1]);

        ts_diffs[j - 1] = MOD_DIFF(hss->si.timestamps[j], hss->si.timestamps[j - 1]);
        time_usec_diffs[j - 1] = TIMEVAL_SUBTRACT(hss->seq_send_times[j], hss->seq_send_times[j - 1]);
        if (!time_usec_diffs[j - 1]) time_usec_diffs[j - 1]++; /* We divide by this later */
    /* Rate of ISN increase per second */
    seq_rates[j - 1] = seq_diffs[j - 1] * 1000000.0 / time_usec_diffs[j - 1];
    seq_avg_rate += seq_rates[j - 1];
      }
      j++;
    } /* Otherwise nothing good in this slot to copy */
  }

  hss->si.responses = j; /* Just for assurance */

  /* Time to look at the TCP ISN predictability */
  if (hss->si.responses >= 4 && o.scan_delay <= 1000) {
    seq_avg_rate /= hss->si.responses - 1;
    seq_rate = seq_avg_rate;

    /* First calculate the GCD */
    seq_gcd = gcd_n_uint(hss->si.responses -1, seq_diffs);

    if (!seq_gcd) {
      /* Constant ISN */
      seq_rate = 0;
      seq_stddev = 0;
      hss->si.index = 0;
    } else {

      /* Finally we take a binary logarithm, multiply by 8, and round
       * to get the final result */
      seq_rate = log(seq_rate) / log(2.0);
      seq_rate = (unsigned int) (seq_rate * 8 + 0.5);

      /* Normally we don't divide by gcd in computing the rate stddev
       * because otherwise we'll get an artificially low value about
       * 1/32 of the time if the responses all happen to be even.  On
       * the other hand, if a system inherently uses a large gcd such
       * as 64,000, we want to get rid of it.  So as a compromise, we
       * divide by the gcd if it is at least 9 */
      int div_gcd = 1;
      if (seq_gcd > 9)
        div_gcd = seq_gcd;

      for (i = 0; i < hss->si.responses - 1; i++) {
        double rtmp = seq_rates[i] / div_gcd - seq_avg_rate / div_gcd;
        seq_stddev += rtmp * rtmp;
      }

      /* We divide by ((numelements in seq_diffs) - 1), which is
       * (si.responses - 2), because that gives a better approx of
       * std. dev when you're only looking at a subset of whole
       * population. */
      seq_stddev /= hss->si.responses - 2;

      /* Next we need to take the square root of this value */
      seq_stddev = sqrt(seq_stddev);

      /* Finally we take a binary logarithm, multiply by 8, and round
       * to get the final result */
      if (seq_stddev <= 1)
        hss->si.index = 0;
      else {
        seq_stddev = log(seq_stddev) / log(2.0);
        hss->si.index = (int) (seq_stddev * 8 + 0.5);
      }
    }

    AV.attribute = "SP";
    AV.value = string_pool_sprintf("%X", hss->si.index);
    seq_AVs.push_back(AV);
    AV.attribute = "GCD";
    AV.value = string_pool_sprintf("%X", seq_gcd);
    seq_AVs.push_back(AV);
    AV.attribute = "ISR";
    AV.value = string_pool_sprintf("%X", (unsigned int) seq_rate);
    seq_AVs.push_back(AV);
  } else if (hss->si.responses > 0) {
    if (o.debugging)
      log_write(LOG_PLAIN, "Insufficient responses from %s for TCP sequencing (%d), OS detection may be less accurate\n", hss->target->targetipstr(), hss->si.responses);
  }

  /* Now it is time to deal with IPIDs */
  good_tcp_ipid_num = 0;
  good_tcp_closed_ipid_num = 0;
  good_icmp_ipid_num = 0;

  for (i = 0; i < NUM_SEQ_SAMPLES; i++) {
    if (hss->ipid.tcp_ipids[i] != -1) {
      if (good_tcp_ipid_num < i) {
        hss->ipid.tcp_ipids[good_tcp_ipid_num] = hss->ipid.tcp_ipids[i];
      }
      good_tcp_ipid_num++;
    }

    if (hss->ipid.tcp_closed_ipids[i] != -1) {
      if (good_tcp_closed_ipid_num < i) {
        hss->ipid.tcp_closed_ipids[good_tcp_closed_ipid_num] = hss->ipid.tcp_closed_ipids[i];
      }
      good_tcp_closed_ipid_num++;
    }

    if (hss->ipid.icmp_ipids[i] != -1) {
      if (good_icmp_ipid_num < i) {
        hss->ipid.icmp_ipids[good_icmp_ipid_num] = hss->ipid.icmp_ipids[i];
      }
      good_icmp_ipid_num++;
    }
  }

  if (good_tcp_ipid_num >= 3) {
    tcp_ipid_seqclass = get_ipid_sequence(good_tcp_ipid_num, hss->ipid.tcp_ipids, islocalhost(hss->target->TargetSockAddr()));
  } else {
    tcp_ipid_seqclass = IPID_SEQ_UNKNOWN;
  }
  /* Only print open tcp ipid seqclass in the final report. */
  hss->si.ipid_seqclass = tcp_ipid_seqclass;

  if (good_tcp_closed_ipid_num >= 2) {
    tcp_closed_ipid_seqclass = get_ipid_sequence(good_tcp_closed_ipid_num, hss->ipid.tcp_closed_ipids, islocalhost(hss->target->TargetSockAddr()));
  } else {
    tcp_closed_ipid_seqclass = IPID_SEQ_UNKNOWN;
  }

  if (good_icmp_ipid_num >= 2) {
    icmp_ipid_seqclass = get_ipid_sequence(good_icmp_ipid_num, hss->ipid.icmp_ipids, islocalhost(hss->target->TargetSockAddr()));
  } else {
    icmp_ipid_seqclass = IPID_SEQ_UNKNOWN;
  }

  /* This fills in TI=Z or something like that. */
  if (make_aval_ipid_seq(&AV, "TI", tcp_ipid_seqclass, hss->ipid.tcp_ipids) != NULL)
    seq_AVs.push_back(AV);
  if (make_aval_ipid_seq(&AV, "CI", tcp_closed_ipid_seqclass, hss->ipid.tcp_closed_ipids) != NULL)
    seq_AVs.push_back(AV);
  if (make_aval_ipid_seq(&AV, "II", icmp_ipid_seqclass, hss->ipid.icmp_ipids) != NULL)
    seq_AVs.push_back(AV);

  /* SS: Shared IP ID sequence boolean */
  if ( (tcp_ipid_seqclass == IPID_SEQ_INCR ||
        tcp_ipid_seqclass == IPID_SEQ_BROKEN_INCR ||
        tcp_ipid_seqclass == IPID_SEQ_RPI) &&
       (icmp_ipid_seqclass == IPID_SEQ_INCR ||
        icmp_ipid_seqclass == IPID_SEQ_BROKEN_INCR ||
        icmp_ipid_seqclass == IPID_SEQ_RPI)) {
    /* Both are incremental. Thus we have "SS" test. Check if they
       are in the same sequence. */
    AV.attribute = "SS";
    int avg = (hss->ipid.tcp_ipids[good_tcp_ipid_num - 1] - hss->ipid.tcp_ipids[0]) / (good_tcp_ipid_num - 1);
    if ( hss->ipid.icmp_ipids[0] < hss->ipid.tcp_ipids[good_tcp_ipid_num - 1] + 3 * avg) {
      AV.value = "S";
    } else {
      AV.value = "O";
    }
    seq_AVs.push_back(AV);
  }

  /* Now we look at TCP Timestamp sequence prediction */
  /* Battle plan:
     1) Compute average increments per second, and variance in incr. per second
     2) If any are 0, set to constant
     3) If variance is high, set to random incr. [ skip for now ]
     4) if ~10/second, set to appropriate thing
     5) Same with ~100/sec
  */
  if (hss->si.ts_seqclass == TS_SEQ_UNKNOWN && hss->si.responses >= 2) {
    double lastboot = 0.0;
    avg_ts_hz = 0.0;
    for (i = 0; i < hss->si.responses - 1; i++) {
      double dhz;

      dhz = (double) ts_diffs[i] / (time_usec_diffs[i] / 1000000.0);
      /*       printf("ts incremented by %d in %li usec -- %fHZ\n", ts_diffs[i], time_usec_diffs[i], dhz); */
      avg_ts_hz += dhz / ( hss->si.responses - 1);
    }

    if (avg_ts_hz > 0 && avg_ts_hz < 5.66) { /* relatively wide range because sampling time so short and frequency so slow */
      hss->si.ts_seqclass = TS_SEQ_2HZ;
      lastboot = (double) hss->seq_send_times[0].tv_sec - (hss->si.timestamps[0] / 2);
      hss->si.lastboot = hss->seq_send_times[0].tv_sec - (hss->si.timestamps[0] / 2);
    }
    else if (avg_ts_hz > 70 && avg_ts_hz < 150) {
      hss->si.ts_seqclass = TS_SEQ_100HZ;
      lastboot = (double) hss->seq_send_times[0].tv_sec - (hss->si.timestamps[0] / 100);
    }
    else if (avg_ts_hz > 724 && avg_ts_hz < 1448) {
      hss->si.ts_seqclass = TS_SEQ_1000HZ;
      lastboot = (double) hss->seq_send_times[0].tv_sec - (hss->si.timestamps[0] / 1000);
    }
    else if (avg_ts_hz > 0) {
      hss->si.ts_seqclass = TS_SEQ_OTHER_NUM;
      lastboot = (double) hss->seq_send_times[0].tv_sec - (hss->si.timestamps[0] / (unsigned int)(0.5 + avg_ts_hz));
    }

    if (lastboot != 0.0 && (hss->seq_send_times[0].tv_sec - lastboot > 63072000)) {
      /* Up 2 years?  Perhaps, but they're probably lying. */
      if (o.debugging) {
        log_write(LOG_STDOUT, "Ignoring claimed %s uptime of %lu days",
        hss->target->targetipstr(), (hss->seq_send_times[0].tv_sec - hss->si.lastboot) / 86400);
      }
      lastboot = 0;
    }
    hss->si.lastboot = (long) lastboot;
  }

  switch (hss->si.ts_seqclass) {

  case TS_SEQ_ZERO:
    AV.attribute = "TS";
    AV.value = "0";
    seq_AVs.push_back(AV);
    break;
  case TS_SEQ_2HZ:
  case TS_SEQ_100HZ:
  case TS_SEQ_1000HZ:
  case TS_SEQ_OTHER_NUM:
    AV.attribute = "TS";

    /* Here we "cheat" a little to make the classes correspond more
       closely to common real-life frequencies (particularly 100)
       which aren't powers of two. */
    if (avg_ts_hz <= 5.66) {
      /* 1 would normally range from 1.4 - 2.82, but we expand that
         to 0 - 5.66, so we won't ever even get a value of 2.  Needs
         to be wide because our test is so fast that it is hard to
         match slow frequencies exactly.  */
      tsnewval = 1;
    } else if (avg_ts_hz > 70 && avg_ts_hz <= 150) {
      /* mathematically 7 would be 90.51 - 181, but we change to 70-150 to
         better align with common freq 100 */
      tsnewval = 7;
    } else if (avg_ts_hz > 150 && avg_ts_hz <= 350) {
      /* would normally be 181 - 362.  Now aligns better with 200 */
      tsnewval = 8;
    } else {
      /* Do a log base2 rounded to nearest int */
      tsnewval = (unsigned int)(0.5 + log(avg_ts_hz) / log(2.0));
    }

    AV.value = string_pool_sprintf("%X", tsnewval);
    seq_AVs.push_back(AV);
    break;
  case TS_SEQ_UNSUPPORTED:
    AV.attribute = "TS";
    AV.value = "U";
    seq_AVs.push_back(AV);
    break;
  }

  /* Now generate the SEQ line of the fingerprint if there are any test results
     in seq_AVs. */
  if (!seq_AVs.empty()) {
    hss->FP_TSeq = new FingerTest;
    hss->FP_TSeq->name = "SEQ";
    hss->FP_TSeq->results = seq_AVs;
  }
}


void HostOsScan::makeTOpsFP(HostOsScanStats *hss) {
  assert(hss);
  std::vector<struct AVal> AVs;
  int i, n;

  if (hss->TOpsReplyNum != 6)
    return;

  for (n = 0; n < 6; n++) {
    if (!hss->TOps_AVs[n])
      break;
  }
  if (n < 6) {
    if (o.debugging)
      error("We didn't get all the TOps replies from %s", hss->target->targetipstr());
    return;
  }

  AVs.reserve(n);

  for (i = 0; i < n; i++)
    AVs.push_back(*hss->TOps_AVs[i]);

  hss->FP_TOps = new FingerTest;
  hss->FP_TOps->results = AVs;
  hss->FP_TOps->name = "OPS";
}


void HostOsScan::makeTWinFP(HostOsScanStats *hss) {
  assert(hss);
  std::vector<struct AVal> AVs;
  int i, n;

  if (hss->TWinReplyNum != 6)
    return;

  for (n = 0; n < 6; n++) {
    if (!hss->TWin_AVs[n])
      break;
  }
  if (n < 6) {
    if (o.debugging)
      error("We didn't get all the TWin replies from %s", hss->target->targetipstr());
    return;
  }

  AVs.reserve(n);

  for (i = 0; i < n; i++)
    AVs.push_back(*hss->TWin_AVs[i]);

  hss->FP_TWin = new FingerTest;
  hss->FP_TWin->results = AVs;
  hss->FP_TWin->name = "WIN";
}


bool HostOsScan::processTSeqResp(HostOsScanStats *hss, struct ip *ip, int replyNo) {
  assert(replyNo >= 0 && replyNo < NUM_SEQ_SAMPLES);

  struct tcp_hdr *tcp;
  int seq_response_num; /* response # for sequencing */
  u32 timestamp = 0; /* TCP timestamp we receive back */

  if (hss->lastipid != 0 && ip->ip_id == hss->lastipid) {
    /* Probably a duplicate -- this happens sometimes when scanning localhost */
    return false;
  }
  hss->lastipid = ip->ip_id;

  tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));

  if ((tcp->th_flags & TH_RST)) {
    if (hss->si.responses == 0) {
      error("WARNING:  RST from %s port %d -- is this port really open?",
              hss->target->targetipstr(), hss->openTCPPort);
    }
    return false;
  }

  if ((tcp->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
    /*  error("DEBUG: response is SYN|ACK to port %hu\n", ntohs(tcp->th_dport)); */
    /*readtcppacket((char *)ip, ntohs(ip->ip_len));*/
    /* We use the ACK value to match up our sent with rcv'd packets */
    seq_response_num = ntohl(tcp->th_ack) - tcpSeqBase - 1;
    /* printf("seq_response_num = %d\treplyNo = %d\n", seq_response_num, replyNo); */

    if (seq_response_num != replyNo) {
      /* BzzT! Value out of range */
      if (o.debugging) {
        error("Unable to associate os scan response with sent packet for %s.",
              hss->target->targetipstr());
        error("Received ack: %lX; sequence sent: %lX. Packet:",
              (unsigned long) ntohl(tcp->th_ack),
              (unsigned long) tcpSeqBase);
        readtcppacket((unsigned char *)ip, ntohs(ip->ip_len));
      }
      seq_response_num = replyNo;
    }

    if (hss->si.seqs[seq_response_num] == 0) {
      /* New response found! */
      hss->si.responses++;
      hss->si.seqs[seq_response_num] = ntohl(tcp->th_seq); /* TCP ISN */
      hss->si.ipids[seq_response_num] = ntohs(ip->ip_id);

      if ((gettcpopt_ts(tcp, &timestamp, NULL) == 0))
        hss->si.ts_seqclass = TS_SEQ_UNSUPPORTED;
      else {
        if (timestamp == 0) {
          hss->si.ts_seqclass = TS_SEQ_ZERO;
        }
      }
      hss->si.timestamps[seq_response_num] = timestamp;
      /* printf("Response #%d -- ipid=%hu ts=%i\n", seq_response_num, ntohs(ip->ip_id), timestamp); */

      return true;
    }
  }

  return false;
}


bool HostOsScan::processTOpsResp(HostOsScanStats *hss, struct tcp_hdr *tcp, int replyNo) {
  assert(replyNo >= 0 || replyNo < 6);
  char ops_buf[256];
  bool opsParseResult;

  if (hss->FP_TOps || hss->TOps_AVs[replyNo])
    return false;

  hss->TOps_AVs[replyNo] = (struct AVal *) safe_zalloc(sizeof(struct AVal));
  opsParseResult = get_tcpopt_string(tcp, this->tcpMss, ops_buf, sizeof(ops_buf));

  if (!opsParseResult) {
    if (o.debugging)
      error("Option parse error for TOps response %d from %s.", replyNo, hss->target->targetipstr());
    hss->TOps_AVs[replyNo]->value = "";
  }

  hss->TOps_AVs[replyNo]->value = string_pool_insert(ops_buf);

  switch (replyNo) {
  case 0:
    hss->TOps_AVs[replyNo]->attribute = "O1";
    break;
  case 1:
    hss->TOps_AVs[replyNo]->attribute = "O2";
    break;
  case 2:
    hss->TOps_AVs[replyNo]->attribute = "O3";
    break;
  case 3:
    hss->TOps_AVs[replyNo]->attribute = "O4";
    break;
  case 4:
    hss->TOps_AVs[replyNo]->attribute = "O5";
    break;
  case 5:
    hss->TOps_AVs[replyNo]->attribute = "O6";
    break;
  }

  hss->TOpsReplyNum++;
  return true;
}


bool HostOsScan::processTWinResp(HostOsScanStats *hss, struct tcp_hdr *tcp, int replyNo) {
  assert(replyNo >= 0 || replyNo < 6);

  if (hss->FP_TWin || hss->TWin_AVs[replyNo])
    return false;

  hss->TWin_AVs[replyNo] = (struct AVal *) safe_zalloc(sizeof(struct AVal));
  hss->TWin_AVs[replyNo]->value = string_pool_sprintf("%hX", ntohs(tcp->th_win));

  switch (replyNo) {
  case 0:
    hss->TWin_AVs[replyNo]->attribute = "W1";
    break;
  case 1:
    hss->TWin_AVs[replyNo]->attribute = "W2";
    break;
  case 2:
    hss->TWin_AVs[replyNo]->attribute = "W3";
    break;
  case 3:
    hss->TWin_AVs[replyNo]->attribute = "W4";
    break;
  case 4:
    hss->TWin_AVs[replyNo]->attribute = "W5";
    break;
  case 5:
    hss->TWin_AVs[replyNo]->attribute = "W6";
    break;
  }

  hss->TWinReplyNum++;
  return true;
}


bool HostOsScan::processTEcnResp(HostOsScanStats *hss, struct ip *ip) {
  std::vector<struct AVal> AVs;
  struct AVal AV;
  char ops_buf[256];
  char quirks_buf[10];
  char *p;
  int numtests = 7;
  struct tcp_hdr *tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));
  bool opsParseResult;

  if (hss->FP_TEcn)
    return false;

  /* Create the Avals */
  AVs.reserve(numtests);

  AV.attribute = "R";
  AV.value = "Y";
  AVs.push_back(AV);

  /* don't frag flag */
  AV.attribute = "DF";
  if (ntohs(ip->ip_off) & IP_DF)
    AV.value = "Y";
  else
    AV.value = "N";
  AVs.push_back(AV);

  /* TTL */
  AV.attribute = "T";
  AV.value = string_pool_sprintf("%d", ip->ip_ttl);
  AVs.push_back(AV);

  /* TCP Window size */
  AV.attribute = "W";
  AV.value = string_pool_sprintf("%hX", ntohs(tcp->th_win));
  AVs.push_back(AV);

  /* Now for the TCP options ... */
  AV.attribute = "O";
  opsParseResult = get_tcpopt_string(tcp, this->tcpMss, ops_buf, sizeof(ops_buf));

  if (!opsParseResult) {
    if (o.debugging)
      error("Option parse error for ECN response from %s.", hss->target->targetipstr());
    AV.value = "";
  }

  AV.value = string_pool_insert(ops_buf);
  AVs.push_back(AV);

  /* Explicit Congestion Notification support test */
  AV.attribute = "CC";
  if ((tcp->th_flags & TH_ECE) && (tcp->th_flags & TH_CWR))
    /* echo back */
    AV.value = "S";
  else if (tcp->th_flags & TH_ECE)
    /* support */
    AV.value = "Y";
  else if (!(tcp->th_flags & TH_CWR))
    /* not support */
    AV.value = "N";
  else
    AV.value = "O";
  AVs.push_back(AV);

  /* TCP miscellaneous quirks test */
  AV.attribute = "Q";
  p = quirks_buf;
  if (tcp->th_x2) {
    /* Reserved field of TCP is not zero */
    assert(p + 1 < quirks_buf + sizeof(quirks_buf));
    *p++ = 'R';
  }
  if (!(tcp->th_flags & TH_URG) && tcp->th_urp) {
    /* URG pointer value when urg flag not set */
    assert(p + 1 < quirks_buf + sizeof(quirks_buf));
    *p++ = 'U';
  }
  *p = '\0';
  AV.value = string_pool_insert(quirks_buf);
  AVs.push_back(AV);

  hss->FP_TEcn = new FingerTest;
  hss->FP_TEcn->name = "ECN";
  hss->FP_TEcn->results = AVs;

  return true;
}


bool HostOsScan::processT1_7Resp(HostOsScanStats *hss, struct ip *ip, int replyNo) {
  std::vector<struct AVal> AVs;
  struct AVal AV;
  assert(replyNo >= 0 && replyNo < 7);

  int numtests;
  struct tcp_hdr *tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));

  int i;
  bool opsParseResult;
  int length;
  char flags_buf[10];
  char quirks_buf[10];
  char *p;

  if (hss->FPtests[FP_T1_7_OFF + replyNo])
    return false;

  if (replyNo == 0)
    numtests = 8; /* T1 doesn't has 'Win', 'Ops' tests. */
  else numtests = 10;

  /* Create the Avals */
  AVs.reserve(numtests);

  /* First we give the "response" flag to say we did actually receive
     a packet -- this way we won't match a template with R=N */
  AV.attribute = "R";
  AV.value = "Y";
  AVs.push_back(AV);

  /* Next we check whether the Don't Fragment bit is set */
  AV.attribute = "DF";
  if (ntohs(ip->ip_off) & IP_DF)
    AV.value = "Y";
  else
    AV.value = "N";
  AVs.push_back(AV);

  /* TTL */
  AV.attribute = "T";
  AV.value = string_pool_sprintf("%d", ip->ip_ttl);
  AVs.push_back(AV);

  if (replyNo != 0) {
    /* Now we do the TCP Window size */
    AV.attribute = "W";
    AV.value = string_pool_sprintf("%hX", ntohs(tcp->th_win));
    AVs.push_back(AV);
  }

  /* Seq test values:
     Z   = zero
     A   = same as ack
     A+  = ack + 1
     O   = other
  */
  AV.attribute = "S";
  if (ntohl(tcp->th_seq) == 0)
    AV.value = "Z";
  else if (ntohl(tcp->th_seq) == tcpAck)
    AV.value = "A";
  else if (ntohl(tcp->th_seq) == tcpAck + 1)
    AV.value = "A+";
  else
    AV.value = "O";
  AVs.push_back(AV);

  /* ACK test values:
     Z   = zero
     S   = same as syn
     S+  = syn + 1
     O   = other
  */
  AV.attribute = "A";
  if (ntohl(tcp->th_ack) == 0)
    AV.value = "Z";
  else if (ntohl(tcp->th_ack) == tcpSeqBase)
    AV.value = "S";
  else if (ntohl(tcp->th_ack) == tcpSeqBase + 1)
    AV.value = "S+";
  else
    AV.value = "O";
  AVs.push_back(AV);

  /* Flags. They must be in this order:
     E = ECN Echo
     U = Urgent
     A = Acknowledgement
     P = Push
     R = Reset
     S = Synchronize
     F = Final
  */
  struct {
    u8 flag;
    char c;
  } flag_defs[] = {
    { TH_ECE, 'E' },
    { TH_URG, 'U' },
    { TH_ACK, 'A' },
    { TH_PUSH, 'P' },
    { TH_RST, 'R' },
    { TH_SYN, 'S' },
    { TH_FIN, 'F' },
  };
  assert(sizeof(flag_defs) / sizeof(flag_defs[0]) < sizeof(flags_buf));
  AV.attribute = "F";
  p = flags_buf;
  for (i = 0; i < (int) (sizeof(flag_defs) / sizeof(flag_defs[0])); i++) {
    if (tcp->th_flags & flag_defs[i].flag)
      *p++ = flag_defs[i].c;
  }
  *p = '\0';
  AV.value = string_pool_insert(flags_buf);
  AVs.push_back(AV);

  if (replyNo != 0) {
    char ops_buf[256];

    /* Now for the TCP options ... */
    AV.attribute = "O";
    opsParseResult = get_tcpopt_string(tcp, this->tcpMss, ops_buf, sizeof(ops_buf));
    if (!opsParseResult) {
      if (o.debugging)
        error("Option parse error for T%d response from %s.", replyNo, hss->target->targetipstr());
      AV.value = "";
    }

    AV.value = string_pool_insert(ops_buf);
    AVs.push_back(AV);
  }

  /* Rst Data CRC32 */
  AV.attribute = "RD";
  length = (int) ntohs(ip->ip_len) - 4 * ip->ip_hl -4 * tcp->th_off;
  if ((tcp->th_flags & TH_RST) && length>0) {
    AV.value = string_pool_sprintf("%08lX", nbase_crc32(((u8 *)tcp) + 4 * tcp->th_off, length));
  } else {
    AV.value = "0";
  }
  AVs.push_back(AV);

  /* TCP miscellaneous quirks test */
  AV.attribute = "Q";
  p = quirks_buf;
  if (tcp->th_x2) {
    /* Reserved field of TCP is not zero */
    assert(p + 1 < quirks_buf + sizeof(quirks_buf));
    *p++ = 'R';
  }
  if (!(tcp->th_flags & TH_URG) && tcp->th_urp) {
    /* URG pointer value when urg flag not set */
    assert(p + 1 < quirks_buf + sizeof(quirks_buf));
    *p++ = 'U';
  }
  *p = '\0';
  AV.value = string_pool_insert(quirks_buf);
  AVs.push_back(AV);

  hss->FPtests[FP_T1_7_OFF + replyNo] = new FingerTest;
  hss->FPtests[FP_T1_7_OFF + replyNo]->results = AVs;
  hss->FPtests[FP_T1_7_OFF + replyNo]->name = (replyNo == 0) ? "T1" : (replyNo == 1) ? "T2" : (replyNo == 2) ? "T3" : (replyNo == 3) ? "T4" : (replyNo == 4) ? "T5" : (replyNo == 5) ? "T6" : "T7";

  return true;
}


bool HostOsScan::processTUdpResp(HostOsScanStats *hss, struct ip *ip) {
  std::vector<struct AVal> AVs;
  struct AVal AV;

  assert(hss);
  assert(ip);

  struct icmp *icmp;
  struct ip *ip2;
  int numtests;
  unsigned short checksum;
  unsigned short *checksumptr;
  struct udp_hdr *udp;
  unsigned char *datastart, *dataend;

#if !defined(SOLARIS) && !defined(SUNOS) && !defined(IRIX) && !defined(HPUX)
  numtests = 10;
#else
  /* We don't do RID test under these operating systems, thus the
        number of test is 1 less. */
  numtests = 9;
#endif

  if (hss->FP_TUdp)
    return false;

  icmp = ((struct icmp *)(((char *) ip) + 4 * ip->ip_hl));

  /* Make sure this is icmp port unreachable. */
  assert(icmp->icmp_type == 3 && icmp->icmp_code == 3);

  ip2 = (struct ip*)((char *)icmp + 8);
  udp = (struct udp_hdr *)((char *)ip2 + 4 * ip2->ip_hl);

  /* The ports should match. */
  if (ntohs(udp->uh_sport) != hss->upi.sport || ntohs(udp->uh_dport) != hss->upi.dport) {
    return false;
  }

  /* Create the Avals */
  AVs.reserve(numtests);

  /* First of all, if we got this far the response was yes */
  AV.attribute = "R";
  AV.value = "Y";
  AVs.push_back(AV);

  /* Also, we now know that the port we reached was closed */
  if (hss->target->FPR->osscan_closedudpport == -1)
    hss->target->FPR->osscan_closedudpport = hss->upi.dport;

  /* Now let us do an easy one, Don't fragment */
  AV.attribute = "DF";
  if (ntohs(ip->ip_off) & IP_DF)
    AV.value = "Y";
  else
    AV.value = "N";
  AVs.push_back(AV);

  /* TTL */
  AV.attribute = "T";
  AV.value = string_pool_sprintf("%d", ip->ip_ttl);
  AVs.push_back(AV);

  /* Now we look at the IP datagram length that was returned, some
     machines send more of the original packet back than others */
  AV.attribute = "IPL";
  AV.value = string_pool_sprintf("%hX", ntohs(ip->ip_len));
  AVs.push_back(AV);

  /* unused filed not zero in Destination Unreachable Message */
  AV.attribute = "UN";
  AV.value = string_pool_sprintf("%hX", ntohl(icmp->icmp_void));
  AVs.push_back(AV);

  /* OK, lets check the returned IP length, some systems @$@ this
     up */
  AV.attribute = "RIPL";
  if (ntohs(ip2->ip_len) == 328)
    AV.value = "G";
  else
    AV.value = string_pool_sprintf("%hX", ntohs(ip2->ip_len));
  AVs.push_back(AV);

  /* This next test doesn't work on Solaris because the lamers
     overwrite our ip_id */
#if !defined(SOLARIS) && !defined(SUNOS) && !defined(IRIX) && !defined(HPUX)

  /* Now lets see how they treated the ID we sent ... */
  AV.attribute = "RID";
  if (ntohs(ip2->ip_id) == hss->upi.ipid)
    AV.value = "G"; /* The good "expected" value */
  else
    AV.value = string_pool_sprintf("%hX", ntohs(ip2->ip_id));
  AVs.push_back(AV);

#endif

  /* Let us see if the IP checksum we got back computes */

  AV.attribute = "RIPCK";
  /* Thanks to some machines not having struct ip member ip_sum we
     have to go with this BS */
  checksumptr = (unsigned short *)   ((char *) ip2 + 10);
  checksum = *checksumptr;

  if (checksum == 0) {
    AV.value = "Z";
  } else {
    *checksumptr = 0;
    if (in_cksum((unsigned short *)ip2, 20) == checksum) {
      AV.value = "G"; /* The "expected" good value */
    } else {
      AV.value = "I"; /* They fucked it up */
    }
    *checksumptr = checksum;
  }
  AVs.push_back(AV);

  /* UDP checksum */
  AV.attribute = "RUCK";
  if (udp->uh_sum == hss->upi.udpck)
    AV.value = "G"; /* The "expected" good value */
  else
    AV.value = string_pool_sprintf("%hX", ntohs(udp->uh_sum));
  AVs.push_back(AV);

  /* Finally we ensure the data is OK */
  datastart = ((unsigned char *)udp) + 8;
  dataend = (unsigned char *)  ip + ntohs(ip->ip_len);

  while (datastart < dataend) {
    if (*datastart != hss->upi.patternbyte)
      break;
    datastart++;
  }
  AV.attribute = "RUD";
  if (datastart < dataend)
    AV.value = "I"; /* They fucked it up */
  else
    AV.value = "G";
  AVs.push_back(AV);

  hss->FP_TUdp = new FingerTest;
  hss->FP_TUdp->name = "U1";
  hss->FP_TUdp->results = AVs;

  /* Count hop count */
  if (hss->distance == -1) {
    hss->distance = this->udpttl - ip2->ip_ttl + 1;
  }

  return true;
}


bool HostOsScan::processTIcmpResp(HostOsScanStats *hss, struct ip *ip, int replyNo) {
  assert(replyNo == 0 || replyNo == 1);

  std::vector<struct AVal> AVs;
  struct AVal AV;
  int numtests = 4;
  struct ip *ip1, *ip2;
  struct icmp *icmp1, *icmp2;
  unsigned short value1, value2;

  if (hss->FP_TIcmp)
    return false;

  if (hss->icmpEchoReply == NULL) {
    /* This is the first icmp reply we get, store it and return. */
    hss->icmpEchoReply = (struct ip *) safe_malloc(ntohs(ip->ip_len));
    memcpy(hss->icmpEchoReply, ip, ntohs(ip->ip_len));
    hss->storedIcmpReply = replyNo;
    return true;
  } else if (hss->storedIcmpReply == replyNo) {
    /* This is a dunplicated icmp reply. */
    return false;
  }

  /* Ok, now we get another reply. */
  if (hss->storedIcmpReply == 0) {
    ip1 = hss->icmpEchoReply;
    ip2 = ip;
  } else {
    ip1 = ip;
    ip2 = hss->icmpEchoReply;
  }

  icmp1 = ((struct icmp *)(((char *) ip1) + 4 * ip1->ip_hl));
  icmp2 = ((struct icmp *)(((char *) ip2) + 4 * ip2->ip_hl));

  assert(icmp1->icmp_type == 0 && icmp2->icmp_type == 0);

  /* Create the Avals */
  AVs.reserve(numtests);

  AV.attribute = "R";
  AV.value = "Y";
  AVs.push_back(AV);

  /* DFI test values:
   * Y. Both set DF;
   * S. Both use the DF that the sender uses;
   * N. Both not set;
   * O. Other(both different with the sender, -_-b).
   */
  AV.attribute = "DFI";
  value1 = (ntohs(ip1->ip_off) & IP_DF);
  value2 = (ntohs(ip2->ip_off) & IP_DF);
  if (value1 && value2)
    /* both set */
    AV.value = "Y";
  else if (value1 && !value2)
    /* echo back */
    AV.value = "S";
  else if (!value1 && !value2)
    /* neither set */
    AV.value = "N";
  else
    AV.value = "O";
  AVs.push_back(AV);

  /* TTL */

  AV.attribute = "T";
  AV.value = string_pool_sprintf("%d", ip1->ip_ttl);
  AVs.push_back(AV);

  /* ICMP Code value. Test values:
   * [Value]. Both set Code to the same value [Value];
   * S. Both use the Code that the sender uses;
   * O. Other.
   */
  AV.attribute = "CD";
  value1 = icmp1->icmp_code;
  value2 = icmp2->icmp_code;
  if (value1 == value2) {
    if (value1 == 0)
      AV.value = "Z";
    else
      AV.value = string_pool_sprintf("%hX", value1);
  }
  else if (value1 == 9 && value2 == 0)
    /* both the same as in the corresponding probe */
    AV.value = "S";
  else
    AV.value = "O";
  AVs.push_back(AV);

  hss->FP_TIcmp= new FingerTest;
  hss->FP_TIcmp->name = "IE";
  hss->FP_TIcmp->results = AVs;

  return true;
}


bool HostOsScan::get_tcpopt_string(struct tcp_hdr *tcp, int mss, char *result, int maxlen) {
  char *p, *q;
  u16 tmpshort;
  u32 tmpword;
  int length;
  int opcode;

  p = result;
  length = (tcp->th_off * 4) - sizeof(struct tcp_hdr);
  q = ((char *)tcp) + sizeof(struct tcp_hdr);

  /*
   * Example parsed result: M5B4ST11NW2
   *   MSS, Sack Permitted, Timestamp with both value not zero, Nop, WScale with value 2
   */

  /* Be aware of the max increament value for p in parsing,
   * now is 5 = strlen("Mxxxx") <-> MSS Option
   */
  while (length > 0 && (p - result) < (maxlen - 5)) {
    opcode = *q++;
    if (!opcode) { /* End of List */
      *p++ = 'L';
      length--;
    } else if (opcode == 1) { /* No Op */
      *p++ = 'N';
      length--;
    } else if (opcode == 2) { /* MSS */
      if (length < 4)
        break; /* MSS has 4 bytes */
      *p++ = 'M';
      q++;
      memcpy(&tmpshort, q, 2);
      /*  if (ntohs(tmpshort) == mss) */
      /*    *p++ = 'E'; */
      sprintf(p, "%hX", ntohs(tmpshort));
      p += strlen(p); /* max movement of p is 4 (0xFFFF) */
      q += 2;
      length -= 4;
    } else if (opcode == 3) { /* Window Scale */
      if (length < 3)
        break; /* Window Scale option has 3 bytes */
      *p++ = 'W';
      q++;
      snprintf(p, length, "%hX", *((u8*)q));
      p += strlen(p); /* max movement of p is 2 (max WScale value is 0xFF) */
      q++;
      length -= 3;
    } else if (opcode == 4) { /* SACK permitted */
      if (length < 2)
        break; /* SACK permitted option has 2 bytes */
      *p++ = 'S';
      q++;
      length -= 2;
    } else if (opcode == 8) { /* Timestamp */
      if (length < 10)
        break; /* Timestamp option has 10 bytes */
      *p++ = 'T';
      q++;
      memcpy(&tmpword, q, 4);
      if (tmpword)
        *p++ = '1';
      else
        *p++ = '0';
      q += 4;
      memcpy(&tmpword, q, 4);
      if (tmpword)
        *p++ = '1';
      else
        *p++ = '0';
      q += 4;
      length -= 10;
    }
  }

  if (length > 0) {
    /* We could reach here for one of the two reasons:
     *  1. At least one option is not correct. (Eg. Should have 4 bytes but only has 3 bytes left).
     *  2. The option string is too long.
     */
    *result = '\0';
    return false;
  }

  *p = '\0';
  return true;
}


/******************************************************************************
 * Implementation of class HostOsScanInfo                                     *
 ******************************************************************************/

HostOsScanInfo::HostOsScanInfo(Target *t, OsScanInfo *OsSI) {
  target = t;
  OSI = OsSI;

  FPs = (FingerPrint **) safe_zalloc(o.maxOSTries() * sizeof(FingerPrint *));
  FP_matches = (FingerPrintResultsIPv4 *) safe_zalloc(o.maxOSTries() * sizeof(FingerPrintResultsIPv4));
  timedOut = false;
  isCompleted = false;

  if (target->FPR == NULL) {
    this->FPR = new FingerPrintResultsIPv4;
    target->FPR = this->FPR;
  }
  target->osscanSetFlag(OS_PERF);

  hss = new HostOsScanStats(t);
}


HostOsScanInfo::~HostOsScanInfo() {
  delete hss;
  free(FPs);
  free(FP_matches);
}


/******************************************************************************
 * Implementation of class OsScanInfo                                         *
 ******************************************************************************/

OsScanInfo::OsScanInfo(vector<Target *> &Targets) {
  unsigned int targetno;
  HostOsScanInfo *hsi;
  int num_timedout = 0;

  gettimeofday(&now, NULL);

  numInitialTargets = 0;

  /* build up incompleteHosts list */
  for (targetno = 0; targetno < Targets.size(); targetno++) {
    /* check if Targets[targetno] is good to be scanned
     * if yes, append it to the list
     */
    if (Targets[targetno]->timedOut(&now)) {
      num_timedout++;
      continue;
    }

#ifdef WIN32
    if (Targets[targetno]->ifType() == devt_loopback) {
      log_write(LOG_STDOUT, "Skipping OS Scan against %s because it doesn't work against your own machine (localhost)\n", Targets[targetno]->NameIP());
      continue;
    }
#endif

    if (Targets[targetno]->ports.getStateCounts(IPPROTO_TCP, PORT_OPEN) == 0 ||
        (Targets[targetno]->ports.getStateCounts(IPPROTO_TCP, PORT_CLOSED) == 0 &&
         Targets[targetno]->ports.getStateCounts(IPPROTO_TCP, PORT_UNFILTERED) == 0)) {
      if (o.osscan_limit) {
        if (o.verbose)
          log_write(LOG_PLAIN, "Skipping OS Scan against %s due to absence of open (or perhaps closed) ports\n", Targets[targetno]->NameIP());
        continue;
      } else {
        Targets[targetno]->osscanSetFlag(OS_PERF_UNREL);
      }
    }

    hsi = new HostOsScanInfo(Targets[targetno], this);
    incompleteHosts.push_back(hsi);
    numInitialTargets++;
  }

  nextI = incompleteHosts.begin();
}


OsScanInfo::~OsScanInfo()
{
  while (!incompleteHosts.empty()) {
    delete incompleteHosts.front();
    incompleteHosts.pop_front();
  }
}


/* Find a HostScanStats by IP its address in the incomplete list.  Returns NULL if
   none are found. */
HostOsScanInfo *OsScanInfo::findIncompleteHost(struct sockaddr_storage *ss) {
  list<HostOsScanInfo *>::iterator hostI;
  struct sockaddr_in *sin = (struct sockaddr_in *) ss;

  if (sin->sin_family != AF_INET)
    fatal("%s passed a non IPv4 address", __func__);

  for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end(); hostI++) {
    if ((*hostI)->target->v4hostip()->s_addr == sin->sin_addr.s_addr)
      return *hostI;
  }
  return NULL;
}


/* A circular buffer of the incompleteHosts.  nextIncompleteHost() gives
   the next one.  The first time it is called, it will give the
   first host in the list.  If incompleteHosts is empty, returns
   NULL. */
HostOsScanInfo *OsScanInfo::nextIncompleteHost() {
  HostOsScanInfo *nxt;

  if (incompleteHosts.empty())
    return NULL;

  nxt = *nextI;
  nextI++;
  if (nextI == incompleteHosts.end())
    nextI = incompleteHosts.begin();

  return nxt;
}


/* Removes any hosts that have completed their scans from the incompleteHosts
   list.  Returns the number of hosts removed. */
int OsScanInfo::removeCompletedHosts() {
  list<HostOsScanInfo *>::iterator hostI, nxt;
  HostOsScanInfo *hsi = NULL;
  int hostsRemoved = 0;
  bool timedout = false;

  for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end();
      hostI = nxt) {
    nxt = hostI;
    nxt++;
    hsi = *hostI;
    timedout = hsi->target->timedOut(&now);
    if (hsi->isCompleted || timedout) {
      /* A host to remove!  First adjust nextI appropriately */
      if (nextI == hostI && incompleteHosts.size() > 1) {
        nextI++;
        if (nextI == incompleteHosts.end())
          nextI = incompleteHosts.begin();
      }

      if (o.verbose && numInitialTargets > 50) {
        int remain = incompleteHosts.size() - 1;
        if (remain && !timedout)
          log_write(LOG_STDOUT, "Completed os scan against %s in %.3fs (%d %s)\n",
                    hsi->target->targetipstr(),
                    o.TimeSinceStart() - this->starttime, remain,
                    (remain == 1)? "host left" : "hosts left");
        else if (timedout)
          log_write(LOG_STDOUT, "%s timed out during os scan (%d %s)\n",
                    hsi->target->targetipstr(), remain,
                    (remain == 1)? "host left" : "hosts left");
      }
      incompleteHosts.erase(hostI);
      hostsRemoved++;
      hsi->target->stopTimeOutClock(&now);
      delete hsi;
    }
  }
  return hostsRemoved;
}

/******************************************************************************
 * Implementation of class OSScan()                                           *
 ******************************************************************************/

/* Constructor */
OSScan::OSScan() {
  this->reset();
  return;
}

/* Destructor */
OSScan::~OSScan() {
  return;
}

/* Function that initializes internal variables */
void OSScan::reset() {

}


/* This function takes a group of targets and divides it in chunks if there are
 * too many to be processed at the same time. The threshold is based on Nmap's
 * timing level (when timing level is above 4, no chunking is performed).
 * The reason targets are processed in smaller groups is to improve accuracy. */
int OSScan::chunk_and_do_scan(vector<Target *> &Targets, int family) {
  unsigned int max_os_group_sz = 20;
  double fudgeratio = 1.2; /* Allow a slightly larger final group rather than finish with a tiny one */
  vector<Target *> tmpTargets;
  unsigned int startidx = 0;

  if (o.timing_level == 4)
    max_os_group_sz = (unsigned int) (max_os_group_sz * 1.5);

  if (o.timing_level > 4 || Targets.size() <= max_os_group_sz * fudgeratio) {
    if (family == AF_INET6)
      os_scan_ipv6(Targets);
    else
      os_scan_ipv4(Targets);
    return OP_SUCCESS;
  }

  /* We need to split it up */
  while (startidx < Targets.size()) {
    int diff = Targets.size() - startidx;
    if (diff > max_os_group_sz * fudgeratio) {
      diff = max_os_group_sz;
    }
    tmpTargets.assign(Targets.begin() + startidx, Targets.begin() + startidx + diff);
    if (family == AF_INET6)
      os_scan_ipv6(Targets);
    else
      os_scan_ipv4(Targets);
    startidx += diff;
  }
  return OP_SUCCESS;
}


/* Performs the OS detection for IPv4 hosts. This method should not be called
 * directly. os_scan() should be used instead, as it handles chunking so
 * you don't do too many targets in parallel */
int OSScan::os_scan_ipv4(vector<Target *> &Targets) {
  int itry = 0;
  /* Hosts which haven't matched and have been removed from incompleteHosts because
   * they have exceeded the number of retransmissions the host is allowed. */
  list<HostOsScanInfo *> unMatchedHosts;

  /* Check we have at least one target*/
  if (Targets.size() == 0) {
    return OP_FAILURE;
  }

  perf.init();

  OsScanInfo OSI(Targets);
  if (OSI.numIncompleteHosts() == 0) {
    /* no one will be scanned */
    return OP_FAILURE;
  }
  OSI.starttime = o.TimeSinceStart();
  startTimeOutClocks(&OSI);

  HostOsScan HOS(Targets[0]);

  /* Initialize the pcap session handler in HOS */
  begin_sniffer(&HOS, Targets);
  while (OSI.numIncompleteHosts() != 0) {
    if (itry > 0)
      sleep(1);
    if (itry == 3)
      usleep(1500000); /* Try waiting a little longer just in case it matters */
    if (o.verbose) {
      char targetstr[128];
      bool plural = (OSI.numIncompleteHosts() != 1);
      if (!plural) {
	(*(OSI.incompleteHosts.begin()))->target->NameIP(targetstr, sizeof(targetstr));
      } else Snprintf(targetstr, sizeof(targetstr), "%d hosts", (int) OSI.numIncompleteHosts());
      log_write(LOG_STDOUT, "%s OS detection (try #%d) against %s\n", (itry == 0)? "Initiating" : "Retrying", itry + 1, targetstr);
      log_flush_all();
    }
    startRound(&OSI, &HOS, itry);
    doSeqTests(&OSI, &HOS);
    doTUITests(&OSI, &HOS);
    endRound(&OSI, &HOS, itry);
    expireUnmatchedHosts(&OSI, &unMatchedHosts);
    itry++;
  }

  /* Now move the unMatchedHosts array back to IncompleteHosts */
  if (!unMatchedHosts.empty())
    OSI.incompleteHosts.splice(OSI.incompleteHosts.begin(), unMatchedHosts);

  if (OSI.numIncompleteHosts()) {
    /* For hosts that don't have a perfect match, find the closest fingerprint
     * in the DB and, if we are in debugging mode, print them. */
    findBestFPs(&OSI);
    if (o.debugging > 1)
      printFP(&OSI);
  }

  return OP_SUCCESS;
}


/* Performs the OS detection for IPv6 hosts. This method should not be called
 * directly. os_scan() should be used instead, as it handles chunking so
 * you don't do too many targets in parallel */
int OSScan::os_scan_ipv6(vector<Target *> &Targets) {

  /* Object instantiation */
  FPEngine6 fp6;

  /* Safe checks. */
  if (Targets.size() == 0) {
    return OP_FAILURE;
  }

  return fp6.os_scan(Targets);
}


/* This function performs the OS detection. It processes the supplied list of
 * targets and classifies it into two groups: IPv4 and IPv6 targets. Then,
 * OS detection is carried out for those two separate groups. It returns
 * OP_SUCCESS on success or OP_FAILURE in case of error. */
int OSScan::os_scan(vector<Target *> &Targets) {
  vector<Target *> ip4_targets;
  vector<Target *> ip6_targets;
  int res4 = OP_SUCCESS, res6 = OP_SUCCESS;

  /* Make sure we have at least one target */
  if (Targets.size() <= 0)
    return OP_FAILURE;

  /* Classify targets into two groups: IPv4 and IPv6 */
  for (size_t i = 0; i < Targets.size(); i++) {
      if (Targets[i]->af() == AF_INET6)
          ip6_targets.push_back(Targets[i]);
      else
          ip4_targets.push_back(Targets[i]);
  }

  /* Do IPv4 OS Detection */
  if (ip4_targets.size() > 0)
      res4 = this->os_scan_ipv4(ip4_targets);

  /* Do IPv6 OS Detection */
  if (ip6_targets.size() > 0)
      res6 = this->os_scan_ipv6(ip6_targets);

  /* If both scans were succesful, return OK */
  if (res4 == OP_SUCCESS && res6 == OP_SUCCESS)
    return OP_SUCCESS;
  else
    return OP_FAILURE;
}