File: nmap.cc

package info (click to toggle)
nmap 4.62-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 17,904 kB
  • ctags: 14,278
  • sloc: ansic: 58,868; cpp: 31,473; sh: 12,443; python: 11,074; xml: 8,499; makefile: 813; lex: 434; yacc: 407
file content (2773 lines) | stat: -rw-r--r-- 105,047 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
/***************************************************************************
 * nmap.cc -- Currently handles some of Nmap's port scanning features as   *
 * well as the command line user interface.  Note that the actual main()   *
 * function is in main.cc                                                  *
 *                                                                         *
 ***********************IMPORTANT NMAP LICENSE TERMS************************
 *                                                                         *
 * The Nmap Security Scanner is (C) 1996-2008 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, and version detection.                                       *
 *                                                                         *
 * 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 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-fingerprints 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.  This list is not exclusive, but is just meant to        *
 * clarify our interpretation of derived works with some common examples.  *
 * These restrictions only apply when you actually redistribute Nmap.  For *
 * example, nothing stops you from writing and selling a proprietary       *
 * front-end to Nmap.  Just distribute it by itself, and point people to   *
 * http://nmap.org to download Nmap.                                       *
 *                                                                         *
 * We don't consider these to be added restrictions on top of the GPL, but *
 * just a clarification of how we interpret "derived works" as it applies  *
 * to our GPL-licensed Nmap product.  This is similar to the way Linus     *
 * Torvalds has announced his interpretation of how "derived works"        *
 * applies to Linux kernel modules.  Our interpretation refers only to     *
 * Nmap - we don't speak for any other GPL products.                       *
 *                                                                         *
 * 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 as well as helping to     *
 * fund the continued development of Nmap technology.  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 Copying.OpenSSL 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 fyodor@insecure.org for possible incorporation into the main         *
 * distribution.  By sending these changes to Fyodor or one of the         *
 * Insecure.Org development mailing lists, it is assumed that you are      *
 * offering Fyodor and 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 for more details at                              *
 * http://www.gnu.org/copyleft/gpl.html , or in the COPYING file included  *
 * with Nmap.                                                              *
 *                                                                         *
 ***************************************************************************/

/* $Id: nmap.cc 7182 2008-04-24 03:23:01Z fyodor $ */

#include "nmap.h"
#include "osscan.h"
#include "osscan2.h"
#include "scan_engine.h"
#include "idle_scan.h"
#include "timing.h"
#include "NmapOps.h"
#include "MACLookup.h"
#include "traceroute.h"
#include "nmap_tty.h"
#include "nmap_dns.h"
#include "services.h"
#include "protocols.h"
#include "targets.h"
#include "TargetGroup.h"
#include "service_scan.h"
#include "charpool.h"
#include "nmap_error.h"
#include "utils.h"

#ifndef NOLUA
#include "nse_main.h"
#endif 

#ifdef WIN32
#include "winfix.h"
#endif

using namespace std;

/* global options */
extern char *optarg;
extern int optind;
extern NmapOps o;  /* option structure */

/* parse the --scanflags argument.  It can be a number >=0 or a string consisting of TCP flag names like "URGPSHFIN".  Returns -1 if the argument is invalid. */
static int parse_scanflags(char *arg) {
  int flagval = 0;
  char *end = NULL;

  if (isdigit(arg[0])) {
    flagval = strtol(arg, &end, 0);
    if (*end || flagval < 0 || flagval > 255) return -1;
  } else {
    if (strcasestr(arg, "FIN")) {
      flagval |= TH_FIN;
    } 
    if (strcasestr(arg, "SYN")) {
      flagval |= TH_SYN;
    } 
    if (strcasestr(arg, "RST") || strcasestr(arg, "RESET")) {
      flagval |= TH_RST;
    } 
    if (strcasestr(arg, "PSH") || strcasestr(arg, "PUSH")) {
      flagval |= TH_PUSH;
    } 
    if (strcasestr(arg, "ACK")) {
      flagval |= TH_ACK;
    } 
    if (strcasestr(arg, "URG")) {
      flagval |= TH_URG;
    } 
    if (strcasestr(arg, "ECE")) {
      flagval |= TH_ECE;
    } 
    if (strcasestr(arg, "CWR")) {
      flagval |= TH_CWR;
    } 
    if (strcasestr(arg, "ALL")) {
      flagval = 255;
    }
    if (strcasestr(arg, "NONE")) {
      flagval = 0;
    }
  }
  return flagval;
}

/* parse a URL stype ftp string of the form user:pass@server:portno */
static int parse_bounce_argument(struct ftpinfo *ftp, char *url) {
  char *p = url,*q, *s;

  if ((q = strrchr(url, '@'))) { /* we have user and/or pass */
    *q++ = '\0';

    if ((s = strchr(p, ':'))) { /* we have user AND pass */
      *s++ = '\0';
      strncpy(ftp->pass, s, 255);
    } else { /* we ONLY have user */
      log_write(LOG_STDOUT, "Assuming %s is a username, and using the default password: %s\n",
		p, ftp->pass);
    }

    strncpy(ftp->user, p, 63);
  } else {
    q = url;
  }

  /* q points to beginning of server name */
  if ((s = strchr(q, ':'))) { /* we have portno */
    *s++ = '\0';
    ftp->port = atoi(s);
  }

  strncpy(ftp->server_name, q, MAXHOSTNAMELEN);

  ftp->user[63] = ftp->pass[255] = ftp->server_name[MAXHOSTNAMELEN] = 0;

  return 1;
}

static void printusage(char *name, int rc) {

printf("%s %s ( %s )\n"
       "Usage: nmap [Scan Type(s)] [Options] {target specification}\n"
       "TARGET SPECIFICATION:\n"
       "  Can pass hostnames, IP addresses, networks, etc.\n"
       "  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254\n"
       "  -iL <inputfilename>: Input from list of hosts/networks\n"
       "  -iR <num hosts>: Choose random targets\n"
       "  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks\n"
       "  --excludefile <exclude_file>: Exclude list from file\n"
       "HOST DISCOVERY:\n"
       "  -sL: List Scan - simply list targets to scan\n"
       "  -sP: Ping Scan - go no further than determining if host is online\n"
       "  -PN: Treat all hosts as online -- skip host discovery\n"
       "  -PS/PA/PU [portlist]: TCP SYN/ACK or UDP discovery to given ports\n"
       "  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes\n"
       "  -PO [protocol list]: IP Protocol Ping\n"
       "  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]\n"
       "  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers\n"
       "  --system-dns: Use OS's DNS resolver\n"
       "SCAN TECHNIQUES:\n"
       "  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans\n"
       "  -sU: UDP Scan\n"
       "  -sN/sF/sX: TCP Null, FIN, and Xmas scans\n"
       "  --scanflags <flags>: Customize TCP scan flags\n"
       "  -sI <zombie host[:probeport]>: Idle scan\n"
       "  -sO: IP protocol scan\n"
       "  -b <FTP relay host>: FTP bounce scan\n"
       "  --traceroute: Trace hop path to each host\n"
       "  --reason: Display the reason a port is in a particular state\n"
       "PORT SPECIFICATION AND SCAN ORDER:\n"
       "  -p <port ranges>: Only scan specified ports\n"
       "    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080\n"
       "  -F: Fast mode - Scan fewer ports than the default scan\n"
       "  -r: Scan ports consecutively - don't randomize\n"
       "  --top-ports <number>: Scan <number> most common ports\n"
       "  --port-ratio <ratio>: Scan ports more common than <ratio>\n"
       "SERVICE/VERSION DETECTION:\n"
       "  -sV: Probe open ports to determine service/version info\n"
       "  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)\n"
       "  --version-light: Limit to most likely probes (intensity 2)\n"
       "  --version-all: Try every single probe (intensity 9)\n"
       "  --version-trace: Show detailed version scan activity (for debugging)\n"
#ifndef NOLUA
       "SCRIPT SCAN:\n"
       "  -sC: equivalent to --script=safe,intrusive\n"
       "  --script=<Lua scripts>: <Lua scripts> is a comma separated list of \n"
	   "           directories, script-files or script-categories\n"
	   "  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts\n"
       "  --script-trace: Show all data sent and received\n"
       "  --script-updatedb: Update the script database.\n"
#endif
       "OS DETECTION:\n"
       "  -O: Enable OS detection\n"
       "  --osscan-limit: Limit OS detection to promising targets\n"
       "  --osscan-guess: Guess OS more aggressively\n"
       "TIMING AND PERFORMANCE:\n"
       "  Options which take <time> are in milliseconds, unless you append 's'\n"
       "  (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).\n"
       "  -T[0-5]: Set timing template (higher is faster)\n"
       "  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes\n"
       "  --min-parallelism/max-parallelism <time>: Probe parallelization\n"
       "  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies\n"
       "      probe round trip time.\n"
       "  --max-retries <tries>: Caps number of port scan probe retransmissions.\n"
       "  --host-timeout <time>: Give up on target after this long\n"
       "  --scan-delay/--max-scan-delay <time>: Adjust delay between probes\n"
       "  --min-rate <number>: Send packets no slower than <number> per second\n"
       "FIREWALL/IDS EVASION AND SPOOFING:\n"
       "  -f; --mtu <val>: fragment packets (optionally w/given MTU)\n"
       "  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys\n"
       "  -S <IP_Address>: Spoof source address\n"
       "  -e <iface>: Use specified interface\n"
       "  -g/--source-port <portnum>: Use given port number\n"
       "  --data-length <num>: Append random data to sent packets\n"
       "  --ip-options <options>: Send packets with specified ip options\n"
       "  --ttl <val>: Set IP time-to-live field\n"
       "  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address\n"
       "  --badsum: Send packets with a bogus TCP/UDP checksum\n"
       "OUTPUT:\n"
       "  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,\n"
       "     and Grepable format, respectively, to the given filename.\n"
       "  -oA <basename>: Output in the three major formats at once\n"
       "  -v: Increase verbosity level (use twice or more for greater effect)\n"
       "  -d[level]: Set or increase debugging level (Up to 9 is meaningful)\n"
       "  --open: Only show open (or possibly open) ports\n"
       "  --packet-trace: Show all packets sent and received\n"
       "  --iflist: Print host interfaces and routes (for debugging)\n"
       "  --log-errors: Log errors/warnings to the normal-format output file\n"
       "  --append-output: Append to rather than clobber specified output files\n"
       "  --resume <filename>: Resume an aborted scan\n"
       "  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML\n"
       "  --webxml: Reference stylesheet from Insecure.Org for more portable XML\n"
       "  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output\n"
       "MISC:\n"
       "  -6: Enable IPv6 scanning\n"
       "  -A: Enables OS detection and Version detection, Script scanning and Traceroute\n"
       "  --datadir <dirname>: Specify custom Nmap data file location\n"
       "  --send-eth/--send-ip: Send using raw ethernet frames or IP packets\n"
       "  --privileged: Assume that the user is fully privileged\n"
       "  --unprivileged: Assume the user lacks raw socket privileges\n"
       "  -V: Print version number\n"
       "  -h: Print this help summary page.\n"
       "EXAMPLES:\n"
       "  nmap -v -A scanme.nmap.org\n"
       "  nmap -v -sP 192.168.0.0/16 10.0.0.0/8\n"
       "  nmap -v -iR 10000 -PN -p 80\n"
       "SEE THE MAN PAGE FOR MANY MORE OPTIONS, DESCRIPTIONS, AND EXAMPLES\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
  exit(rc);
}

/**
 * Returns 1 if this is a reserved IP address, where "reserved" means
 * either a private address, non-routable address, or even a non-reserved
 * but unassigned address which has an extremely high probability of being
 * black-holed.
 *
 * We try to optimize speed when ordering the tests. This optimization
 * assumes that all byte values are equally likely in the input.
 *
 * Warning: This function could easily become outdated if the IANA
 * starts to assign some more IPv4 ranges to RIPE, etc. as they have
 * started doing this year (2001), for example 80.0.0.0/4 used to be
 * completely unassigned until they gave 80.0.0.0/7 to RIPE in April
 * 2001 (www.junk.org is an example of a new address in this range).
 *
 * Check <http://www.iana.org/assignments/ipv4-address-space> for
 * the most recent assigments and
 * <http://www.cymru.com/Documents/bogon-bn-nonagg.txt> for bogon
 * netblocks.
 */
static int ip_is_reserved(struct in_addr *ip)
{
  char *ipc = (char *) &(ip->s_addr);
  unsigned char i1 = ipc[0], i2 = ipc[1], i3 = ipc[2], i4 = ipc[3];

  /* do all the /7's and /8's with a big switch statement, hopefully the
   * compiler will be able to optimize this a little better using a jump table
   * or what have you
   */
  switch (i1)
    {
    case 0:         /* 000/8 is IANA reserved       */
    case 1:         /* 001/8 is IANA reserved       */
    case 2:         /* 002/8 is IANA reserved       */
    case 5:         /* 005/8 is IANA reserved       */
    case 6:         /* USA Army ISC                 */
    case 7:         /* used for BGP protocol        */
    case 10:        /* the infamous 10.0.0.0/8      */
    case 14:        /* 014/8 is IANA reserved       */
    case 23:        /* 023/8 is IANA reserved       */
    case 27:        /* 027/8 is IANA reserved       */
    case 31:        /* 031/8 is IANA reserved       */
    case 36:        /* 036/8 is IANA reserved       */
    case 37:        /* 037/8 is IANA reserved       */
    case 39:        /* 039/8 is IANA reserved       */
    case 42:        /* 042/8 is IANA reserved       */
    case 46:        /* 046/8 is IANA reserved       */
    case 49:        /* 049/8 is IANA reserved       */
    case 50:        /* 050/8 is IANA reserved       */
    case 55:        /* misc. U.S.A. Armed forces    */
    case 127:       /* 127/8 is reserved for loopback */
    case 197:       /* 197/8 is IANA reserved       */
    case 223:       /* 223/8 is IANA reserved       */
      return 1;
    default:
      break;
    }

  /* 100-113/8 is IANA reserved */
  if (i1 >= 100 && i1 <= 113)
    return 1;

  /* 172.16.0.0/12 is reserved for private nets by RFC1819 */
  if (i1 == 172 && i2 >= 16 && i2 <= 31)
    return 1;

  /* 175-185/8 is IANA reserved */
  if (i1 >= 175 && i1 <= 185)
    return 1;

  /* 192.168.0.0/16 is reserved for private nets by RFC1819 */
  /* 192.0.2.0/24 is reserved for documentation and examples */
  /* 192.88.99.0/24 is used as 6to4 Relay anycast prefix by RFC3068 */
  if (i1 == 192) {
    if (i2 == 168)
      return 1;
    if (i2 == 0 && i3 == 2)
      return 1;
    if (i2 == 88 && i3 == 99)
      return 1;
  }

  /* 198.18.0.0/15 is used for benchmark tests by RFC2544 */
  if (i1 == 198 && i2 == 18 && i3 >= 1 && i3 <= 64) {
    return 1;
  }

  /* reserved for DHCP clients seeking addresses, not routable outside LAN */
  if (i1 == 169 && i2 == 254)
    return 1;

  /* believe it or not, 204.152.64.0/23 is some bizarre Sun proprietary
   * clustering thing */
  if (i1 == 204 && i2 == 152 && (i3 == 64 || i3 == 65))
    return 1;

  /* 224-239/8 is all multicast stuff */
  /* 240-255/8 is IANA reserved */
  if (i1 >= 224)
    return 1;

  /* 255.255.255.255, note we already tested for i1 in this range */
  if (i2 == 255 && i3 == 255 && i4 == 255)
    return 1;

  return 0;
}

static char *grab_next_host_spec(FILE *inputfd, int argc, char **fakeargv) {
  static char host_spec[1024];
  unsigned int host_spec_index;
  int ch;
  struct in_addr ip;

  if (o.generate_random_ips) {
    do {
      ip.s_addr = get_random_u32();
    } while (ip_is_reserved(&ip));
    Strncpy(host_spec, inet_ntoa(ip), sizeof(host_spec));
  } else if (!inputfd) {
    return( (optind < argc)?  fakeargv[optind++] : NULL);
  } else { 
    host_spec_index = 0;
    while((ch = getc(inputfd)) != EOF) {
      if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\0') {
	if (host_spec_index == 0) continue;
	host_spec[host_spec_index] = '\0';
	return host_spec;
      } else if (host_spec_index < sizeof(host_spec) / sizeof(char) -1) {
	host_spec[host_spec_index++] = (char) ch;
      } else fatal("One of the host_specifications from your input file is too long (> %d chars)", (int) sizeof(host_spec));
    }
    host_spec[host_spec_index] = '\0';
  }
  if (!*host_spec) return NULL;
  return host_spec;
}

int nmap_main(int argc, char *argv[]) {
  char *p, *q;
  int i, arg;
  long l;
  unsigned int targetno;
  FILE *inputfd = NULL, *excludefd = NULL;
  char *host_spec = NULL, *exclude_spec = NULL;
  short randomize=1;
  short quashargv = 0;
  char **host_exp_group;
  char *idleProxy = NULL; /* The idle host used to "Proxy" an idle scan */
  int num_host_exp_groups;
  char *machinefilename = NULL, *kiddiefilename = NULL, 
    *normalfilename = NULL, *xmlfilename = NULL;
  time_t now;
  struct tm *tm;
  HostGroupState *hstate = NULL;
  char *endptr = NULL;
  struct scan_lists *ports = NULL;
  TargetGroup *exclude_group = NULL;
  Traceroute *troute = NULL;
  char myname[MAXHOSTNAMELEN + 1];
#if (defined(IN_ADDR_DEEPSTRUCT) || defined( SOLARIS))
  /* Note that struct in_addr in solaris is 3 levels deep just to store an
   * unsigned int! */
  struct ftpinfo ftp = { FTPUSER, FTPPASS, "",  { { { 0 } } } , 21, 0};
#else
  struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { 0 }, 21, 0};
#endif
  struct hostent *target = NULL;
  char **fakeargv;
  Target *currenths;
  vector<Target *> Targets;
  char *portlist = NULL; /* Ports list specified by user */
  int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
				source addresses? */
  unsigned int ideal_scan_group_sz = 0;
  char hostname[MAXHOSTNAMELEN + 1] = "";
  const char *spoofmac = NULL;
  time_t timep;
  char mytime[128];
  struct sockaddr_storage ss;
  size_t sslen;
  int option_index;
  bool iflist = false;
  struct timeval tv;

  // Pre-specified timing parameters.
  // These are stored here during the parsing of the arguments so that we can
  // set the defaults specified by any timing template options (-T2, etc) BEFORE
  // any of these. In other words, these always take precedence over the templates.
  int pre_max_parallelism=-1, pre_scan_delay=-1, pre_max_scan_delay=-1;
  int pre_init_rtt_timeout=-1, pre_min_rtt_timeout=-1, pre_max_rtt_timeout=-1;
  int pre_max_retries=-1;
  long pre_host_timeout=-1;

  struct option long_options[] =
    {
      {"version", no_argument, 0, 'V'},
      {"verbose", no_argument, 0, 'v'},
      {"datadir", required_argument, 0, 0},
      {"servicedb", required_argument, 0, 0},
      {"versiondb", required_argument, 0, 0},
      {"debug", optional_argument, 0, 'd'},
      {"help", no_argument, 0, 'h'},
      {"iflist", no_argument, 0, 0},
      {"release_memory", no_argument, 0, 0},
      {"release-memory", no_argument, 0, 0},
      {"max_os_tries", required_argument, 0, 0},
      {"max-os-tries", required_argument, 0, 0},
      {"max_parallelism", required_argument, 0, 'M'},
      {"max-parallelism", required_argument, 0, 'M'},
      {"min_parallelism", required_argument, 0, 0},
      {"min-parallelism", required_argument, 0, 0},
      {"timing", required_argument, 0, 'T'},
      {"max_rtt_timeout", required_argument, 0, 0},
      {"max-rtt-timeout", required_argument, 0, 0},
      {"min_rtt_timeout", required_argument, 0, 0},
      {"min-rtt-timeout", required_argument, 0, 0},
      {"initial_rtt_timeout", required_argument, 0, 0},
      {"initial-rtt-timeout", required_argument, 0, 0},
      {"excludefile", required_argument, 0, 0},
      {"exclude", required_argument, 0, 0},
      {"max_hostgroup", required_argument, 0, 0},
      {"max-hostgroup", required_argument, 0, 0},
      {"min_hostgroup", required_argument, 0, 0},
      {"min-hostgroup", required_argument, 0, 0},
      {"open", no_argument, 0, 0},
      {"scanflags", required_argument, 0, 0},
      {"defeat_rst_ratelimit", no_argument, 0, 0},
      {"defeat-rst-ratelimit", no_argument, 0, 0},
      {"host_timeout", required_argument, 0, 0},
      {"host-timeout", required_argument, 0, 0},
      {"scan_delay", required_argument, 0, 0},
      {"scan-delay", required_argument, 0, 0},
      {"max_scan_delay", required_argument, 0, 0},
      {"max-scan-delay", required_argument, 0, 0},
      {"max_retries", required_argument, 0, 0},
      {"max-retries", required_argument, 0, 0},
      {"oA", required_argument, 0, 0},  
      {"oN", required_argument, 0, 0},
      {"oM", required_argument, 0, 0},  
      {"oG", required_argument, 0, 0},  
      {"oS", required_argument, 0, 0},
      {"oH", required_argument, 0, 0},  
      {"oX", required_argument, 0, 0},  
      {"iL", required_argument, 0, 'i'},  
      {"iR", required_argument, 0, 0},
      {"sI", required_argument, 0, 0},  
      {"source_port", required_argument, 0, 'g'},
      {"source-port", required_argument, 0, 'g'},
      {"randomize_hosts", no_argument, 0, 0},
      {"randomize-hosts", no_argument, 0, 0},
      {"osscan_limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
      {"osscan-limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
      {"osscan_guess", no_argument, 0, 0}, /* More guessing flexability */
      {"osscan-guess", no_argument, 0, 0}, /* More guessing flexability */
      {"fuzzy", no_argument, 0, 0}, /* Alias for osscan_guess */
      {"packet_trace", no_argument, 0, 0}, /* Display all packets sent/rcv */
      {"packet-trace", no_argument, 0, 0}, /* Display all packets sent/rcv */
      {"version_trace", no_argument, 0, 0}, /* Display -sV related activity */
      {"version-trace", no_argument, 0, 0}, /* Display -sV related activity */
      {"data_length", required_argument, 0, 0},
      {"data-length", required_argument, 0, 0},
      {"send_eth", no_argument, 0, 0},
      {"send-eth", no_argument, 0, 0},
      {"send_ip", no_argument, 0, 0},
      {"send-ip", no_argument, 0, 0},
      {"stylesheet", required_argument, 0, 0},
      {"no_stylesheet", no_argument, 0, 0},
      {"no-stylesheet", no_argument, 0, 0},
      {"webxml", no_argument, 0, 0},
      {"rH", no_argument, 0, 0},
      {"vv", no_argument, 0, 0},
      {"ff", no_argument, 0, 0},
      {"privileged", no_argument, 0, 0},
      {"unprivileged", no_argument, 0, 0},
      {"mtu", required_argument, 0, 0},
      {"append_output", no_argument, 0, 0},
      {"append-output", no_argument, 0, 0},
      {"noninteractive", no_argument, 0, 0},
      {"spoof_mac", required_argument, 0, 0},
      {"spoof-mac", required_argument, 0, 0},
      {"thc", no_argument, 0, 0},  
      {"badsum", no_argument, 0, 0},  
      {"ttl", required_argument, 0, 0}, /* Time to live */
      {"traceroute", no_argument, 0, 0},
      {"reason", no_argument, 0, 0},
      {"allports", no_argument, 0, 0},
      {"version_intensity", required_argument, 0, 0},
      {"version-intensity", required_argument, 0, 0},
      {"version_light", no_argument, 0, 0},
      {"version-light", no_argument, 0, 0},
      {"version_all", no_argument, 0, 0},
      {"version-all", no_argument, 0, 0},
      {"system_dns", no_argument, 0, 0},
      {"system-dns", no_argument, 0, 0},
      {"log_errors", no_argument, 0, 0},
      {"log-errors", no_argument, 0, 0},
      {"dns_servers", required_argument, 0, 0},
      {"dns-servers", required_argument, 0, 0},
      {"port-ratio", required_argument, 0, 0},
      {"port_ratio", required_argument, 0, 0},
      {"top-ports", required_argument, 0, 0},
      {"top_ports", required_argument, 0, 0},
#ifndef NOLUA
      {"script", required_argument, 0, 0},
      {"script-trace", no_argument, 0, 0},
      {"script_trace", no_argument, 0, 0},
      {"script-updatedb", no_argument, 0, 0},
      {"script_updatedb", no_argument, 0, 0},
      {"script-args",required_argument,0,0},
      {"script_args",required_argument,0,0},
#endif
      {"ip_options", required_argument, 0, 0},
      {"ip-options", required_argument, 0, 0},
      {"min-rate", required_argument, 0, 0},
      {0, 0, 0, 0}
    };

  /* argv faking silliness */
  fakeargv = (char **) safe_malloc(sizeof(char *) * (argc + 1));
  for(i=0; i < argc; i++) {
    fakeargv[i] = strdup(argv[i]);
  }
  fakeargv[argc] = NULL;

  if (argc < 2 ) printusage(argv[0], -1);

  /* You never know when "random" numbers will come in handy ... */
  gettimeofday(&tv, NULL);
  srand((tv.tv_sec ^ tv.tv_usec) ^ getpid() + 31337);

  Targets.reserve(100);
#ifdef WIN32
  win_pre_init();
#endif

  now = time(NULL);
  tm = localtime(&now);

  /* OK, lets parse these args! */
  optind = 1; /* so it can be called multiple times */
  while((arg = getopt_long_only(argc,fakeargv,"6Ab:D:d::e:Ffg:hIi:M:m:nO::o:P:p:qRrS:s:T:Vv", long_options, &option_index)) != EOF) {
    switch(arg) {
    case 0:
#ifndef NOLUA
	if (strcmp(long_options[option_index].name, "script") == 0) {
		o.script = 1;
		o.chooseScripts(optarg);
	} else if(optcmp(long_options[option_index].name,"script-args")==0){
		o.scriptargs=strdup(optarg);
		if(script_check_args()!=0)
			fatal("Error parsing --script-args\n");
	}else if (optcmp(long_options[option_index].name, "script-trace") == 0) {
		o.scripttrace = 1;
	} else if (optcmp(long_options[option_index].name, "script-updatedb") == 0){
		o.scriptupdatedb = 1;
	} else
#endif
	if (optcmp(long_options[option_index].name, "max-os-tries") == 0) {
	l = tval2msecs(optarg);
	if (l < 1 || l > 50) 
	  fatal("Bogus --max-os-tries argument specified, must be between 1 and 50 (inclusive)");
	o.setMaxOSTries(l);
      } else if (optcmp(long_options[option_index].name, "max-rtt-timeout") == 0) {
	l = tval2msecs(optarg);
	if (l < 5) fatal("Bogus --max-rtt-timeout argument specified, must be at least 5");
        if (l < 20) {
	  error("WARNING: You specified a round-trip time timeout (%ld ms) that is EXTRAORDINARILY SMALL.  Accuracy may suffer.", l);
	}
        pre_max_rtt_timeout = l;
      } else if (optcmp(long_options[option_index].name, "min-rtt-timeout") == 0) {
	l = tval2msecs(optarg);
	if (l < 0) fatal("Bogus --min-rtt-timeout argument specified");
	if (l > 50000) {
	  error("Warning:  min-rtt-timeout is given in milliseconds, your value seems pretty large.");
	}
        pre_min_rtt_timeout = l;
      } else if (optcmp(long_options[option_index].name, "initial-rtt-timeout") == 0) {
	l = tval2msecs(optarg);
	if (l <= 0) fatal("Bogus --initial-rtt-timeout argument specified.  Must be positive");
        pre_init_rtt_timeout = l;
      } else if (strcmp(long_options[option_index].name, "excludefile") == 0) {
	if (exclude_spec)
	  fatal("--excludefile and --exclude options are mutually exclusive.");
        excludefd = fopen(optarg, "r");
        if (!excludefd) {
          fatal("Failed to open exclude file %s for reading", optarg);
        }
      } else if (strcmp(long_options[option_index].name, "exclude") == 0) {
	if (excludefd)
	  fatal("--excludefile and --exclude options are mutually exclusive.");
	exclude_spec = strdup(optarg);
      } else if (optcmp(long_options[option_index].name, "max-hostgroup") == 0) {
	o.setMaxHostGroupSz(atoi(optarg));
      } else if (optcmp(long_options[option_index].name, "min-hostgroup") == 0) {
	o.setMinHostGroupSz(atoi(optarg));
	if (atoi(optarg) > 100)
	  error("Warning: You specified a highly aggressive --min-hostgroup.");
      } else if (strcmp(long_options[option_index].name, "open") == 0) {
	o.setOpenOnly(true);
      } else if (strcmp(long_options[option_index].name, "scanflags") == 0) {
	o.scanflags = parse_scanflags(optarg);
	if (o.scanflags < 0) {
	  fatal("--scanflags option must be a number between 0 and 255 (inclusive) or a string like \"URGPSHFIN\".");
	}
      } else if (strcmp(long_options[option_index].name, "iflist") == 0 ) {
	iflist = true;
      } else if (optcmp(long_options[option_index].name, "release-memory") == 0 ) {
	o.release_memory = true;
      } else if (optcmp(long_options[option_index].name, "min-parallelism") == 0 ) {
	o.min_parallelism = atoi(optarg); 
	if (o.min_parallelism < 1) fatal("Argument to --min-parallelism must be at least 1!");
	if (o.min_parallelism > 100) {
	  error("Warning: Your --min-parallelism option is pretty high!  This can hurt reliability.");
	}
      } else if (optcmp(long_options[option_index].name, "host-timeout") == 0) {
	l = tval2msecs(optarg);
	if (l <= 1500) fatal("--host-timeout is specified in milliseconds unless you qualify it by appending 's', 'm', 'h', or 'd'.  The value must be greater than 1500 milliseconds");
	pre_host_timeout = l;
	if (l < 15000) {
	  error("host-timeout is given in milliseconds, so you specified less than 15 seconds (%lims). This is allowed but not recommended.", l);
	}
      } else if (strcmp(long_options[option_index].name, "ttl") == 0) {
	o.ttl = atoi(optarg);
	if (o.ttl < 0 || o.ttl > 255) {
	  fatal("ttl option must be a number between 0 and 255 (inclusive)");
	}
      } else if (strcmp(long_options[option_index].name, "datadir") == 0) {
	o.datadir = strdup(optarg);
      } else if (strcmp(long_options[option_index].name, "servicedb") == 0) {
	o.requested_data_files["nmap-services"] = optarg;
	o.fastscan++;
      } else if (strcmp(long_options[option_index].name, "versiondb") == 0) {
	o.requested_data_files["nmap-service-probes"] = optarg;
      } else if (optcmp(long_options[option_index].name, "append-output") == 0) {
	o.append_output = 1;
      } else if (strcmp(long_options[option_index].name, "noninteractive") == 0) {
	o.noninteractive = true;
      } else if (optcmp(long_options[option_index].name, "spoof-mac") == 0) {
	/* I need to deal with this later, once I'm sure that I have output
	   files set up, --datadir, etc. */
	spoofmac = optarg;
      } else if (strcmp(long_options[option_index].name, "allports") == 0) {
        o.override_excludeports = 1;
      } else if (optcmp(long_options[option_index].name, "version-intensity") == 0) {
	o.version_intensity = atoi(optarg);
	if (o.version_intensity < 0 || o.version_intensity > 9)
		fatal("version-intensity must be between 0 and 9");
      } else if (optcmp(long_options[option_index].name, "version-light") == 0) {
        o.version_intensity = 2;
      } else if (optcmp(long_options[option_index].name, "version-all") == 0) {
        o.version_intensity = 9;
      } else if (optcmp(long_options[option_index].name, "scan-delay") == 0) {
	l = tval2msecs(optarg);
	if (l < 0) fatal("Bogus --scan-delay argument specified.");
	pre_scan_delay = l;
      } else if (optcmp(long_options[option_index].name, "defeat-rst-ratelimit") == 0) {
        o.defeat_rst_ratelimit = 1;
      } else if (optcmp(long_options[option_index].name, "max-scan-delay") == 0) {
	l = tval2msecs(optarg);
	if (l < 0) fatal("--max-scan-delay cannot be negative.");
	pre_max_scan_delay = l;
      } else if (optcmp(long_options[option_index].name, "max-retries") == 0) {
        pre_max_retries = atoi(optarg);
        if (pre_max_retries < 0)
          fatal("max-retries must be positive");
      } else if (optcmp(long_options[option_index].name, "randomize-hosts") == 0
		 || strcmp(long_options[option_index].name, "rH") == 0) {
	o.randomize_hosts = 1;
	o.ping_group_sz = PING_GROUP_SZ * 4;
      } else if (optcmp(long_options[option_index].name, "osscan-limit")  == 0) {
	o.osscan_limit = 1;
      } else if (optcmp(long_options[option_index].name, "osscan-guess")  == 0
                 || strcmp(long_options[option_index].name, "fuzzy") == 0) {
	o.osscan_guess = 1;
      } else if (optcmp(long_options[option_index].name, "packet-trace") == 0) {
	o.setPacketTrace(true);
#ifndef NOLUA
	o.scripttrace = 1;
#endif
      } else if (optcmp(long_options[option_index].name, "version-trace") == 0) {
	o.setVersionTrace(true);
	o.debugging++;
      } else if (optcmp(long_options[option_index].name, "data-length") == 0) {
	o.extra_payload_length = atoi(optarg);
	if (o.extra_payload_length < 0) {
	  fatal("data-length must be greater than 0");
	} else if (o.extra_payload_length > 0) {
	  o.extra_payload = (char *) safe_malloc(o.extra_payload_length);
	  get_random_bytes(o.extra_payload, o.extra_payload_length);
	}
      } else if (optcmp(long_options[option_index].name, "send-eth") == 0) {
	o.sendpref = PACKET_SEND_ETH_STRONG;
      } else if (optcmp(long_options[option_index].name, "send-ip") == 0) {
	o.sendpref = PACKET_SEND_IP_STRONG;
      } else if (strcmp(long_options[option_index].name, "stylesheet") == 0) {
	o.setXSLStyleSheet(optarg);
      } else if (optcmp(long_options[option_index].name, "no-stylesheet") == 0) {
	o.setXSLStyleSheet(NULL);
      } else if (optcmp(long_options[option_index].name, "system-dns") == 0) {
        o.mass_dns = false;
      } else if (optcmp(long_options[option_index].name, "dns-servers") == 0) {
        o.dns_servers = strdup(optarg);
      } else if (optcmp(long_options[option_index].name, "log-errors") == 0) {
        o.log_errors = 1;
      } else if (strcmp(long_options[option_index].name, "webxml") == 0) {
	o.setXSLStyleSheet("http://nmap.org/data/nmap.xsl");
      } else if (strcmp(long_options[option_index].name, "oN") == 0) {
	normalfilename = logfilename(optarg, tm);
      } else if (strcmp(long_options[option_index].name, "oG") == 0 ||
		 strcmp(long_options[option_index].name, "oM") == 0) {
	machinefilename = logfilename(optarg, tm);
      } else if (strcmp(long_options[option_index].name, "oS") == 0) {
	kiddiefilename = logfilename(optarg, tm);
      } else if (strcmp(long_options[option_index].name, "oH") == 0) {
	fatal("HTML output is not directly supported, though Nmap includes an XSL for transforming XML output into HTML.  See the man page.");
      } else if (strcmp(long_options[option_index].name, "oX") == 0) {
	xmlfilename = logfilename(optarg, tm);
      } else if (strcmp(long_options[option_index].name, "oA") == 0) {
	char buf[MAXPATHLEN];
	Snprintf(buf, sizeof(buf), "%s.nmap", logfilename(optarg, tm));
	normalfilename = strdup(buf);
	Snprintf(buf, sizeof(buf), "%s.gnmap", logfilename(optarg, tm));
	machinefilename = strdup(buf);
	Snprintf(buf, sizeof(buf), "%s.xml", logfilename(optarg, tm));
	xmlfilename = strdup(buf);
      } else if (strcmp(long_options[option_index].name, "thc") == 0) {
	printf("!!Greets to Van Hauser, Plasmoid, Skyper and the rest of THC!!\n");
	exit(0);
      } else if (strcmp(long_options[option_index].name, "badsum") == 0) {
	o.badsum = 1;
      } else if (strcmp(long_options[option_index].name, "iR") == 0) {
	o.generate_random_ips = 1;
	o.max_ips_to_scan = strtoul(optarg, &endptr, 10);
	if (*endptr != '\0') {
	  fatal("ERROR: -iR argument must be the maximum number of random IPs you wish to scan (use 0 for unlimited)");
	}
      } else if (strcmp(long_options[option_index].name, "sI") == 0) {
	o.idlescan = 1;
	idleProxy = optarg;
      } else if (strcmp(long_options[option_index].name, "vv") == 0) {
	/* Compatability hack ... ugly */
	o.verbose += 2;
      } else if (strcmp(long_options[option_index].name, "ff") == 0) {
	o.fragscan += 16; 
      } else if (strcmp(long_options[option_index].name, "privileged") == 0) {
	o.isr00t = 1;
      } else if (strcmp(long_options[option_index].name, "unprivileged") == 0) {
	o.isr00t = 0;
      } else if (strcmp(long_options[option_index].name, "mtu") == 0) {
        o.fragscan = atoi(optarg);
        if (o.fragscan <= 0 || o.fragscan % 8 != 0)
            fatal("Data payload MTU must be >0 and multiple of 8");
      } else if (optcmp(long_options[option_index].name, "port-ratio") == 0) {
        char *ptr;
        o.topportlevel = strtod(optarg, &ptr);
        if (!ptr || o.topportlevel < 0 || o.topportlevel >= 1)
          fatal("--port-ratio should be between [0 and 1)");
      } else if (optcmp(long_options[option_index].name, "top-ports") == 0) {
        char *ptr;
        o.topportlevel = strtod(optarg, &ptr);
        if (!ptr || o.topportlevel < 1 || ((double)((int)o.topportlevel)) != o.topportlevel)
          fatal("--top-ports should be an integer 1 or greater");
      } else if (optcmp(long_options[option_index].name, "ip-options") == 0){
        o.ipoptions    = (u8*) safe_malloc(4*10+1);
        o.ipoptionslen = parse_ip_options(optarg, o.ipoptions, 4*10+1, &o.ipopt_firsthop, &o.ipopt_lasthop);
        if(o.ipoptionslen > 4*10)
          fatal("Ip options can't be more than 40 bytes long");
        if(o.ipoptionslen %4 != 0)
          fatal("Ip options must be multiple of 4 (read length is %i bytes)", o.ipoptionslen);
      } else if(strcmp(long_options[option_index].name, "traceroute") == 0) {
	o.traceroute = true;
      } else if(strcmp(long_options[option_index].name, "reason") == 0) {
     o.reason = true;
      } else if(optcmp(long_options[option_index].name, "min-rate") == 0) {
        if (sscanf(optarg, "%f", &o.min_packet_send_rate) != 1 || o.min_packet_send_rate <= 0.0)
          fatal("Argument to --min-rate must be a positive floating-point number");
      } else {
	fatal("Unknown long option (%s) given@#!$#$", long_options[option_index].name);
      }
      break;
    case '6':
#if !HAVE_IPV6
      fatal("I am afraid IPv6 is not available because your host doesn't support it or you chose to compile Nmap w/o IPv6 support.");
#else
      o.setaf(AF_INET6);
#endif /* !HAVE_IPV6 */
      break;
    case 'A':
      o.servicescan = true;
#ifndef NOLUA
      o.script = 1;
#endif
      if (o.isr00t) {
		o.osscan = OS_SCAN_DEFAULT;
		o.traceroute = true;
      }		
      break;
    case 'b': 
      o.bouncescan++;
      if (parse_bounce_argument(&ftp, optarg) < 0 ) {
	error("Your argument to -b is b0rked. Use the normal url style:  user:pass@server:port or just use server and use default anon login\n  Use -h for help");
      }
      break;
    case 'D':
      p = optarg;
      do {    
	q = strchr(p, ',');
	if (q) *q = '\0';
	if (!strcasecmp(p, "me")) {
	  if (o.decoyturn != -1) 
	    fatal("Can only use 'ME' as a decoy once.\n");
	  o.decoyturn = o.numdecoys++;
	} else if (!strcasecmp(p, "rnd") || !strncasecmp(p, "rnd:", 4)) {
	  int i = 1;

	  /* 'rnd:' is allowed and just gives them one */
	  if (strlen(p) > 4)
	    i = atoi(&p[4]);

	  if (i < 1)
	    fatal("Bad 'rnd' decoy \"%s\"", p);

	  if (o.numdecoys + i >= MAX_DECOYS - 1)
	    fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);

	  while (i--) {
	    do {
	      o.decoys[o.numdecoys].s_addr = get_random_u32();
	    } while (ip_is_reserved(&o.decoys[o.numdecoys]));
	    o.numdecoys++;
	  }
	} else {      
	  if (o.numdecoys >= MAX_DECOYS -1)
	    fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
	  if (resolve(p, &o.decoys[o.numdecoys])) {
	    o.numdecoys++;
	  } else {
	    fatal("Failed to resolve decoy host: %s (must be hostname or IP address)", p);
	  }
	}
	if (q) {
	  *q = ',';
	  p = q+1;
	}
      } while(q);
      break;
    case 'd': 
      if (optarg)
	o.debugging = o.verbose = atoi(optarg);
      else {
	o.debugging++; o.verbose++;
      }
      o.reason = true;
      break;
    case 'e': 
      Strncpy(o.device, optarg, sizeof(o.device)); break;
    case 'F': o.fastscan++; break;
    case 'f': o.fragscan += 8; break;
    case 'g': 
      o.magic_port = atoi(optarg);
      o.magic_port_set = 1;
      if (o.magic_port == 0) error("WARNING: a source port of zero may not work on all systems.");
      break;    
    case 'h': printusage(argv[0], 0); break;
    case '?': printusage(argv[0], -1); break;
    case 'I': 
      printf("WARNING: identscan (-I) no longer supported.  Ignoring -I\n");
      break;
      // o.identscan++; break;
    case 'i': 
      if (inputfd) {
	fatal("Only one input filename allowed");
      }
      if (!strcmp(optarg, "-")) {
	inputfd = stdin;
      } else {    
	inputfd = fopen(optarg, "r");
	if (!inputfd) {
	  fatal("Failed to open input file %s for reading", optarg);
	}  
      }
      break;  
    case 'M': 
      pre_max_parallelism = atoi(optarg); 
      if (pre_max_parallelism < 1) fatal("Argument to -M must be at least 1!");
      if (pre_max_parallelism > 900) {
	error("Warning: Your max-parallelism (-M) option is extraordinarily high, which can hurt reliability");
      }
      break;
    case 'm': 
      machinefilename = optarg;
      break;
    case 'n': o.noresolve++; break;
    case 'O': 
      if (!optarg || *optarg == '2')
        o.osscan = OS_SCAN_DEFAULT;
      else if (*optarg == '1')
        fatal("First-generation OS detection (-O1) is no longer supported. Use -O instead.");
      else
        fatal("Unknown argument to -O.");
      break;
    case 'o':
      normalfilename = logfilename(optarg, tm);
      break;
    case 'P': 
      if (*optarg == '\0' || *optarg == 'I' || *optarg == 'E')
	o.pingtype |= PINGTYPE_ICMP_PING;
      else if (*optarg == 'M') 
	o.pingtype |= PINGTYPE_ICMP_MASK;
      else if (*optarg == 'P') 
	o.pingtype |= PINGTYPE_ICMP_TS;
      else if (*optarg == '0' || *optarg == 'N' || *optarg == 'D')      
	o.pingtype = PINGTYPE_NONE;
      else if (*optarg == 'R')
	o.pingtype |= PINGTYPE_ARP;
      else if (*optarg == 'S') {
	o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_SYN);
	if (*(optarg + 1) != '\0') {
	  getpts_simple(optarg + 1, SCAN_TCP_PORT, &o.ping_synprobes, &o.num_ping_synprobes);
	  if (o.num_ping_synprobes <= 0) {
	    fatal("Bogus argument to -PS: %s", optarg + 1);
	  }
	}
	if (o.num_ping_synprobes == 0) {
	  getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &o.ping_synprobes, &o.num_ping_synprobes);
	  assert(o.num_ping_synprobes > 0);
	}
      }
      else if (*optarg == 'T' || *optarg == 'A') {
	/* NmapOps::ValidateOptions() takes care of changing this
	   to SYN if not root or if IPv6 */
	o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK);
	if (*(optarg + 1) != '\0') {
	  getpts_simple(optarg + 1, SCAN_TCP_PORT, &o.ping_ackprobes, &o.num_ping_ackprobes);
	  if (o.num_ping_ackprobes <= 0) {
	    fatal("Bogus argument to -PA: %s", optarg + 1);
	  }
	}
	if (o.num_ping_ackprobes == 0) {
	  getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &o.ping_ackprobes, &o.num_ping_ackprobes);
	  assert(o.num_ping_ackprobes > 0);
	}
      }
      else if (*optarg == 'U') {
	o.pingtype |= (PINGTYPE_UDP);
	if (*(optarg + 1) != '\0') {
	  getpts_simple(optarg + 1, SCAN_UDP_PORT, &o.ping_udpprobes, &o.num_ping_udpprobes);
	  if (o.num_ping_udpprobes <= 0) {
	    fatal("Bogus argument to -PU: %s", optarg + 1);
	  }
	}
	if (o.num_ping_udpprobes == 0) {
	  getpts_simple(DEFAULT_UDP_PROBE_PORT_SPEC, SCAN_UDP_PORT, &o.ping_udpprobes, &o.num_ping_udpprobes);
	  assert(o.num_ping_udpprobes > 0);
	}
      }
      else if (*optarg == 'B') {
	o.pingtype = (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK|PINGTYPE_ICMP_PING);
	if (*(optarg + 1) != '\0') {
	  getpts_simple(optarg + 1, SCAN_TCP_PORT, &o.ping_ackprobes, &o.num_ping_ackprobes);
	  if (o.num_ping_ackprobes <= 0) {
	    fatal("Bogus argument to -PB: %s", optarg + 1);
	  }
	}
	if (o.num_ping_ackprobes == 0) {
	  getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &o.ping_ackprobes, &o.num_ping_ackprobes);
	  assert(o.num_ping_ackprobes > 0);
	}
      } else if (*optarg == 'O') {
	o.pingtype |= PINGTYPE_PROTO;
	if (*(optarg + 1) != '\0') {
	  getpts_simple(optarg + 1, SCAN_PROTOCOLS, &o.ping_protoprobes, &o.num_ping_protoprobes);
	  if (o.num_ping_protoprobes <= 0) {
	    fatal("Bogus argument to -PO: %s", optarg + 1);
	  }
	}
	if (o.num_ping_protoprobes == 0) {
	  getpts_simple(DEFAULT_PROTO_PROBE_PORT_SPEC, SCAN_PROTOCOLS, &o.ping_protoprobes, &o.num_ping_protoprobes);
	  assert(o.num_ping_protoprobes > 0);
	}
      } else { 
	fatal("Illegal Argument to -P, use -PN, -PO, -PI, -PB, -PE, -PM, -PP, -PA, -PU, -PT, or -PT80 (or whatever number you want for the TCP probe destination port)"); 
      }
      break;
    case 'p': 
      if (ports || portlist)
	fatal("Only 1 -p option allowed, separate multiple ranges with commas.");
      portlist = strdup(optarg);
      break;
    case 'q': quashargv++; break;
    case 'R': o.resolve_all++; break;
    case 'r': 
      randomize = 0;
      break;
    case 'S': 
      if (o.spoofsource)
	fatal("You can only use the source option once!  Use -D <decoy1> -D <decoy2> etc. for decoys\n");
      if (resolve(optarg, &ss, &sslen, o.af()) == 0) {
	fatal("Failed to resolve/decode supposed %s source address %s. Note that if you are using IPv6, the -6 argument must come before -S", (o.af() == AF_INET)? "IPv4" : "IPv6", optarg);
      }
      o.setSourceSockAddr(&ss, sslen);
      o.spoofsource = 1;
      break;
    case 's': 
      if (!*optarg) {
	error("An option is required for -s, most common are -sT (tcp scan), -sS (SYN scan), -sF (FIN scan), -sU (UDP scan) and -sP (Ping scan)");
	printusage(argv[0], -1);
      }
      p = optarg;
      while(*p) {
	switch(*p) {
	case 'A': o.ackscan = 1; break;
	case 'B':  fatal("No scan type 'B', did you mean bounce scan (-b)?"); break;
#ifndef NOLUA
	case 'C':  o.script = 1; break;
#endif
	case 'F':  o.finscan = 1; break;
	case 'L':  o.listscan = 1; o.pingtype = PINGTYPE_NONE; break;
	case 'M':  o.maimonscan = 1; break;
	case 'N':  o.nullscan = 1; break;
	case 'O':  o.ipprotscan = 1; break;
	case 'P':  o.pingscan = 1; break;
	case 'R':  o.rpcscan = 1; break;
	case 'S':  o.synscan = 1; break;	  
	case 'W':  o.windowscan = 1; break;
	case 'T':  o.connectscan = 1; break;
	case 'V':  o.servicescan = 1; break;
	case 'U':  o.udpscan++; break;
	case 'X':  o.xmasscan++; break;
	default:  error("Scantype %c not supported\n",*p); printusage(argv[0], -1); break;
	}
	p++;
      }
      break;
    case 'T':
      if (*optarg == '0' || (strcasecmp(optarg, "Paranoid") == 0)) {
	o.timing_level = 0;
	o.max_parallelism = 1;
	o.scan_delay = 300000;
	o.setInitialRttTimeout(300000);
      } else if (*optarg == '1' || (strcasecmp(optarg, "Sneaky") == 0)) {
	o.timing_level = 1;
	o.max_parallelism = 1;
	o.scan_delay = 15000;
	o.setInitialRttTimeout(15000);
      } else if (*optarg == '2' || (strcasecmp(optarg, "Polite") == 0)) {
	o.timing_level = 2;
	o.max_parallelism = 1;
	o.scan_delay = 400;
      } else if (*optarg == '3' || (strcasecmp(optarg, "Normal") == 0)) {
      } else if (*optarg == '4' || (strcasecmp(optarg, "Aggressive") == 0)) {
	o.timing_level = 4;
	o.setMinRttTimeout(100);
	o.setMaxRttTimeout(1250);
	o.setInitialRttTimeout(500);
        o.setMaxTCPScanDelay(10);
        o.setMaxRetransmissions(6);
      } else if (*optarg == '5' || (strcasecmp(optarg, "Insane") == 0)) {
	o.timing_level = 5;
	o.setMinRttTimeout(50);
	o.setMaxRttTimeout(300);
	o.setInitialRttTimeout(250);
	o.host_timeout = 900000;
        o.setMaxTCPScanDelay(5);
        o.setMaxRetransmissions(2);
      } else {
	fatal("Unknown timing mode (-T argument).  Use either \"Paranoid\", \"Sneaky\", \"Polite\", \"Normal\", \"Aggressive\", \"Insane\" or a number from 0 (Paranoid) to 5 (Insane)");
      }
      break;
    case 'V': 
      printf("\n%s version %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL); 
      exit(0);
      break;
    case 'v': o.verbose++; break;
    }
  }

#ifdef WIN32
    win_init();
#endif

  tty_init(); // Put the keyboard in raw mode

#if HAVE_SIGNAL
  if (!o.debugging)
    signal(SIGSEGV, sigdie); 
#endif

  // After the arguments are fully processed we now make any of the timing
  // tweaks the user might've specified:
  if (pre_max_parallelism != -1) o.max_parallelism = pre_max_parallelism;
  if (pre_scan_delay != -1) {
    o.scan_delay = pre_scan_delay;
    if (o.scan_delay > o.maxTCPScanDelay()) o.setMaxTCPScanDelay(o.scan_delay);
    if (o.scan_delay > o.maxUDPScanDelay()) o.setMaxUDPScanDelay(o.scan_delay);
    o.max_parallelism = 1;
    if(pre_max_parallelism != -1)
      fatal("You can't use --max-parallelism with --scan-delay.");
  }
  if (pre_max_scan_delay != -1) {
    o.setMaxTCPScanDelay(pre_max_scan_delay);
    o.setMaxUDPScanDelay(pre_max_scan_delay);
  }
  if (pre_init_rtt_timeout != -1) o.setInitialRttTimeout(pre_init_rtt_timeout);
  if (pre_min_rtt_timeout != -1) o.setMinRttTimeout(pre_min_rtt_timeout);
  if (pre_max_rtt_timeout != -1) o.setMaxRttTimeout(pre_max_rtt_timeout);
  if (pre_max_retries != -1) o.setMaxRetransmissions(pre_max_retries);
  if (pre_host_timeout != -1) o.host_timeout = pre_host_timeout;


  if (o.osscan == OS_SCAN_DEFAULT)
    o.reference_FPs = parse_fingerprint_reference_file("nmap-os-db");

  o.ValidateOptions();

  // print ip options
  if((o.debugging || o.packetTrace()) && o.ipoptionslen){
    char buf[256]; // 256 > 5*40
    bintohexstr(buf, sizeof(buf), (char*)o.ipoptions, o.ipoptionslen);
    if(o.ipoptionslen>=8)	// at least one ip address
    log_write(LOG_STDOUT, "Binary ip options to be send:\n%s", buf);
    log_write(LOG_STDOUT, "Parsed ip options to be send:\n%s\n", 
    	print_ip_options(o.ipoptions, o.ipoptionslen));
  }

  /* Open the log files, now that we know whether the user wants them appended
     or overwritten */
  if (normalfilename)
    log_open(LOG_NORMAL, o.append_output, normalfilename);
  if (machinefilename)
    log_open(LOG_MACHINE, o.append_output, machinefilename);
  if (kiddiefilename)
    log_open(LOG_SKID, o.append_output, kiddiefilename);
  if (xmlfilename)
    log_open(LOG_XML, o.append_output, xmlfilename);

  if (!o.interactivemode) {
    char tbuf[128];
    // ISO 8601 date/time -- http://www.cl.cam.ac.uk/~mgk25/iso-time.html 
    if (strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M %Z", tm) <= 0)
      fatal("Unable to properly format time");
    log_write(LOG_STDOUT|LOG_SKID, "\nStarting %s %s ( %s ) at %s\n", NMAP_NAME, NMAP_VERSION, NMAP_URL, tbuf);
    if (o.verbose && tm->tm_mon == 8 && tm->tm_mday == 1) {
      log_write(LOG_STDOUT|LOG_SKID, "Happy %dth Birthday to Nmap, may it live to be %d!\n", tm->tm_year - 97, tm->tm_year + 3 );
    }
    if (iflist) {
      print_iflist();
      exit(0);
    }
  }

 if(o.traceroute && (o.idlescan || o.connectscan)) {
    error("Warning: Traceroute does not support idle or connect scan, disabling...\n");
    o.traceroute = 0;
  }

  if(o.traceroute && !o.isr00t) {
    error("Warning: Traceroute has to be run as root, disabling...\n");
    o.traceroute = 0;
  }


  if ((o.pingscan || o.listscan) && (portlist || o.fastscan))
    fatal("You cannot use -F (fast scan) or -p (explicit port selection) with PING scan or LIST scan");

  if (portlist && o.fastscan)
    fatal("You cannot use -F (fast scan) with -p (explicit port selection) but see --top-ports and --port-ratio to fast scan a range of ports");

  if (o.ipprotscan) {
    if (portlist) ports = getpts(portlist);
    else ports = getpts((char *) (o.fastscan ? "[P:0-]" : "0-"));  // Default protocols to scan
  } else {
    ports = gettoppts(o.topportlevel, portlist);
  }

  if (portlist && !ports)
    fatal("Your port specification string is not parseable");

  if (portlist) {
    free(portlist);
    portlist = NULL;
  }

  // Uncomment the following line to use the common lisp port spec test suite
  //printf("port spec: (%d %d %d)\n", ports->tcp_count, ports->udp_count, ports->prot_count); exit(0);

#ifdef WIN32
  if (o.sendpref & PACKET_SEND_IP) {
	  error("WARNING: raw IP (rather than raw ethernet) packet sending attempted on Windows. This probably won't work.  Consider --send-eth next time.\n");
  }
#endif
  if (spoofmac) {
    u8 mac_data[6];
    int pos = 0; /* Next index of mac_data to fill in */
    char tmphex[3];
    /* A zero means set it all randomly.  Anything that is all digits
       or colons is treated as a prefix, with remaining characters for
       the 6-byte MAC (if any) chosen randomly.  Otherwise, it is
       treated as a vendor string for lookup in nmap-mac-prefixes */
    if (strcmp(spoofmac, "0") == 0) {
      pos = 0;
    } else {
      const char *p = spoofmac;
      while(*p) { 
	if (*p == ':') p++;
	if (isxdigit(*p) && isxdigit(*(p+1))) {
	  if (pos >= 6) fatal("Bogus --spoof-mac value encountered (%s) -- only up to 6 bytes permitted", spoofmac);
	  tmphex[0] = *p; tmphex[1] = *(p+1); tmphex[2] = '\0';
	  mac_data[pos] = (u8) strtol(tmphex, NULL, 16);
	  pos++;
	  p += 2;
	} else break;
      }
      if (*p) {
	/* Failed to parse it as a MAC prefix -- treating as a vendor substring instead */
	if (!MACCorp2Prefix(spoofmac, mac_data))
	  fatal("Could not parse as a prefix nor find as a vendor substring the given --spoof-mac argument: %s.  If you are giving hex digits, there must be an even number of them.", spoofmac);
	pos = 3;
      }
    }
    if (pos < 6) {
      get_random_bytes(mac_data + pos, 6 - pos);
    }
    /* Got the new MAC! */
    const char *vend = MACPrefix2Corp(mac_data);
    log_write(LOG_PLAIN, 
	      "Spoofing MAC address %02X:%02X:%02X:%02X:%02X:%02X (%s)\n",
	      mac_data[0], mac_data[1], mac_data[2], mac_data[3], mac_data[4],
	      mac_data[5], vend? vend : "No registered vendor");
    o.setSpoofMACAddress(mac_data);

    /* If they want to spoof the MAC address, we should at least make
       some effort to actually send raw ethernet frames rather than IP
       packets (which would use the real IP */
    if (o.sendpref != PACKET_SEND_IP_STRONG)
      o.sendpref = PACKET_SEND_ETH_STRONG;
  }

  /* By now, we've got our port lists.  Give the user a warning if no 
   * ports are specified for the type of scan being requested.  Other things
   * (such as OS ident scan) might break cause no ports were specified,  but
   * we've given our warning...
   */
  if ((o.TCPScan()) && ports->tcp_count == 0)
    error("WARNING: a TCP scan type was requested, but no tcp ports were specified.  Skipping this scan type.");
  if (o.UDPScan() && ports->udp_count == 0)
    error("WARNING: UDP scan was requested, but no udp ports were specified.  Skipping this scan type.");
  if (o.ipprotscan && ports->prot_count == 0)
    error("WARNING: protocol scan was requested, but no protocols were specified to be scanned.  Skipping this scan type.");

  /* Set up our array of decoys! */
  if (o.decoyturn == -1) {
    o.decoyturn = (o.numdecoys == 0)?  0 : get_random_uint() % o.numdecoys; 
    o.numdecoys++;
    for(i=o.numdecoys-1; i > o.decoyturn; i--)
      o.decoys[i] = o.decoys[i-1];
  }

  /* We need to find what interface to route through if:
   * --None have been specified AND
   * --We are root and doing tcp ping OR
   * --We are doing a raw sock scan and NOT pinging anyone */
  if (o.af() == AF_INET && o.v4sourceip() && !*o.device) {
    if (ipaddr2devname(o.device, o.v4sourceip()) != 0) {
      fatal("Could not figure out what device to send the packet out on with the source address you gave me!  If you are trying to sp00f your scan, this is normal, just give the -e eth0 or -e ppp0 or whatever.  Otherwise you can still use -e, but I find it kindof fishy.");
    }
  }

  if (o.af() == AF_INET && *o.device && !o.v4sourceip()) {
    struct sockaddr_in tmpsock;
    memset(&tmpsock, 0, sizeof(tmpsock));
    if (devname2ipaddr(o.device, &(tmpsock.sin_addr)) == -1) {
      fatal("I cannot figure out what source address to use for device %s, does it even exist?", o.device);
    }
    tmpsock.sin_family = AF_INET;
#if HAVE_SOCKADDR_SA_LEN
    tmpsock.sin_len = sizeof(tmpsock);
#endif
    o.setSourceSockAddr((struct sockaddr_storage *) &tmpsock, sizeof(tmpsock));
  }


  /* If he wants to bounce off of an FTP site, that site better damn well be reachable! */
  if (o.bouncescan) {
	  if (!inet_pton(AF_INET, ftp.server_name, &ftp.server)) {
      if ((target = gethostbyname(ftp.server_name)))
	memcpy(&ftp.server, target->h_addr_list[0], 4);
      else {
	fatal("Failed to resolve FTP bounce proxy hostname/IP: %s",
		ftp.server_name);
      } 
    }  else if (o.verbose)
      log_write(LOG_STDOUT, "Resolved FTP bounce attack proxy to %s (%s).\n", 
		ftp.server_name, inet_ntoa(ftp.server)); 
  }
  fflush(stdout);
  fflush(stderr);

  timep = time(NULL);
  
  /* Brief info incase they forget what was scanned */
  Strncpy(mytime, ctime(&timep), sizeof(mytime));
  chomp(mytime);
  char *xslfname = o.XSLStyleSheet();
  char xslline[1024];
  if (xslfname) {
    char *p = xml_convert(xslfname);
    Snprintf(xslline, sizeof(xslline), "<?xml-stylesheet href=\"%s\" type=\"text/xsl\"?>\n", p);
    free(p);
  }  else xslline[0] = '\0';
  log_write(LOG_XML, "<?xml version=\"1.0\" ?>\n%s<!-- ", xslline);
  log_write(LOG_NORMAL|LOG_MACHINE, "# ");
  log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML, "%s %s scan initiated %s as: ", NMAP_NAME, NMAP_VERSION, mytime);
  
  for(i=0; i < argc; i++) {
    char *p = xml_convert(fakeargv[i]);
    log_write(LOG_XML,"%s ", p);
    free(p);
    log_write(LOG_NORMAL|LOG_MACHINE,"%s ", fakeargv[i]);
  }
  log_write(LOG_XML, "-->");
  log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML,"\n");  

  log_write(LOG_XML, "<nmaprun scanner=\"nmap\" args=\"");
  for(i=0; i < argc; i++) 
    log_write(LOG_XML, (i == argc-1)? "%s\" " : "%s ", fakeargv[i]);

  log_write(LOG_XML, "start=\"%lu\" startstr=\"%s\" version=\"%s\" xmloutputversion=\"1.02\">\n",
	    (unsigned long) timep, mytime, NMAP_VERSION);

  output_xml_scaninfo_records(ports);

  log_write(LOG_XML, "<verbose level=\"%d\" />\n<debugging level=\"%d\" />\n",
	    o.verbose, o.debugging);

  /* Before we randomize the ports scanned, lets output them to machine 
     parseable output */
  if (o.verbose)
    output_ports_to_machine_parseable_output(ports, o.TCPScan(), o.udpscan, o.ipprotscan);

  /* more fakeargv junk, BTW malloc'ing extra space in argv[0] doesn't work */
  if (quashargv) {
    size_t fakeargvlen = strlen(FAKE_ARGV), argvlen = strlen(argv[0]);
    if (argvlen < fakeargvlen)
      fatal("If you want me to fake your argv, you need to call the program with a longer name.  Try the full pathname, or rename it fyodorssuperdedouperportscanner");
    strncpy(argv[0], FAKE_ARGV, fakeargvlen);
    memset(&argv[0][fakeargvlen], '\0', strlen(&argv[0][fakeargvlen]));
    for(i=1; i < argc; i++)
      memset(argv[i], '\0', strlen(argv[i]));
  }

#if defined(HAVE_SIGNAL) && defined(SIGPIPE)
  signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
			       of it, but we really shouldn't get an unsuspected
			       SIGPIPE */
#endif

  if (o.max_parallelism && (i = max_sd()) && i < o.max_parallelism) {
    error("WARNING:  Your specified max_parallel_sockets of %d, but your system says it might only give us %d.  Trying anyway", o.max_parallelism, i);
  }

  if (o.debugging > 1) log_write(LOG_STDOUT, "The max # of sockets we are using is: %d\n", o.max_parallelism);

  // At this point we should fully know our timing parameters
  if (o.debugging) {
    log_write(LOG_PLAIN, "--------------- Timing report ---------------\n");
    log_write(LOG_PLAIN, "  hostgroups: min %d, max %d\n", o.minHostGroupSz(), o.maxHostGroupSz());
    log_write(LOG_PLAIN, "  rtt-timeouts: init %d, min %d, max %d\n", o.initialRttTimeout(), o.minRttTimeout(), o.maxRttTimeout());
    log_write(LOG_PLAIN, "  max-scan-delay: TCP %d, UDP %d\n", o.maxTCPScanDelay(), o.maxUDPScanDelay());
    log_write(LOG_PLAIN, "  parallelism: min %d, max %d\n", o.min_parallelism, o.max_parallelism);
    log_write(LOG_PLAIN, "  max-retries: %d, host-timeout: %ld\n", o.getMaxRetransmissions(), o.host_timeout);
    log_write(LOG_PLAIN, "  min-rate: %g\n", o.min_packet_send_rate);
    log_write(LOG_PLAIN, "---------------------------------------------\n");
  }

  /* Before we randomize the ports scanned, we must initialize PortList class. */
  if (o.ipprotscan)
    PortList::initializePortMap(IPPROTO_IP,  ports->prots, ports->prot_count);
  if (o.TCPScan())
    PortList::initializePortMap(IPPROTO_TCP, ports->tcp_ports, ports->tcp_count);
  if (o.UDPScan())
    PortList::initializePortMap(IPPROTO_UDP, ports->udp_ports, ports->udp_count);
  
  if  (randomize) {
    if (ports->tcp_count) {
      shortfry(ports->tcp_ports, ports->tcp_count); 
      // move a few more common ports closer to the beginning to speed scan
      random_port_cheat(ports->tcp_ports, ports->tcp_count);
    }
    if (ports->udp_count) 
      shortfry(ports->udp_ports, ports->udp_count); 
    if (ports->prot_count) 
      shortfry(ports->prots, ports->prot_count); 
  }

  /* lets load our exclude list */
  if ((NULL != excludefd) || (NULL != exclude_spec)) {
    exclude_group = load_exclude(excludefd, exclude_spec);

    if (o.debugging > 3)
      dumpExclude(exclude_group);

    if ((FILE *)NULL != excludefd)
      fclose(excludefd);
    if ((char *)NULL != exclude_spec)
      free(exclude_spec);
  }

#ifndef NOLUA
  if(o.scriptupdatedb) {
	script_updatedb();
	// disable warnings
  	o.max_ips_to_scan = o.numhosts_scanned; 
  }
#endif
  
  /* Time to create a hostgroup state object filled with all the requested
     machines. The list is initially empty. It is refilled inside the loop
     whenever it is empty. */
  host_exp_group = (char **) safe_malloc(o.ping_group_sz * sizeof(char *));
  num_host_exp_groups = 0;

  hstate = new HostGroupState(o.ping_group_sz, o.randomize_hosts,
			      host_exp_group, num_host_exp_groups);

  do {
    ideal_scan_group_sz = determineScanGroupSize(o.numhosts_scanned, ports);
    while(Targets.size() < ideal_scan_group_sz) {
      o.current_scantype = HOST_DISCOVERY;
      currenths = nexthost(hstate, exclude_group, ports, o.pingtype);
      if (!currenths) {
	/* Try to refill with any remaining expressions */
	/* First free the old ones */
	for(i=0; i < num_host_exp_groups; i++)
	  free(host_exp_group[i]);
	num_host_exp_groups = 0;
	/* Now grab any new expressions */
	while(num_host_exp_groups < o.ping_group_sz && 
	      (!o.max_ips_to_scan ||  o.max_ips_to_scan > o.numhosts_scanned + num_host_exp_groups) &&
	      (host_spec = grab_next_host_spec(inputfd, argc, fakeargv))) {
	  // For purposes of random scan
	  host_exp_group[num_host_exp_groups++] = strdup(host_spec);
	}
	if (num_host_exp_groups == 0)
	  break;
	delete hstate;
	hstate = new HostGroupState(o.ping_group_sz, o.randomize_hosts,
				    host_exp_group, num_host_exp_groups);
      
	/* Try one last time -- with new expressions */
	currenths = nexthost(hstate, exclude_group, ports, o.pingtype);
	if (!currenths)
	  break;
      }
      o.numhosts_scanned++;
    
      if (currenths->flags & HOST_UP && !o.listscan) 
	o.numhosts_up++;
    
    if ((o.pingscan && !o.traceroute) || o.listscan) {
	/* We're done with the hosts */
	log_write(LOG_XML, "<host>");
	write_host_status(currenths, o.resolve_all);
	printmacinfo(currenths);
	//	if (currenths->flags & HOST_UP)
	//  log_write(LOG_PLAIN,"\n");
	log_write(LOG_XML, "</host>\n");
	log_flush_all();
	delete currenths;
	continue;
      }
    
      if (o.spoofsource) {
	o.SourceSockAddr(&ss, &sslen);
	currenths->setSourceSockAddr(&ss, sslen);
      }
    
      /* I used to check that !currenths->wierd_responses, but in some
	 rare cases, such IPs CAN be port successfully scanned and even connected to */
      if (!(currenths->flags & HOST_UP)) {
	delete currenths;
	continue;
      }

      if (o.af() == AF_INET && o.RawScan()) { 
	if (currenths->SourceSockAddr(NULL, NULL) != 0) {
	  if (o.SourceSockAddr(&ss, &sslen) == 0) {
	    currenths->setSourceSockAddr(&ss, sslen);
	  } else {
	    if (gethostname(myname, MAXHOSTNAMELEN) || 
		resolve(myname, &ss, &sslen, o.af()) == 0)
	      fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n"); 
	    
	    o.setSourceSockAddr(&ss, sslen);
	    currenths->setSourceSockAddr(&ss, sslen);
	    if (! sourceaddrwarning) {
	      error("WARNING:  We could not determine for sure which interface to use, so we are guessing %s .  If this is wrong, use -S <my_IP_address>.", inet_socktop(&ss));
	      sourceaddrwarning = 1;
	    }
	  }
	}

	if (!currenths->deviceName())
	  fatal("Do not have appropriate device name for target");
	
	/* Groups should generally use the same device as properties
	   change quite a bit between devices.  Plus dealing with a
	   multi-device group can be a pain programmatically. So if
	   this Target has a different device the rest, we give it
	   back. */
	if (Targets.size() > 0 && 
	    strcmp(Targets[Targets.size() - 1]->deviceName(), currenths->deviceName())) {
	  returnhost(hstate);
	  o.numhosts_scanned--; o.numhosts_up--;
	  break;
	}
	o.decoys[o.decoyturn] = currenths->v4source();
      }
      Targets.push_back(currenths);
    }
    
    if (Targets.size() == 0)
      break; /* Couldn't find any more targets */
    
    // Set the variable for status printing
    o.numhosts_scanning = Targets.size();
    
    // Our source must be set in decoy list because nexthost() call can
    // change it (that issue really should be fixed when possible)
    if (o.af() == AF_INET && o.RawScan())
      o.decoys[o.decoyturn] = Targets[0]->v4source();
    
    /* ping scan traceroutes */
    if(o.traceroute && o.pingscan) {
        /* Assume that all targets in a group use the same device */
        troute = new Traceroute(Targets[0]->deviceName(), Targets[0]->ifType());
        troute->trace(Targets);
        troute->resolveHops();

        /* print ping traceroutes, making sure the reference
         * trace is first */
        while(!Targets.empty()) {
            currenths = *Targets.begin();
            log_write(LOG_XML, "<host>");
            write_host_status(currenths, o.resolve_all);
            printmacinfo(currenths);
            troute->outputTarget(currenths);
            log_write(LOG_XML, "</host>\n");
            log_write(LOG_PLAIN,"\n");
            delete currenths;
            Targets.erase(Targets.begin());
        }
        o.numhosts_scanning = 0;
        log_flush_all();
        delete troute;
        troute = NULL;
        continue;
    }

    /* I now have the group for scanning in the Targets vector */

    // Ultra_scan sets o.scantype for us so we don't have to worry
    if (o.synscan)
      ultra_scan(Targets, ports, SYN_SCAN);
    
    if (o.ackscan)
      ultra_scan(Targets, ports, ACK_SCAN);
    
    if (o.windowscan)
      ultra_scan(Targets, ports, WINDOW_SCAN);
    
    if (o.finscan)
      ultra_scan(Targets, ports, FIN_SCAN);
    
    if (o.xmasscan)
      ultra_scan(Targets, ports, XMAS_SCAN);
    
    if (o.nullscan)
      ultra_scan(Targets, ports, NULL_SCAN);
    
    if (o.maimonscan)
      ultra_scan(Targets, ports, MAIMON_SCAN);
    
    if (o.udpscan)
      ultra_scan(Targets, ports, UDP_SCAN);
    
    if (o.connectscan)
      ultra_scan(Targets, ports, CONNECT_SCAN);
    
    if (o.ipprotscan)
      ultra_scan(Targets, ports, IPPROT_SCAN);
    
    /* These lame functions can only handle one target at a time */
    for(targetno = 0; targetno < Targets.size(); targetno++) {
      currenths = Targets[targetno];
      if (o.idlescan) {
         o.current_scantype = IDLE_SCAN;
         keyWasPressed(); // Check if a status message should be printed
         idle_scan(currenths, ports->tcp_ports, 
				ports->tcp_count, idleProxy);
      }
      if (o.bouncescan) {
         o.current_scantype = BOUNCE_SCAN;
         keyWasPressed(); // Check if a status message should be printed
	if (ftp.sd <= 0) ftp_anon_connect(&ftp);
	if (ftp.sd > 0) bounce_scan(currenths, ports->tcp_ports, 
				    ports->tcp_count, &ftp);
      }
    }

    if (o.servicescan) {
      o.current_scantype = SERVICE_SCAN; 
#ifndef NOLUA
      o.scriptversion = 1;
#endif

      keyWasPressed(); // Check if a status message should be printed
      service_scan(Targets);
    }

    if (o.osscan == OS_SCAN_DEFAULT)
	  os_scan2(Targets);

    if(o.traceroute) {
        troute = new Traceroute(Targets[0]->deviceName(), Targets[0]->ifType());
        troute->trace(Targets);
        troute->resolveHops();
    }

    for(targetno = 0; targetno < Targets.size(); targetno++) {
      currenths = Targets[targetno];
    
      /* This scantype must be after any TCP or UDP scans since it
       * get's it's port scan list from the open port list of the current
       * host rather than port list the user specified.
       */
      if (o.servicescan || o.rpcscan)  pos_scan(currenths, NULL, 0, RPC_SCAN);
		}
#ifndef NOLUA
    if(o.script || o.scriptversion) {
	    script_scan(Targets);
    }
#endif

    for(targetno = 0; targetno < Targets.size(); targetno++) {
      currenths = Targets[targetno];
    /* Now I can do the output and such for each host */
      log_write(LOG_XML, "<host>");
      write_host_status(currenths, o.resolve_all);
      if (currenths->timedOut(NULL)) {
	log_write(LOG_PLAIN,"Skipping host %s due to host timeout\n", 
		  currenths->NameIP(hostname, sizeof(hostname)));
	log_write(LOG_MACHINE,"Host: %s (%s)\tStatus: Timeout", 
		  currenths->targetipstr(), currenths->HostName());
      } else {
	printportoutput(currenths, &currenths->ports);
	printmacinfo(currenths);
	printosscanoutput(currenths);
	printserviceinfooutput(currenths);
#ifndef NOLUA
	printhostscriptresults(currenths);
#endif
      }
    
    if(troute)
        troute->outputTarget(currenths);

      if (o.debugging) 
	log_write(LOG_STDOUT, "Final times for host: srtt: %d rttvar: %d  to: %d\n", 
		  currenths->to.srtt, currenths->to.rttvar, currenths->to.timeout);
      log_write(LOG_XML, "<times srtt=\"%d\" rttvar=\"%d\" to=\"%d\" />\n",
		currenths->to.srtt, currenths->to.rttvar, currenths->to.timeout);
      log_write(LOG_PLAIN|LOG_MACHINE,"\n");
      log_write(LOG_XML, "</host>\n");
    }
    log_flush_all();
  
    /* Free all of the Targets */
    while(!Targets.empty()) {
      currenths = Targets.back();
      delete currenths;
      Targets.pop_back();
    }
    o.numhosts_scanning = 0;
  } while(!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned);
  
  if(troute)
    delete troute;
 
  delete hstate;
  if (exclude_group)
    delete[] exclude_group;

  hstate = NULL;

  /* Free host expressions */
  for(i=0; i < num_host_exp_groups; i++)
    free(host_exp_group[i]);
  num_host_exp_groups = 0;
  free(host_exp_group);

  printdatafilepaths();

  printfinaloutput();

  free_scan_lists(ports);

  eth_close_cached();

  if(o.release_memory || o.interactivemode) {
    /* Free fake argv */
    for(i=0; i < argc; i++)
      free(fakeargv[i]);
    free(fakeargv);

    nmap_free_mem();
  }
  return 0;
}      
      
// Free some global memory allocations.
// This is used for detecting memory leaks.
void nmap_free_mem() {
  PortList::freePortMap();
  cp_free();
  free_dns_servers();
  free_etchosts();
  if(o.reference_FPs){
    free_fingerprint_file(o.reference_FPs);
    o.reference_FPs = NULL;
  }
  AllProbes::service_scan_free();
  
}

/* Reads in a (normal or machine format) Nmap log file and gathers enough
   state to allow Nmap to continue where it left off.  The important things
   it must gather are:
   1) The last host completed
   2) The command arguments
*/
   
int gather_logfile_resumption_state(char *fname, int *myargc, char ***myargv) {
  char *filestr;
  int filelen;
  char nmap_arg_buffer[1024];
  struct in_addr lastip;
  char *p, *q, *found; /* I love C! */
  /* We mmap it read/write since we will change the last char to a newline if it is not already */
  filestr = mmapfile(fname, &filelen, O_RDWR);
  if (!filestr) {
    fatal("Could not mmap() %s read/write", fname);
  }

  if (filelen < 20) {
    fatal("Output file %s is too short -- no use resuming", fname);
  }

  /* For now we terminate it with a NUL, but we will terminate the file with
     a '\n' later */
  filestr[filelen - 1] = '\0';

  /* First goal is to find the nmap args */
  if ((p = strstr(filestr, " as: ")))
    p += 5;
  else fatal("Unable to parse supposed log file %s.  Are you sure this is an Nmap output file?", fname);
  while(*p && !isspace((int) *p))
    p++;
  if (!*p) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  p++; /* Skip the space between program name and first arg */
  if (*p == '\n' || !*p) fatal("Unable to parse supposed log file %s.  Sorry", fname);

  q = strchr(p, '\n');
  if (!q || ((unsigned int) (q - p) >= sizeof(nmap_arg_buffer) - 32))
    fatal("Unable to parse supposed log file %s.  Perhaps the Nmap execution had not finished at least one host?  In that case there is no use \"resuming\"", fname);


  strcpy(nmap_arg_buffer, "nmap --append-output ");
  if ((q-p) + 21 + 1 >= (int) sizeof(nmap_arg_buffer)) fatal("0verfl0w");
  memcpy(nmap_arg_buffer + 21, p, q-p);
  nmap_arg_buffer[21 + q-p] = '\0';

  if (strstr(nmap_arg_buffer, "--randomize-hosts") != NULL) {
    error("WARNING:  You are attempting to resume a scan which used --randomize-hosts.  Some hosts in the last randomized batch may be missed and others may be repeated once");
  }

  *myargc = arg_parse(nmap_arg_buffer, myargv);
  if (*myargc == -1) {  
    fatal("Unable to parse supposed log file %s.  Sorry", fname);
  }
     
  /* Now it is time to figure out the last IP that was scanned */
  q = p;
  found = NULL;
  /* Lets see if its a machine log first */
  while((q = strstr(q, "\nHost: ")))
    found = q = q + 7;

  if (found) {
    q = strchr(found, ' ');
    if (!q) fatal("Unable to parse supposed log file %s.  Sorry", fname);
    *q = '\0';
    if (inet_pton(AF_INET, found, &lastip) == 0)
      fatal("Unable to parse supposed log file %s.  Sorry", fname);
    *q = ' ';
  } else {
    /* OK, I guess (hope) it is a normal log then */
    q = p;
    found = NULL;
    while((q = strstr(q, "\nInteresting ports on ")))
      found = q++;

    /* There may be some later IPs of the form 'All [num] scanned ports on  ([ip]) are: state */
    if (found) q = found;
    if (q) {    
      while((q = strstr(q, "\nAll "))) {
	q+= 5;
	while(isdigit(*q)) q++;
	if (strncmp(q, " scanned ports on", 17) == 0)
	  found = q;
      }
    }

    if (found) {    
      found = strchr(found, '(');
      if (!found) fatal("Unable to parse supposed log file %s.  Sorry", fname);
      found++;
      q = strchr(found, ')');
      if (!q) fatal("Unable to parse supposed log file %s.  Sorry", fname);
      *q = '\0';
      if (inet_pton(AF_INET, found, &lastip) == 0)
	fatal("Unable to parse ip (%s) supposed log file %s.  Sorry", found, fname);
      *q = ')';
    } else {
      error("Warning: You asked for --resume but it doesn't look like any hosts in the log file were successfully scanned.  Starting from the beginning.");
      lastip.s_addr = 0;
    }
  }
  o.resume_ip = lastip;

  /* Ensure the log file ends with a newline */
  filestr[filelen - 1] = '\n';
  munmap(filestr, filelen);
  return 0;
}

/* We set the socket lingering so we will RST connection instead of wasting
   bandwidth with the four step close  */
void init_socket(int sd) {
  struct linger l;
  int res;
  static int bind_failed=0;
  struct sockaddr_storage ss;
  size_t sslen;

  l.l_onoff = 1;
  l.l_linger = 0;

  if (setsockopt(sd, SOL_SOCKET, SO_LINGER,  (const char *) &l, sizeof(struct linger)))
    {
      error("Problem setting socket SO_LINGER, errno: %d", socket_errno());
      perror("setsockopt");
    }
  if (o.spoofsource && !bind_failed)
    {
      o.SourceSockAddr(&ss, &sslen);
      res=bind(sd, (struct sockaddr*)&ss, sslen);
      if (res<0)
	{
	  error("init_socket: Problem binding source address (%s), errno :%d", inet_socktop(&ss), socket_errno());
	  perror("bind");
	  bind_failed=1;
	}
    }
}



/* Convert a string like "-100,n*tp,200-1024,3000-4000,[60000-]" into an array
 * of port numbers. Note that one trailing comma is OK -- this is actually
 * useful for machine generated lists
 *
 * Fyodor - Wrote original
 * William McVey - Added T:, U:, P: directives
 * Doug Hoyte - Added [], name lookups, and wildcard expansion
 *
 * getpts() handles []
 * Any port ranges included inside square brackets will have all
 * their ports looked up in nmap-services or nmap-protocols
 * and will only be included if they are found.
 * Returns a scan_list* with all the ports that should be scanned.
 *
 * getpts() handles service/protocol name lookups and wildcard expansion.
 * The service name can be specified instead of the port number.
 * For example, "ssh" can be used instead of "22". You can use wildcards
 * like "*" and "?". See the function wildtest() for the exact details.
 * For example,
 *
 * nmap -p http* host
 *
 * Will scan http (80), http-mgmt (280), http-proxy (8080), https (443), etc.
 *
 * Matching is case INsensitive but the first character in a match MUST
 * be lowercase so it doesn't conflict with the T:, U:, and P: directives.
 *
 * getpts() is unable to match service names that start with a digit
 * like 3com-tsmux (106/udp). Use a pattern like "?com-*" instead.
 *
 * BE CAREFUL ABOUT SHELL EXPANSIONS!!!
 * If you are trying to match the services nmsp (537/tcp) and nms (1429/tcp)
 * and you execute the command
 *
 * ./nmap -p nm* host
 *
 * You will see
 *
 * Found no matches for the service mask 'nmap' and your specified protocols
 * QUITTING!
 *
 * This is because nm* was expanded to the name of the binary file nmap in
 * the current directory by your shell. When unsure, quote your port strings
 * to be safe:
 *
 * ./nmap -p 'nm*' host
 *
 * getpts() is smart enough to keep the T: U: and P: directives nested
 * and working in a logical manner. For instance,
 *
 * nmap -sTU -p [U:1025-],1-1024 host
 *
 * Will scan UDP ports 1025 and up that are found in the service file
 * and all TCP/UDP ports below <= 1024. Notice that the U doesn't affect
 * the outer part of the port expression. It's "closed".
 */

static void getpts_aux(const char *origexpr, int nested, u8 *porttbl, int range_type,
                       int *portwarning, bool change_range_type = true);

struct scan_lists *getpts(const char *origexpr) {
  u8 *porttbl;
  struct scan_lists *ports;
  int range_type = 0;
  int portwarning = 0;
  int i, tcpi, udpi, proti;

  if (o.TCPScan())
    range_type |= SCAN_TCP_PORT;
  if (o.UDPScan())
    range_type |= SCAN_UDP_PORT;
  if (o.ipprotscan)
    range_type |= SCAN_PROTOCOLS;

  porttbl = (u8 *) safe_zalloc(65536);
  ports = (struct scan_lists *) safe_zalloc(sizeof(struct scan_lists));

  getpts_aux(origexpr,      // Pass on the expression
             0,             // Don't start off nested
             porttbl,       // Our allocated port table
             range_type,    // Defaults to TCP/UDP/Protos
             &portwarning); // No, we haven't warned them about dup ports yet

  ports->tcp_count = 0;
  ports->udp_count = 0;
  ports->prot_count = 0;
  for(i = 0; i <= 65535; i++) {
    if (porttbl[i] & SCAN_TCP_PORT)
      ports->tcp_count++;
    if (porttbl[i] & SCAN_UDP_PORT)
      ports->udp_count++;
    if (porttbl[i] & SCAN_PROTOCOLS && i < 256)
      ports->prot_count++;
  }

  if (range_type != 0 && 0 == (ports->tcp_count + ports->udp_count + ports->prot_count))
    fatal("No ports specified -- If you really don't want to scan any ports use ping scan...");

  if (ports->tcp_count) {
    ports->tcp_ports = (unsigned short *)safe_zalloc(ports->tcp_count * sizeof(unsigned short));
  }
  if (ports->udp_count) {
    ports->udp_ports = (unsigned short *)safe_zalloc(ports->udp_count * sizeof(unsigned short));
  }
  if (ports->prot_count) {
    ports->prots = (unsigned short *)safe_zalloc(ports->prot_count * sizeof(unsigned short));
  }

  for(i=tcpi=udpi=proti=0; i <= 65535; i++) {
    if (porttbl[i] & SCAN_TCP_PORT)
      ports->tcp_ports[tcpi++] = i;
    if (porttbl[i] & SCAN_UDP_PORT)
      ports->udp_ports[udpi++] = i;
    if (porttbl[i] & SCAN_PROTOCOLS && i < 256)
      ports->prots[proti++] = i;
  }

  free(porttbl);

  return ports;

}

/* This function is like getpts except that instead of returning several lists
   of ports in a struct scan_lists, it allocates only one list and stores it in
   the list and count arguments. For that reason, T:, U:, and P: restrictions
   are not allowed and only one bit in range_type may be set. */
void getpts_simple(const char *origexpr, int range_type,
                   unsigned short **list, int *count) {
  u8 *porttbl;
  int portwarning = 0;
  int i, j;

  /* Make sure that only one bit in range_type is set (or that range_type is 0,
     which is useless but not incorrect). */
  assert((range_type & (range_type - 1)) == 0);

  porttbl = (u8 *) safe_zalloc(65536);

  /* Get the ports but do not allow changing the type with T:, U:, or P:. */
  getpts_aux(origexpr, 0, porttbl, range_type, &portwarning, false);

  /* Count how many are set. */
  *count = 0;
  for (i = 0; i <= 65535; i++) {
    if (porttbl[i] & range_type)
      (*count)++;
  }

  if (*count == 0)
    return;

  *list = (unsigned short *) safe_zalloc(*count * sizeof(unsigned short));

  /* Fill in the list. */
  for (i = 0, j = 0; i <= 65535; i++) {
    if (porttbl[i] & range_type)
      (*list)[j++] = i;
  }

  free(porttbl);
}

/* getpts() and getpts_simple() (see above) are wrappers for this function */

static void getpts_aux(const char *origexpr, int nested, u8 *porttbl, int range_type, int *portwarning, bool change_range_type) {
  long rangestart = -2343242, rangeend = -9324423;
  const char *current_range;
  char *endptr;
  char servmask[128];  // A protocol name can be up to 127 chars + nul byte
  int i;

  /* An example of proper syntax to use in error messages. */
  const char *syntax_example;
  if (change_range_type)
    syntax_example = "-100,200-1024,T:3000-4000,U:60000-";
  else
    syntax_example = "-100,200-1024,3000-4000,60000-";

  current_range = origexpr;
  do {
    while(isspace((int) *current_range))
      current_range++; /* I don't know why I should allow spaces here, but I will */

    if (change_range_type) {
      if (*current_range == 'T' && *++current_range == ':') {
          current_range++;
          range_type = SCAN_TCP_PORT;
          continue;
      }
      if (*current_range == 'U' && *++current_range == ':') {
          current_range++;
          range_type = SCAN_UDP_PORT;
          continue;
      }
      if (*current_range == 'P' && *++current_range == ':') {
          current_range++;
          range_type = SCAN_PROTOCOLS;
          continue;
      }
    }

    if (*current_range == '[') {
      if (nested)
        fatal("Can't nest [] brackets in port/protocol specification");

      getpts_aux(++current_range, 1, porttbl, range_type, portwarning);

      // Skip past the ']'. This is OK because we can't nest []s
      while(*current_range != ']') current_range++;
      current_range++;

      // Skip over a following ',' so we're ready to keep parsing
      if (*current_range == ',') current_range++;

      continue;
    } else if (*current_range == ']') {
      if (!nested)
        fatal("Unexpected ] character in port/protocol specification");

      return;
    } else if (*current_range == '-') {
      if (range_type & SCAN_PROTOCOLS)
        rangestart = 0;
      else
        rangestart = 1;
    }
    else if (isdigit((int) *current_range)) {
      rangestart = strtol(current_range, &endptr, 10);
      if (range_type & SCAN_PROTOCOLS) {
        if (rangestart < 0 || rangestart > 255)
	  fatal("Protocols to be scanned must be between 0 and 255 inclusive");
      } else {
        if (rangestart < 0 || rangestart > 65535)
	  fatal("Ports to be scanned must be between 0 and 65535 inclusive");
      }
      current_range = endptr;
      while(isspace((int) *current_range)) current_range++;
    } else if (islower((int) *current_range) || *current_range == '*' || *current_range == '?') {
      i = 0;

      while (*current_range && !isspace((int)*current_range) && *current_range != ',' && *current_range != ']') {
        servmask[i++] = *(current_range++);
        if (i >= ((int)sizeof(servmask)-1))
          fatal("A service mask in the port/protocol specification is either malformed or too long");
      }

      if (*current_range && *current_range != ']') current_range++; // We want the '] character to be picked up on the next pass
      servmask[i] = '\0'; // Finish the string

      i = addportsfromservmask(servmask, porttbl, range_type);
      if (range_type & SCAN_PROTOCOLS) i += addprotocolsfromservmask(servmask, porttbl);

      if (i == 0)
        fatal("Found no matches for the service mask '%s' and your specified protocols", servmask);

      continue;

    } else {
      fatal("Error #485: Your port specifications are illegal.  Example of proper form: \"%s\"", syntax_example);
    }
    /* Now I have a rangestart, time to go after rangeend */
    if (!*current_range || *current_range == ',' || *current_range == ']') {
      /* Single port specification */
      rangeend = rangestart;
    } else if (*current_range == '-') {
      current_range++;
      if (!*current_range || *current_range == ',' || *current_range == ']') {
	/* Ended with a -, meaning up until the last possible port */
        if (range_type & SCAN_PROTOCOLS)
          rangeend = 255;
        else
          rangeend = 65535;
      } else if (isdigit((int) *current_range)) {
	rangeend = strtol(current_range, &endptr, 10);
        if (range_type & SCAN_PROTOCOLS) {
	  if (rangeend < 0 || rangeend > 255)
	    fatal("Protocols to be scanned must be between 0 and 255 inclusive");
	} else {
	  if (rangeend < 0 || rangeend > 65535)
	    fatal("Ports to be scanned must be between 0 and 65535 inclusive");
	}
	current_range = endptr;
      } else {
	fatal("Error #486: Your port specifications are illegal.  Example of proper form: \"%s\"", syntax_example);
      }
    } else {
	fatal("Error #487: Your port specifications are illegal.  Example of proper form: \"%s\"", syntax_example);
    }

    /* Now I have a rangestart and a rangeend, so I can add these ports */
    while(rangestart <= rangeend) {
      if (porttbl[rangestart] & range_type) {
        if (!(*portwarning)) {
	  error("WARNING:  Duplicate port number(s) specified.  Are you alert enough to be using Nmap?  Have some coffee or Jolt(tm).");
          (*portwarning)++;
	} 
      } else {      
        if (nested) {
          if ((range_type & SCAN_TCP_PORT) &&
              nmap_getservbyport(htons(rangestart), "tcp")) {
            porttbl[rangestart] |= SCAN_TCP_PORT;
          }
          if ((range_type & SCAN_UDP_PORT) &&
              nmap_getservbyport(htons(rangestart), "udp")) {
            porttbl[rangestart] |= SCAN_UDP_PORT;
          }
          if ((range_type & SCAN_PROTOCOLS) &&
              nmap_getprotbynum(htons(rangestart))) {
            porttbl[rangestart] |= SCAN_PROTOCOLS;
          }
        } else {
          porttbl[rangestart] |= range_type;
        }
      }
      rangestart++;
    }
    
    /* Find the next range */
    while(isspace((int) *current_range)) current_range++;

    if (*current_range == ']') return;

    if (*current_range && *current_range != ',') {
      fatal("Error #488: Your port specifications are illegal.  Example of proper form: \"%s\"", syntax_example);
    }
    if (*current_range == ',')
      current_range++;
  } while(current_range && *current_range);

}

void free_scan_lists(struct scan_lists *ports) {
  if (ports) {
    if (ports->tcp_ports) free(ports->tcp_ports);
    if (ports->udp_ports) free(ports->udp_ports);
    if (ports->prots) free(ports->prots);
    free(ports);
  }
}

void printinteractiveusage() {
  printf(
	 "Nmap Interactive Commands:\n\
n <nmap args> -- executes an nmap scan using the arguments given and\n\
waits for nmap to finish.  Results are printed to the\n\
screen (of course you can still use file output commands).\n\
! <command>   -- runs shell command given in the foreground\n\
x             -- Exit Nmap\n\
f [--spoof <fakeargs>] [--nmap-path <path>] <nmap args>\n\
-- Executes nmap in the background (results are NOT\n\
printed to the screen).  You should generally specify a\n\
file for results (with -oX, -oG, or -oN).  If you specify\n\
fakeargs with --spoof, Nmap will try to make those\n\
appear in ps listings.  If you wish to execute a special\n\
version of Nmap, specify --nmap-path.\n\
n -h          -- Obtain help with Nmap syntax\n\
h             -- Prints this help screen.\n\
Examples:\n\
n -sS -O -v example.com/24\n\
f --spoof \"/usr/local/bin/pico -z hello.c\" -sS -oN e.log example.com/24\n\n");
}

char *seqreport(struct seq_info *seq) {
  static char report[512];

  Snprintf(report, sizeof(report), "TCP Sequence Prediction: Difficulty=%d (%s)\n", seq->index, seqidx2difficultystr(seq->index));
  return report;
}

/* Convert a TCP sequence prediction difficulty index like 1264386
   into a difficulty string like "Worthy Challenge */
const char *seqidx2difficultystr(unsigned long idx) {
  return  (idx < 3)? "Trivial joke" : (idx < 6)? "Easy" : (idx < 11)? "Medium" : (idx < 12)? "Formidable" : (idx < 16)? "Worthy challenge" : "Good luck!";
}

const char *ipidclass2ascii(int seqclass) {
  switch(seqclass) {
  case IPID_SEQ_CONSTANT:
    return "Duplicated ipid (!)";
  case IPID_SEQ_INCR:
    return "Incremental";
  case IPID_SEQ_BROKEN_INCR:
    return "Broken little-endian incremental";
  case IPID_SEQ_RD:
    return "Randomized";
  case IPID_SEQ_RPI:
    return "Random positive increments";
  case IPID_SEQ_ZERO:
    return "All zeros";
  case IPID_SEQ_UNKNOWN:
    return "Busy server or unknown class";
  default:
    return "ERROR, WTF?";
  }
}

const char *tsseqclass2ascii(int seqclass) {
  switch(seqclass) {
  case TS_SEQ_ZERO:
    return "zero timestamp";
  case TS_SEQ_2HZ:
    return "2HZ";
  case TS_SEQ_100HZ:
    return "100HZ";
  case TS_SEQ_1000HZ:
    return "1000HZ";
  case TS_SEQ_OTHER_NUM:
    return "other";
  case TS_SEQ_UNSUPPORTED:
    return "none returned (unsupported)";
  case TS_SEQ_UNKNOWN:
    return "unknown class";
  default:
    return "ERROR, WTF?";
  }
}




/* Just a routine for obtaining a string for printing based on the scantype */
const char *scantype2str(stype scantype) {

  switch(scantype) {
  case STYPE_UNKNOWN: return "Unknown Scan Type"; break;
  case HOST_DISCOVERY: return "Host Discovery"; break;
  case ACK_SCAN: return "ACK Scan"; break;
  case SYN_SCAN: return "SYN Stealth Scan"; break;
  case FIN_SCAN: return "FIN Scan"; break;
  case XMAS_SCAN: return "XMAS Scan"; break;
  case UDP_SCAN: return "UDP Scan"; break;
  case CONNECT_SCAN: return "Connect Scan"; break;
  case NULL_SCAN: return "NULL Scan"; break;
  case WINDOW_SCAN: return "Window Scan"; break;
  case RPC_SCAN: return "RPCGrind Scan"; break;
  case MAIMON_SCAN: return "Maimon Scan"; break;
  case IPPROT_SCAN: return "IPProto Scan"; break;
  case PING_SCAN: return "Ping Scan"; break;
  case PING_SCAN_ARP: return "ARP Ping Scan"; break;
  case IDLE_SCAN: return "Idle Scan"; break;
  case BOUNCE_SCAN: return "Bounce Scan"; break;
  case SERVICE_SCAN: return "Service Scan"; break;
  case OS_SCAN: return "OS Scan"; break;
  case SCRIPT_SCAN: return "Script Scan"; break;
  case TRACEROUTE: return "Traceroute" ; break;
  case REF_TRACEROUTE: return "Reference Traceroute"; break;
  default: assert(0); break;
  }

  return NULL; /* Unreached */

}

const char *statenum2str(int state) {
  switch(state) {
  case PORT_OPEN: return "open"; break;
  case PORT_FILTERED: return "filtered"; break;
  case PORT_UNFILTERED: return "unfiltered"; break;
  case PORT_CLOSED: return "closed"; break;
  case PORT_OPENFILTERED: return "open|filtered"; break;
  case PORT_CLOSEDFILTERED: return "closed|filtered"; break;
  default: return "unknown"; break;
  }
  return "unknown";
}

int ftp_anon_connect(struct ftpinfo *ftp) {
  int sd;
  struct sockaddr_in sock;
  int res;
  char recvbuf[2048];
  char command[512];

  if (o.verbose || o.debugging) 
    log_write(LOG_STDOUT, "Attempting connection to ftp://%s:%s@%s:%i\n", ftp->user, ftp->pass,
	      ftp->server_name, ftp->port);

  if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    gh_perror("Couldn't create %s socket", __func__);
    return 0;
  }

  sock.sin_family = AF_INET;
  sock.sin_addr.s_addr = ftp->server.s_addr;
  sock.sin_port = htons(ftp->port); 
  res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  if (res < 0 ) {
    fatal("Your FTP bounce proxy server won't talk to us!");
  }
  if (o.verbose || o.debugging) log_write(LOG_STDOUT, "Connected:");
  while ((res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,7, NULL)) > 0) 
    if (o.debugging || o.verbose) {
      recvbuf[res] = '\0';
      log_write(LOG_STDOUT, "%s", recvbuf);
    }
  if (res < 0) {
    pfatal("recv problem from FTP bounce server");
  }

  Snprintf(command, 511, "USER %s\r\n", ftp->user);

  send(sd, command, strlen(command), 0);
  res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,12, NULL);
  if (res <= 0) {
    pfatal("recv problem from FTP bounce server");
  }
  recvbuf[res] = '\0';
  if (o.debugging) log_write(LOG_STDOUT, "sent username, received: %s", recvbuf);
  if (recvbuf[0] == '5') {
    fatal("Your FTP bounce server doesn't like the username \"%s\"", ftp->user);
  }

  Snprintf(command, 511, "PASS %s\r\n", ftp->pass);

  send(sd, command, strlen(command), 0);
  res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,12, NULL);
  if (res < 0) {
    pfatal("recv problem from FTP bounce server");
  }
  if (!res) error("Timeout from bounce server ...");
  else {
    recvbuf[res] = '\0';
    if (o.debugging) log_write(LOG_STDOUT, "sent password, received: %s", recvbuf);
    if (recvbuf[0] == '5') {
      fatal("Your FTP bounce server refused login combo (%s/%s)",
	      ftp->user, ftp->pass);
    }
  }
  while ((res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,2, NULL)) > 0) 
    if (o.debugging) {
      recvbuf[res] = '\0';
      log_write(LOG_STDOUT, "%s", recvbuf);
    }
  if (res < 0) {
    pfatal("recv problem from FTP bounce server");
  }
  if (o.verbose) log_write(LOG_STDOUT, "Login credentials accepted by FTP server!\n");

  ftp->sd = sd;
  return sd;
}

#ifndef WIN32

void reaper(int signo) {
  int status;
  pid_t pid;

  if ((pid = wait(&status)) == -1) {
    gh_perror("waiting to reap child");
  } else {
    fprintf(stderr, "\n[%d finished status=%d (%s)]\nnmap> ", (int) pid, status, (status == 0)? "success"  : "failure");
  }
}
#endif

void sigdie(int signo) {
  int abt = 0;

  fflush(stdout);

  switch(signo) {
  case SIGINT:
    error("caught SIGINT signal, cleaning up");
    break;

#ifdef SIGTERM
  case SIGTERM:
    error("caught SIGTERM signal, cleaning up");
    break;
#endif

#ifdef SIGHUP
  case SIGHUP:
    error("caught SIGHUP signal, cleaning up");
    break;
#endif

#ifdef SIGSEGV
  case SIGSEGV:
    error("caught SIGSEGV signal, cleaning up");
    abt = 1;
    break;
#endif

#ifdef SIGBUS
  case SIGBUS:
    error("caught SIGBUS signal, cleaning up");
    abt = 1;
    break;
#endif

  default:
    error("caught signal %d, cleaning up", signo);
    abt = 1;
    break;
  }

  fflush(stderr);
  log_close(LOG_MACHINE|LOG_NORMAL|LOG_SKID);
  if (abt) abort();
  exit(1);
}

/* Returns one if the file pathname given exists, is not a directory and
 * is readable by the executing process.  Returns two if it is readable
 * and is a directory.  Otherwise returns 0.
 */

int fileexistsandisreadable(char *pathname) {
	char *pathname_buf = strdup(pathname);
	int status = 0;

#ifdef WIN32
	// stat on windows only works for "dir_name" not for "dir_name/" or "dir_name\\"
	int pathname_len = strlen(pathname_buf);
	char last_char = pathname_buf[pathname_len - 1];

	if(	last_char == '/'
		|| last_char == '\\')
		pathname_buf[pathname_len - 1] = '\0';

#endif

  struct stat st;

  if (stat(pathname_buf, &st) == -1)
    status = 0;
  else if (access(pathname_buf, R_OK) != -1)
    status = S_ISDIR(st.st_mode) ? 2 : 1;

  free(pathname_buf);
  return status;
}

int nmap_fileexistsandisreadable(char* pathname) {
	return fileexistsandisreadable(pathname);
}

int nmap_fetchfile(char *filename_returned, int bufferlen, const char *file) {
  char *dirptr;
  int res;
  int foundsomething = 0;
  struct passwd *pw;
  char dot_buffer[512];
  static int warningcount = 0;
  std::map<std::string, std::string>::iterator iter;

  /* First, check the map of requested data file names. If there's an entry for
     file, use it and return.
     Otherwise, we try [--datadir]/file, then $NMAPDIR/file
     next we try ~user/nmap/file
     then we try NMAPDATADIR/file <--NMAPDATADIR 
     finally we try ./file

	 -- or on Windows --

	 --datadir -> $NMAPDIR -> nmap.exe directory -> NMAPDATADIR -> .
  */

  /* Check the map of requested data file names. */
  iter = o.requested_data_files.find(file);
  if (iter != o.requested_data_files.end()) {
    Strncpy(filename_returned, iter->second.c_str(), bufferlen);
    /* If a special file name was requested, we must not return any other file
       name. Return a positive result even if the file doesn't exist or is not
       readable. It is the caller's responsibility to report the error if the
       file can't be accessed. */
    return fileexistsandisreadable(filename_returned) || 1;
  }

  if (o.datadir) {
    res = Snprintf(filename_returned, bufferlen, "%s/%s", o.datadir, file);
    if (res > 0 && res < bufferlen) {
      foundsomething = fileexistsandisreadable(filename_returned);
    }
  }

  if (!foundsomething && (dirptr = getenv("NMAPDIR"))) {
    res = Snprintf(filename_returned, bufferlen, "%s/%s", dirptr, file);
    if (res > 0 && res < bufferlen) {
      foundsomething = fileexistsandisreadable(filename_returned);
    }
  }
#ifndef WIN32
  if (!foundsomething) {
    pw = getpwuid(getuid());
    if (pw) {
      res = Snprintf(filename_returned, bufferlen, "%s/.nmap/%s", pw->pw_dir, file);
      if (res > 0 && res < bufferlen) {
        foundsomething = fileexistsandisreadable(filename_returned);
      }
    }
    if (!foundsomething && getuid() != geteuid()) {
      pw = getpwuid(geteuid());
      if (pw) {
	res = Snprintf(filename_returned, bufferlen, "%s/.nmap/%s", pw->pw_dir, file);
	if (res > 0 && res < bufferlen) {
          foundsomething = fileexistsandisreadable(filename_returned);
	}
      }
    }
  }

  /* Check also in libexec because architecture dependent files ought not to
   * be installed in /usr/share
   */

  if (!foundsomething) {
    res = Snprintf(filename_returned, bufferlen, "%s/%s", NMAPLIBEXECDIR, file);
    if (res > 0 && res < bufferlen) {
      foundsomething = fileexistsandisreadable(filename_returned);
    }
  }
#else
  if (!foundsomething) { /* Try the nMap directory */
	  char fnbuf[MAX_PATH];
	  int i;
	  res = GetModuleFileName(GetModuleHandle(0), fnbuf, 1024);
      if(!res) fatal("GetModuleFileName failed (!)\n");
	  /*	Strip it */
	  for(i = res - 1; i >= 0 && fnbuf[i] != '/' && fnbuf[i] != '\\'; i--);
	  if(i >= 0) /* we found it */
		  fnbuf[i] = 0;
	  res = Snprintf(filename_returned, bufferlen, "%s\\%s", fnbuf, file);
	  if(res > 0 && res < bufferlen) {
		  foundsomething = fileexistsandisreadable(filename_returned);
      }
  }
#endif
  if (!foundsomething) {
    res = Snprintf(filename_returned, bufferlen, "%s/%s", NMAPDATADIR, file);
    if (res > 0 && res < bufferlen) {
      foundsomething = fileexistsandisreadable(filename_returned);
    }
  }

  if (foundsomething && (*filename_returned != '.')) {    
    res = Snprintf(dot_buffer, sizeof(dot_buffer), "./%s", file);
    if (res > 0 && res < bufferlen) {
      if (fileexistsandisreadable(dot_buffer)) {
#ifdef WIN32
	if (warningcount++ < 1 && o.debugging)
#else
	if(warningcount++ < 1)
#endif
	  error("Warning: File %s exists, but Nmap is using %s for security and consistency reasons.  set NMAPDIR=. to give priority to files in your local directory (may affect the other data files too).", dot_buffer, filename_returned);
      }
    }
  }

  if (!foundsomething) {
    res = Snprintf(filename_returned, bufferlen, "./%s", file);
    if (res > 0 && res < bufferlen) {
      foundsomething = fileexistsandisreadable(filename_returned);
    }
  }

  if (!foundsomething) {
    filename_returned[0] = '\0';
  }

  if (foundsomething && o.debugging > 1)
    error("Fetchfile found %s", filename_returned);

  return foundsomething;

}