"Fossies" - the Fresh Open Source Software Archive

Member "nmap-7.91/nmap.cc" (9 Oct 2020, 111738 Bytes) of package /linux/misc/nmap-7.91.tgz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "nmap.cc" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 7.90_vs_7.91.

    1 /***************************************************************************
    2  * nmap.cc -- Currently handles some of Nmap's port scanning features as   *
    3  * well as the command line user interface.  Note that the actual main()   *
    4  * function is in main.cc                                                  *
    5  *                                                                         *
    6  ***********************IMPORTANT NMAP LICENSE TERMS************************
    7  *                                                                         *
    8  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
    9  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
   10  *                                                                         *
   11  * This program is distributed under the terms of the Nmap Public Source   *
   12  * License (NPSL). The exact license text applying to a particular Nmap    *
   13  * release or source code control revision is contained in the LICENSE     *
   14  * file distributed with that version of Nmap or source code control       *
   15  * revision. More Nmap copyright/legal information is available from       *
   16  * https://nmap.org/book/man-legal.html, and further information on the    *
   17  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
   18  * summarizes some key points from the Nmap license, but is no substitute  *
   19  * for the actual license text.                                            *
   20  *                                                                         *
   21  * Nmap is generally free for end users to download and use themselves,    *
   22  * including commercial use. It is available from https://nmap.org.        *
   23  *                                                                         *
   24  * The Nmap license generally prohibits companies from using and           *
   25  * redistributing Nmap in commercial products, but we sell a special Nmap  *
   26  * OEM Edition with a more permissive license and special features for     *
   27  * this purpose. See https://nmap.org/oem                                  *
   28  *                                                                         *
   29  * If you have received a written Nmap license agreement or contract       *
   30  * stating terms other than these (such as an Nmap OEM license), you may   *
   31  * choose to use and redistribute Nmap under those terms instead.          *
   32  *                                                                         *
   33  * The official Nmap Windows builds include the Npcap software             *
   34  * (https://npcap.org) for packet capture and transmission. It is under    *
   35  * separate license terms which forbid redistribution without special      *
   36  * permission. So the official Nmap Windows builds may not be              *
   37  * redistributed without special permission (such as an Nmap OEM           *
   38  * license).                                                               *
   39  *                                                                         *
   40  * Source is provided to this software because we believe users have a     *
   41  * right to know exactly what a program is going to do before they run it. *
   42  * This also allows you to audit the software for security holes.          *
   43  *                                                                         *
   44  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
   45  * and add new features.  You are highly encouraged to submit your         *
   46  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
   47  * for possible incorporation into the main distribution. Unless you       *
   48  * specify otherwise, it is understood that you are offering us very       *
   49  * broad rights to use your submissions as described in the Nmap Public    *
   50  * Source License Contributor Agreement. This is important because we      *
   51  * fund the project by selling licenses with various terms, and also       *
   52  * because the inability to relicense code has caused devastating          *
   53  * problems for other Free Software projects (such as KDE and NASM).       *
   54  *                                                                         *
   55  * The free version of Nmap is distributed in the hope that it will be     *
   56  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
   57  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
   58  * indemnification and commercial support are all available through the    *
   59  * Npcap OEM program--see https://nmap.org/oem.                            *
   60  *                                                                         *
   61  ***************************************************************************/
   62 
   63 /* $Id: nmap.cc 38096 2020-10-09 22:18:58Z dmiller $ */
   64 
   65 #ifdef WIN32
   66 #include "winfix.h"
   67 /* This name collides in the following include. */
   68 #undef PS_NONE
   69 #include <shlobj.h>
   70 #endif
   71 
   72 #include "nmap.h"
   73 #include "osscan.h"
   74 #include "scan_engine.h"
   75 #include "FPEngine.h"
   76 #include "idle_scan.h"
   77 #include "NmapOps.h"
   78 #include "MACLookup.h"
   79 #include "traceroute.h"
   80 #include "nmap_tty.h"
   81 #include "nmap_ftp.h"
   82 #include "services.h"
   83 #include "targets.h"
   84 #include "tcpip.h"
   85 #include "NewTargets.h"
   86 #include "Target.h"
   87 #include "service_scan.h"
   88 #include "charpool.h"
   89 #include "nmap_error.h"
   90 #include "utils.h"
   91 #include "xml.h"
   92 #include "scan_lists.h"
   93 
   94 #ifndef NOLUA
   95 #include "nse_main.h"
   96 #endif
   97 
   98 #ifdef HAVE_SIGNAL
   99 #include <signal.h>
  100 #endif
  101 
  102 #include <fcntl.h>
  103 
  104 #ifdef HAVE_PWD_H
  105 #include <pwd.h>
  106 #endif
  107 
  108 #ifndef IPPROTO_SCTP
  109 #include "libnetutil/netutil.h"
  110 #endif
  111 
  112 #if HAVE_OPENSSL
  113 #include <openssl/opensslv.h>
  114 #endif
  115 
  116 #if HAVE_LIBSSH2
  117 #include <libssh2.h>
  118 #endif
  119 
  120 #if HAVE_LIBZ
  121 #include <zlib.h>
  122 #endif
  123 
  124 /* To get the version number only. */
  125 #ifdef WIN32
  126 #include "libdnet-stripped/include/dnet_winconfig.h"
  127 #else
  128 #include "libdnet-stripped/include/config.h"
  129 #endif
  130 #define DNET_VERSION VERSION
  131 
  132 #ifdef LINUX
  133 /* Check for Windows Subsystem for Linux (WSL) */
  134 #include <sys/utsname.h>
  135 #endif
  136 
  137 #include <string>
  138 #include <sstream>
  139 #include <vector>
  140 
  141 /* global options */
  142 extern char *optarg;
  143 extern int optind;
  144 extern NmapOps o;  /* option structure */
  145 
  146 static void display_nmap_version();
  147 
  148 /* A mechanism to save argv[0] for code that requires that. */
  149 static const char *program_name = NULL;
  150 
  151 void set_program_name(const char *name) {
  152   program_name = name;
  153 }
  154 
  155 static const char *get_program_name(void) {
  156   return program_name;
  157 }
  158 
  159 /* 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. */
  160 static int parse_scanflags(char *arg) {
  161   int flagval = 0;
  162   char *end = NULL;
  163 
  164   if (isdigit((int) (unsigned char) arg[0])) {
  165     flagval = strtol(arg, &end, 0);
  166     if (*end || flagval < 0 || flagval > 255)
  167       return -1;
  168   } else {
  169     if (strcasestr(arg, "FIN"))
  170       flagval |= TH_FIN;
  171     if (strcasestr(arg, "SYN"))
  172       flagval |= TH_SYN;
  173     if (strcasestr(arg, "RST") || strcasestr(arg, "RESET"))
  174       flagval |= TH_RST;
  175     if (strcasestr(arg, "PSH") || strcasestr(arg, "PUSH"))
  176       flagval |= TH_PUSH;
  177     if (strcasestr(arg, "ACK"))
  178       flagval |= TH_ACK;
  179     if (strcasestr(arg, "URG"))
  180       flagval |= TH_URG;
  181     if (strcasestr(arg, "ECE"))
  182       flagval |= TH_ECE;
  183     if (strcasestr(arg, "CWR"))
  184       flagval |= TH_CWR;
  185     if (strcasestr(arg, "ALL"))
  186       flagval = 255;
  187     if (strcasestr(arg, "NONE"))
  188       flagval = 0;
  189   }
  190   return flagval;
  191 }
  192 
  193 static void printusage() {
  194 
  195   printf("%s %s ( %s )\n"
  196          "Usage: nmap [Scan Type(s)] [Options] {target specification}\n"
  197          "TARGET SPECIFICATION:\n"
  198          "  Can pass hostnames, IP addresses, networks, etc.\n"
  199          "  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254\n"
  200          "  -iL <inputfilename>: Input from list of hosts/networks\n"
  201          "  -iR <num hosts>: Choose random targets\n"
  202          "  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks\n"
  203          "  --excludefile <exclude_file>: Exclude list from file\n"
  204          "HOST DISCOVERY:\n"
  205          "  -sL: List Scan - simply list targets to scan\n"
  206          "  -sn: Ping Scan - disable port scan\n"
  207          "  -Pn: Treat all hosts as online -- skip host discovery\n"
  208          "  -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports\n"
  209          "  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes\n"
  210          "  -PO[protocol list]: IP Protocol Ping\n"
  211          "  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]\n"
  212          "  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers\n"
  213          "  --system-dns: Use OS's DNS resolver\n"
  214          "  --traceroute: Trace hop path to each host\n"
  215          "SCAN TECHNIQUES:\n"
  216          "  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans\n"
  217          "  -sU: UDP Scan\n"
  218          "  -sN/sF/sX: TCP Null, FIN, and Xmas scans\n"
  219          "  --scanflags <flags>: Customize TCP scan flags\n"
  220          "  -sI <zombie host[:probeport]>: Idle scan\n"
  221          "  -sY/sZ: SCTP INIT/COOKIE-ECHO scans\n"
  222          "  -sO: IP protocol scan\n"
  223          "  -b <FTP relay host>: FTP bounce scan\n"
  224          "PORT SPECIFICATION AND SCAN ORDER:\n"
  225          "  -p <port ranges>: Only scan specified ports\n"
  226          "    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9\n"
  227          "  --exclude-ports <port ranges>: Exclude the specified ports from scanning\n"
  228          "  -F: Fast mode - Scan fewer ports than the default scan\n"
  229          "  -r: Scan ports consecutively - don't randomize\n"
  230          "  --top-ports <number>: Scan <number> most common ports\n"
  231          "  --port-ratio <ratio>: Scan ports more common than <ratio>\n"
  232          "SERVICE/VERSION DETECTION:\n"
  233          "  -sV: Probe open ports to determine service/version info\n"
  234          "  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)\n"
  235          "  --version-light: Limit to most likely probes (intensity 2)\n"
  236          "  --version-all: Try every single probe (intensity 9)\n"
  237          "  --version-trace: Show detailed version scan activity (for debugging)\n"
  238 #ifndef NOLUA
  239          "SCRIPT SCAN:\n"
  240          "  -sC: equivalent to --script=default\n"
  241          "  --script=<Lua scripts>: <Lua scripts> is a comma separated list of\n"
  242          "           directories, script-files or script-categories\n"
  243          "  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts\n"
  244          "  --script-args-file=filename: provide NSE script args in a file\n"
  245          "  --script-trace: Show all data sent and received\n"
  246          "  --script-updatedb: Update the script database.\n"
  247          "  --script-help=<Lua scripts>: Show help about scripts.\n"
  248          "           <Lua scripts> is a comma-separated list of script-files or\n"
  249          "           script-categories.\n"
  250 #endif
  251          "OS DETECTION:\n"
  252          "  -O: Enable OS detection\n"
  253          "  --osscan-limit: Limit OS detection to promising targets\n"
  254          "  --osscan-guess: Guess OS more aggressively\n"
  255          "TIMING AND PERFORMANCE:\n"
  256          "  Options which take <time> are in seconds, or append 'ms' (milliseconds),\n"
  257          "  's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).\n"
  258          "  -T<0-5>: Set timing template (higher is faster)\n"
  259          "  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes\n"
  260          "  --min-parallelism/max-parallelism <numprobes>: Probe parallelization\n"
  261          "  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies\n"
  262          "      probe round trip time.\n"
  263          "  --max-retries <tries>: Caps number of port scan probe retransmissions.\n"
  264          "  --host-timeout <time>: Give up on target after this long\n"
  265          "  --scan-delay/--max-scan-delay <time>: Adjust delay between probes\n"
  266          "  --min-rate <number>: Send packets no slower than <number> per second\n"
  267          "  --max-rate <number>: Send packets no faster than <number> per second\n"
  268          "FIREWALL/IDS EVASION AND SPOOFING:\n"
  269          "  -f; --mtu <val>: fragment packets (optionally w/given MTU)\n"
  270          "  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys\n"
  271          "  -S <IP_Address>: Spoof source address\n"
  272          "  -e <iface>: Use specified interface\n"
  273          "  -g/--source-port <portnum>: Use given port number\n"
  274          "  --proxies <url1,[url2],...>: Relay connections through HTTP/SOCKS4 proxies\n"
  275          "  --data <hex string>: Append a custom payload to sent packets\n"
  276          "  --data-string <string>: Append a custom ASCII string to sent packets\n"
  277          "  --data-length <num>: Append random data to sent packets\n"
  278          "  --ip-options <options>: Send packets with specified ip options\n"
  279          "  --ttl <val>: Set IP time-to-live field\n"
  280          "  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address\n"
  281          "  --badsum: Send packets with a bogus TCP/UDP/SCTP checksum\n"
  282          "OUTPUT:\n"
  283          "  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,\n"
  284          "     and Grepable format, respectively, to the given filename.\n"
  285          "  -oA <basename>: Output in the three major formats at once\n"
  286          "  -v: Increase verbosity level (use -vv or more for greater effect)\n"
  287          "  -d: Increase debugging level (use -dd or more for greater effect)\n"
  288          "  --reason: Display the reason a port is in a particular state\n"
  289          "  --open: Only show open (or possibly open) ports\n"
  290          "  --packet-trace: Show all packets sent and received\n"
  291          "  --iflist: Print host interfaces and routes (for debugging)\n"
  292          "  --append-output: Append to rather than clobber specified output files\n"
  293          "  --resume <filename>: Resume an aborted scan\n"
  294          "  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML\n"
  295          "  --webxml: Reference stylesheet from Nmap.Org for more portable XML\n"
  296          "  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output\n"
  297          "MISC:\n"
  298          "  -6: Enable IPv6 scanning\n"
  299          "  -A: Enable OS detection, version detection, script scanning, and traceroute\n"
  300          "  --datadir <dirname>: Specify custom Nmap data file location\n"
  301          "  --send-eth/--send-ip: Send using raw ethernet frames or IP packets\n"
  302          "  --privileged: Assume that the user is fully privileged\n"
  303          "  --unprivileged: Assume the user lacks raw socket privileges\n"
  304          "  -V: Print version number\n"
  305          "  -h: Print this help summary page.\n"
  306          "EXAMPLES:\n"
  307          "  nmap -v -A scanme.nmap.org\n"
  308          "  nmap -v -sn 192.168.0.0/16 10.0.0.0/8\n"
  309          "  nmap -v -iR 10000 -Pn -p 80\n"
  310          "SEE THE MAN PAGE (https://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
  311 }
  312 
  313 #ifdef WIN32
  314 static void check_setugid(void) {
  315 }
  316 #else
  317 /* Show a warning when running setuid or setgid, as this allows code execution
  318    (for example NSE scripts) as the owner/group. */
  319 static void check_setugid(void) {
  320   if (getuid() != geteuid())
  321     error("WARNING: Running Nmap setuid, as you are doing, is a major security risk.\n");
  322   if (getgid() != getegid())
  323     error("WARNING: Running Nmap setgid, as you are doing, is a major security risk.\n");
  324 }
  325 #endif
  326 
  327 static void insert_port_into_merge_list(unsigned short *mlist,
  328                                         int *merged_port_count,
  329                                         unsigned short p) {
  330   int i;
  331   // make sure the port isn't already in the list
  332   for (i = 0; i < *merged_port_count; i++) {
  333     if (mlist[i] == p) {
  334       return;
  335     }
  336   }
  337   mlist[*merged_port_count] = p;
  338   (*merged_port_count)++;
  339 }
  340 
  341 static unsigned short *merge_port_lists(unsigned short *port_list1, int count1,
  342                                         unsigned short *port_list2, int count2,
  343                                         int *merged_port_count) {
  344   int i;
  345   unsigned short *merged_port_list = NULL;
  346 
  347   *merged_port_count = 0;
  348 
  349   merged_port_list =
  350     (unsigned short *) safe_zalloc((count1 + count2) * sizeof(unsigned short));
  351 
  352   for (i = 0; i < count1; i++) {
  353     insert_port_into_merge_list(merged_port_list,
  354                                 merged_port_count,
  355                                 port_list1[i]);
  356   }
  357   for (i = 0; i < count2; i++) {
  358     insert_port_into_merge_list(merged_port_list,
  359                                 merged_port_count,
  360                                 port_list2[i]);
  361   }
  362 
  363   // if there were duplicate ports then we can save some memory
  364   if (*merged_port_count < (count1 + count2)) {
  365     merged_port_list = (unsigned short*)
  366                        safe_realloc(merged_port_list,
  367                                     (*merged_port_count) * sizeof(unsigned short));
  368   }
  369 
  370   return merged_port_list;
  371 }
  372 
  373 void validate_scan_lists(scan_lists &vports, NmapOps &vo) {
  374   if (vo.pingtype == PINGTYPE_UNKNOWN) {
  375     if (vo.isr00t) {
  376       if (vo.pf() == PF_INET) {
  377         vo.pingtype = DEFAULT_IPV4_PING_TYPES;
  378       } else {
  379         vo.pingtype = DEFAULT_IPV6_PING_TYPES;
  380       }
  381       getpts_simple(DEFAULT_PING_ACK_PORT_SPEC, SCAN_TCP_PORT,
  382                     &vports.ack_ping_ports, &vports.ack_ping_count);
  383       getpts_simple(DEFAULT_PING_SYN_PORT_SPEC, SCAN_TCP_PORT,
  384                     &vports.syn_ping_ports, &vports.syn_ping_count);
  385     } else {
  386       vo.pingtype = PINGTYPE_TCP; // if nonr00t
  387       getpts_simple(DEFAULT_PING_CONNECT_PORT_SPEC, SCAN_TCP_PORT,
  388                     &vports.syn_ping_ports, &vports.syn_ping_count);
  389     }
  390   }
  391 
  392   if ((vo.pingtype & PINGTYPE_TCP) && (!vo.isr00t)) {
  393     // We will have to do a connect() style ping
  394     // Pretend we wanted SYN probes all along.
  395     if (vports.ack_ping_count > 0) {
  396       // Combine the ACK and SYN ping port lists since they both reduce to
  397       // SYN probes in this case
  398       unsigned short *merged_port_list;
  399       int merged_port_count;
  400 
  401       merged_port_list = merge_port_lists(
  402                            vports.syn_ping_ports, vports.syn_ping_count,
  403                            vports.ack_ping_ports, vports.ack_ping_count,
  404                            &merged_port_count);
  405 
  406       // clean up a bit
  407       free(vports.syn_ping_ports);
  408       free(vports.ack_ping_ports);
  409 
  410       vports.syn_ping_count = merged_port_count;
  411       vports.syn_ping_ports = merged_port_list;
  412       vports.ack_ping_count = 0;
  413       vports.ack_ping_ports = NULL;
  414     }
  415     vo.pingtype &= ~PINGTYPE_TCP_USE_ACK;
  416     vo.pingtype |= PINGTYPE_TCP_USE_SYN;
  417   }
  418 
  419   if (!vo.isr00t) {
  420     if (vo.pingtype & (PINGTYPE_ICMP_PING | PINGTYPE_ICMP_MASK | PINGTYPE_ICMP_TS)) {
  421       error("Warning:  You are not root -- using TCP pingscan rather than ICMP");
  422       vo.pingtype = PINGTYPE_TCP;
  423       if (vports.syn_ping_count == 0) {
  424         getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &vports.syn_ping_ports, &vports.syn_ping_count);
  425         assert(vports.syn_ping_count > 0);
  426       }
  427     }
  428   }
  429 }
  430 
  431 struct ftpinfo ftp = get_default_ftpinfo();
  432 
  433 /* A list of targets to be displayed by the --route-dst debugging option. */
  434 static std::vector<std::string> route_dst_hosts;
  435 
  436 struct scan_lists ports = { 0 };
  437 
  438 /* This struct is used is a temporary storage place that holds options that
  439    can't be correctly parsed and interpreted before the entire command line has
  440    been read. Examples are -6 and -S. Trying to set the source address without
  441    knowing the address family first could result in a failure if you pass an
  442    IPv6 address and the address family is still IPv4. */
  443 static struct delayed_options {
  444 public:
  445   delayed_options() {
  446     this->pre_max_parallelism   = -1;
  447     this->pre_scan_delay        = -1;
  448     this->pre_max_scan_delay    = -1;
  449     this->pre_init_rtt_timeout  = -1;
  450     this->pre_min_rtt_timeout   = -1;
  451     this->pre_max_rtt_timeout   = -1;
  452     this->pre_max_retries       = -1;
  453     this->pre_host_timeout      = -1;
  454 #ifndef NOLUA
  455     this->pre_scripttimeout     = -1;
  456 #endif
  457     this->iflist                = false;
  458     this->advanced              = false;
  459     this->af                    = AF_UNSPEC;
  460     this->decoys                = false;
  461     this->raw_scan_options      = false;
  462   }
  463 
  464   // Pre-specified timing parameters.
  465   // These are stored here during the parsing of the arguments so that we can
  466   // set the defaults specified by any timing template options (-T2, etc) BEFORE
  467   // any of these. In other words, these always take precedence over the templates.
  468   int   pre_max_parallelism, pre_scan_delay, pre_max_scan_delay;
  469   int   pre_init_rtt_timeout, pre_min_rtt_timeout, pre_max_rtt_timeout;
  470   int   pre_max_retries;
  471   long  pre_host_timeout;
  472 #ifndef NOLUA
  473   double pre_scripttimeout;
  474 #endif
  475   char  *machinefilename, *kiddiefilename, *normalfilename, *xmlfilename;
  476   bool  iflist, decoys, advanced, raw_scan_options;
  477   char  *exclude_spec, *exclude_file;
  478   char  *spoofSource, *decoy_arguments;
  479   const char *spoofmac;
  480   int af;
  481   std::vector<std::string> verbose_out;
  482 
  483   void warn_deprecated (const char *given, const char *replacement) {
  484     std::ostringstream os;
  485     os << "Warning: The -" << given << " option is deprecated. Please use -" << replacement;
  486     this->verbose_out.push_back(os.str());
  487   }
  488 
  489 } delayed_options;
  490 
  491 struct tm local_time;
  492 
  493 static void test_file_name(const char *filename, const char *option) {
  494   if (filename[0] == '-' && filename[1] != '\0') {
  495     fatal("Output filename begins with '-'. Try '-%s ./%s' if you really want it to be named as such.", option, filename);
  496   } else if (strcmp(option, "o") == 0 && strchr("NAXGS", filename[0])) {
  497     fatal("You are using a deprecated option in a dangerous way. Did you mean: -o%c %s", filename[0], filename + 1);
  498   } else if (filename[0] == '-' && strcmp(option,"oA") == 0) {
  499     fatal("Cannot display multiple output types to stdout.");
  500   }
  501 }
  502 
  503 void parse_options(int argc, char **argv) {
  504   char *p;
  505   int arg;
  506   long l;
  507   double d;
  508   char *endptr = NULL;
  509   char errstr[256];
  510   int option_index;
  511 #ifdef WORDS_BIGENDIAN
  512   int k[]={2037345391,1935892846,0,1279608146,1331241034,1162758985,1314070817,554303488,1869291630,1768383852};
  513 #else
  514   int k[]={1869377401,1851876211,0,1380271436,1243633999,1229672005,555832142,2593,1847618415,1818584937};
  515 #endif
  516 
  517   struct option long_options[] = {
  518     {"version", no_argument, 0, 'V'},
  519     {"verbose", no_argument, 0, 'v'},
  520     {"datadir", required_argument, 0, 0},
  521     {"servicedb", required_argument, 0, 0},
  522     {"versiondb", required_argument, 0, 0},
  523     {"debug", optional_argument, 0, 'd'},
  524     {"help", no_argument, 0, 'h'},
  525     {"iflist", no_argument, 0, 0},
  526     {"release-memory", no_argument, 0, 0},
  527     {"nogcc", no_argument, 0, 0},
  528     {"max-os-tries", required_argument, 0, 0},
  529     {"max-parallelism", required_argument, 0, 'M'},
  530     {"min-parallelism", required_argument, 0, 0},
  531     {"timing", required_argument, 0, 'T'},
  532     {"max-rtt-timeout", required_argument, 0, 0},
  533     {"min-rtt-timeout", required_argument, 0, 0},
  534     {"initial-rtt-timeout", required_argument, 0, 0},
  535     {"excludefile", required_argument, 0, 0},
  536     {"exclude", required_argument, 0, 0},
  537     {"max-hostgroup", required_argument, 0, 0},
  538     {"min-hostgroup", required_argument, 0, 0},
  539     {"open", no_argument, 0, 0},
  540     {"scanflags", required_argument, 0, 0},
  541     {"defeat-rst-ratelimit", no_argument, 0, 0},
  542     {"defeat-icmp-ratelimit", no_argument, 0, 0},
  543     {"host-timeout", required_argument, 0, 0},
  544     {"scan-delay", required_argument, 0, 0},
  545     {"max-scan-delay", required_argument, 0, 0},
  546     {"max-retries", required_argument, 0, 0},
  547     {"oA", required_argument, 0, 0},
  548     {"oN", required_argument, 0, 0},
  549     {"oM", required_argument, 0, 0},
  550     {"oG", required_argument, 0, 0},
  551     {"oS", required_argument, 0, 0},
  552     {"oH", required_argument, 0, 0},
  553     {"oX", required_argument, 0, 0},
  554     {"iL", required_argument, 0, 0},
  555     {"iR", required_argument, 0, 0},
  556     {"sI", required_argument, 0, 0},
  557     {"source-port", required_argument, 0, 'g'},
  558     {"randomize-hosts", no_argument, 0, 0},
  559     {"nsock-engine", required_argument, 0, 0},
  560     {"proxies", required_argument, 0, 0},
  561     {"proxy", required_argument, 0, 0},
  562     {"discovery-ignore-rst", no_argument, 0, 0},
  563     {"osscan-limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
  564     {"osscan-guess", no_argument, 0, 0}, /* More guessing flexibility */
  565     {"fuzzy", no_argument, 0, 0}, /* Alias for osscan_guess */
  566     {"packet-trace", no_argument, 0, 0}, /* Display all packets sent/rcv */
  567     {"version-trace", no_argument, 0, 0}, /* Display -sV related activity */
  568     {"data", required_argument, 0, 0},
  569     {"data-string", required_argument, 0, 0},
  570     {"data-length", required_argument, 0, 0},
  571     {"send-eth", no_argument, 0, 0},
  572     {"send-ip", no_argument, 0, 0},
  573     {"stylesheet", required_argument, 0, 0},
  574     {"no-stylesheet", no_argument, 0, 0},
  575     {"webxml", no_argument, 0, 0},
  576     {"rH", no_argument, 0, 0},
  577     {"vv", no_argument, 0, 0},
  578     {"ff", no_argument, 0, 0},
  579     {"privileged", no_argument, 0, 0},
  580     {"unprivileged", no_argument, 0, 0},
  581     {"mtu", required_argument, 0, 0},
  582     {"append-output", no_argument, 0, 0},
  583     {"noninteractive", no_argument, 0, 0},
  584     {"spoof-mac", required_argument, 0, 0},
  585     {"thc", no_argument, 0, 0},
  586     {"badsum", no_argument, 0, 0},
  587     {"ttl", required_argument, 0, 0}, /* Time to live */
  588     {"traceroute", no_argument, 0, 0},
  589     {"reason", no_argument, 0, 0},
  590     {"allports", no_argument, 0, 0},
  591     {"version-intensity", required_argument, 0, 0},
  592     {"version-light", no_argument, 0, 0},
  593     {"version-all", no_argument, 0, 0},
  594     {"system-dns", no_argument, 0, 0},
  595     {"resolve-all", no_argument, 0, 0},
  596     {"log-errors", no_argument, 0, 0},
  597     {"deprecated-xml-osclass", no_argument, 0, 0},
  598     {(char*)k, no_argument, 0, 0},
  599     {"dns-servers", required_argument, 0, 0},
  600     {"port-ratio", required_argument, 0, 0},
  601     {"exclude-ports", required_argument, 0, 0},
  602     {"top-ports", required_argument, 0, 0},
  603 #ifndef NOLUA
  604     {"script", required_argument, 0, 0},
  605     {"script-trace", no_argument, 0, 0},
  606     {"script-updatedb", no_argument, 0, 0},
  607     {"script-args", required_argument, 0, 0},
  608     {"script-args-file", required_argument, 0, 0},
  609     {"script-help", required_argument, 0, 0},
  610     {"script-timeout", required_argument, 0, 0},
  611 #endif
  612     {"ip-options", required_argument, 0, 0},
  613     {"min-rate", required_argument, 0, 0},
  614     {"max-rate", required_argument, 0, 0},
  615     {"adler32", no_argument, 0, 0},
  616     {"stats-every", required_argument, 0, 0},
  617     {"disable-arp-ping", no_argument, 0, 0},
  618     {"route-dst", required_argument, 0, 0},
  619     {"resume", required_argument, 0, 0},
  620     {0, 0, 0, 0}
  621   };
  622 
  623   /* OK, lets parse these args! */
  624   optind = 1; /* so it can be called multiple times */
  625   while ((arg = getopt_long_only(argc, argv, "46Ab:D:d::e:Ffg:hIi:M:m:nO::o:P::p:qRrS:s::T:Vv::", long_options, &option_index)) != EOF) {
  626     switch (arg) {
  627     case 0:
  628 #ifndef NOLUA
  629       if (strcmp(long_options[option_index].name, "script") == 0) {
  630         o.script = true;
  631         o.chooseScripts(optarg);
  632       } else if (strcmp(long_options[option_index].name, "script-args") == 0) {
  633         o.scriptargs = strdup(optarg);
  634       } else if (strcmp(long_options[option_index].name, "script-args-file") == 0) {
  635         o.scriptargsfile = strdup(optarg);
  636       } else if (strcmp(long_options[option_index].name, "script-trace") == 0) {
  637         o.scripttrace = true;
  638       } else if (strcmp(long_options[option_index].name, "script-updatedb") == 0) {
  639         o.scriptupdatedb = true;
  640       } else if (strcmp(long_options[option_index].name, "script-help") == 0) {
  641         o.scripthelp = true;
  642         o.chooseScripts(optarg);
  643       } else if (strcmp(long_options[option_index].name, "script-timeout") == 0) {
  644         d = tval2secs(optarg);
  645         if (d < 0 || d > LONG_MAX)
  646           fatal("Bogus --script-timeout argument specified");
  647         delayed_options.pre_scripttimeout = d;
  648       } else
  649 #endif
  650         if (strcmp(long_options[option_index].name, "max-os-tries") == 0) {
  651           l = atoi(optarg);
  652           if (l < 1 || l > 50)
  653             fatal("Bogus --max-os-tries argument specified, must be between 1 and 50 (inclusive)");
  654           o.setMaxOSTries(l);
  655         } else if (strcmp(long_options[option_index].name, "max-rtt-timeout") == 0) {
  656           l = tval2msecs(optarg);
  657           if (l < 5)
  658             fatal("Bogus --max-rtt-timeout argument specified, must be at least 5ms");
  659           if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
  660             fatal("Since April 2010, the default unit for --max-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
  661           if (l < 20)
  662             error("WARNING: You specified a round-trip time timeout (%ld ms) that is EXTRAORDINARILY SMALL.  Accuracy may suffer.", l);
  663           delayed_options.pre_max_rtt_timeout = l;
  664         } else if (strcmp(long_options[option_index].name, "min-rtt-timeout") == 0) {
  665           l = tval2msecs(optarg);
  666           if (l < 0)
  667             fatal("Bogus --min-rtt-timeout argument specified");
  668           if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
  669             fatal("Since April 2010, the default unit for --min-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
  670           delayed_options.pre_min_rtt_timeout = l;
  671         } else if (strcmp(long_options[option_index].name, "initial-rtt-timeout") == 0) {
  672           l = tval2msecs(optarg);
  673           if (l <= 0)
  674             fatal("Bogus --initial-rtt-timeout argument specified.  Must be positive");
  675           if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
  676             fatal("Since April 2010, the default unit for --initial-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
  677           delayed_options.pre_init_rtt_timeout = l;
  678         } else if (strcmp(long_options[option_index].name, "excludefile") == 0) {
  679           delayed_options.exclude_file = strdup(optarg);
  680         } else if (strcmp(long_options[option_index].name, "exclude") == 0) {
  681           delayed_options.exclude_spec = strdup(optarg);
  682         } else if (strcmp(long_options[option_index].name, "max-hostgroup") == 0) {
  683           o.setMaxHostGroupSz(atoi(optarg));
  684         } else if (strcmp(long_options[option_index].name, "min-hostgroup") == 0) {
  685           o.setMinHostGroupSz(atoi(optarg));
  686           if (atoi(optarg) > 100)
  687             error("Warning: You specified a highly aggressive --min-hostgroup.");
  688         } else if (strcmp(long_options[option_index].name, "open") == 0) {
  689           o.setOpenOnly(true);
  690           // If they only want open, don't spend extra time (potentially) distinguishing closed from filtered.
  691           o.defeat_rst_ratelimit = true;
  692         } else if (strcmp(long_options[option_index].name, "scanflags") == 0) {
  693           delayed_options.raw_scan_options = true;
  694           o.scanflags = parse_scanflags(optarg);
  695           if (o.scanflags < 0) {
  696             fatal("--scanflags option must be a number between 0 and 255 (inclusive) or a string like \"URGPSHFIN\".");
  697           }
  698         } else if (strcmp(long_options[option_index].name, "iflist") == 0) {
  699           delayed_options.iflist = true;
  700         } else if (strcmp(long_options[option_index].name, "nogcc") == 0) {
  701           o.nogcc = true;
  702         } else if (strcmp(long_options[option_index].name, "release-memory") == 0) {
  703           o.release_memory = true;
  704         } else if (strcmp(long_options[option_index].name, "min-parallelism") == 0) {
  705           o.min_parallelism = atoi(optarg);
  706           if (o.min_parallelism < 1)
  707             fatal("Argument to --min-parallelism must be at least 1!");
  708           if (o.min_parallelism > 100) {
  709             error("Warning: Your --min-parallelism option is pretty high!  This can hurt reliability.");
  710           }
  711         } else if (strcmp(long_options[option_index].name, "host-timeout") == 0) {
  712           l = tval2msecs(optarg);
  713           if (l <= 0)
  714             fatal("Bogus --host-timeout argument specified");
  715           if (l >= 10000 * 1000 && tval_unit(optarg) == NULL)
  716             fatal("Since April 2010, the default unit for --host-timeout is seconds, so your time of \"%s\" is %.1f hours. If this is what you want, use \"%ss\".", optarg, l / 1000.0 / 60 / 60, optarg);
  717           delayed_options.pre_host_timeout = l;
  718         } else if (strcmp(long_options[option_index].name, "ttl") == 0) {
  719           delayed_options.raw_scan_options = true;
  720           o.ttl = atoi(optarg);
  721           if (o.ttl < 0 || o.ttl > 255) {
  722             fatal("ttl option must be a number between 0 and 255 (inclusive)");
  723           }
  724         } else if (strcmp(long_options[option_index].name, "datadir") == 0) {
  725           o.datadir = strdup(optarg);
  726         } else if (strcmp(long_options[option_index].name, "servicedb") == 0) {
  727           o.requested_data_files["nmap-services"] = optarg;
  728           o.fastscan = true;
  729         } else if (strcmp(long_options[option_index].name, "versiondb") == 0) {
  730           o.requested_data_files["nmap-service-probes"] = optarg;
  731         } else if (strcmp(long_options[option_index].name, "append-output") == 0) {
  732           o.append_output = true;
  733         } else if (strcmp(long_options[option_index].name, "noninteractive") == 0) {
  734           o.noninteractive = true;
  735         } else if (strcmp(long_options[option_index].name, "spoof-mac") == 0) {
  736           /* I need to deal with this later, once I'm sure that I have output
  737              files set up, --datadir, etc. */
  738           delayed_options.spoofmac = optarg;
  739           delayed_options.raw_scan_options = true;
  740         } else if (strcmp(long_options[option_index].name, "allports") == 0) {
  741           o.override_excludeports = true;
  742         } else if (strcmp(long_options[option_index].name, "version-intensity") == 0) {
  743           o.version_intensity = atoi(optarg);
  744           if (o.version_intensity < 0 || o.version_intensity > 9)
  745             fatal("version-intensity must be between 0 and 9");
  746         } else if (strcmp(long_options[option_index].name, "version-light") == 0) {
  747           o.version_intensity = 2;
  748         } else if (strcmp(long_options[option_index].name, "version-all") == 0) {
  749           o.version_intensity = 9;
  750         } else if (strcmp(long_options[option_index].name, "scan-delay") == 0) {
  751           l = tval2msecs(optarg);
  752           if (l < 0)
  753             fatal("Bogus --scan-delay argument specified.");
  754           if (l >= 100 * 1000 && tval_unit(optarg) == NULL)
  755             fatal("Since April 2010, the default unit for --scan-delay is seconds, so your time of \"%s\" is %.1f minutes. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0 / 60, optarg, l / 1000.0);
  756           delayed_options.pre_scan_delay = l;
  757         } else if (strcmp(long_options[option_index].name, "defeat-rst-ratelimit") == 0) {
  758           o.defeat_rst_ratelimit = true;
  759         } else if (strcmp(long_options[option_index].name, "defeat-icmp-ratelimit") == 0) {
  760           o.defeat_icmp_ratelimit = true;
  761         } else if (strcmp(long_options[option_index].name, "max-scan-delay") == 0) {
  762           l = tval2msecs(optarg);
  763           if (l < 0)
  764             fatal("Bogus --max-scan-delay argument specified.");
  765           if (l >= 100 * 1000 && tval_unit(optarg) == NULL)
  766             fatal("Since April 2010, the default unit for --max-scan-delay is seconds, so your time of \"%s\" is %.1f minutes. If this is what you want, use \"%ss\".", optarg, l / 1000.0 / 60, optarg);
  767           delayed_options.pre_max_scan_delay = l;
  768         } else if (strcmp(long_options[option_index].name, "max-retries") == 0) {
  769           delayed_options.pre_max_retries = atoi(optarg);
  770           if (delayed_options.pre_max_retries < 0)
  771             fatal("max-retries must be positive");
  772         } else if (strcmp(long_options[option_index].name, "randomize-hosts") == 0
  773                    || strcmp(long_options[option_index].name, "rH") == 0) {
  774           o.randomize_hosts = true;
  775           o.ping_group_sz = PING_GROUP_SZ * 4;
  776         } else if (strcmp(long_options[option_index].name, "nsock-engine") == 0) {
  777           if (nsock_set_default_engine(optarg) < 0)
  778             fatal("Unknown or non-available engine: %s", optarg);
  779         } else if ((strcmp(long_options[option_index].name, "proxies") == 0) || (strcmp(long_options[option_index].name, "proxy") == 0)) {
  780           if (nsock_proxychain_new(optarg, &o.proxy_chain, NULL) < 0)
  781             fatal("Invalid proxy chain specification");
  782         } else if (strcmp(long_options[option_index].name, "discovery-ignore-rst") == 0) {
  783             o.discovery_ignore_rst = true;
  784         } else if (strcmp(long_options[option_index].name, "osscan-limit")  == 0) {
  785           o.osscan_limit = true;
  786         } else if (strcmp(long_options[option_index].name, "osscan-guess")  == 0
  787                    || strcmp(long_options[option_index].name, "fuzzy") == 0) {
  788           o.osscan_guess = true;
  789         } else if (strcmp(long_options[option_index].name, "packet-trace") == 0) {
  790           o.setPacketTrace(true);
  791 #ifndef NOLUA
  792           o.scripttrace = true;
  793 #endif
  794         } else if (strcmp(long_options[option_index].name, "version-trace") == 0) {
  795           o.setVersionTrace(true);
  796           o.debugging++;
  797         } else if (strcmp(long_options[option_index].name, "data") == 0) {
  798           delayed_options.raw_scan_options = true;
  799           if (o.extra_payload)
  800             fatal("Can't use the --data option(s) multiple times, or together.");
  801           u8 *tempbuff=NULL;
  802           size_t len=0;
  803           if( (tempbuff=parse_hex_string(optarg, &len))==NULL)
  804             fatal("Invalid hex string specified");
  805           else {
  806             o.extra_payload_length = len;
  807             o.extra_payload = (char *) safe_malloc(o.extra_payload_length);
  808             memcpy(o.extra_payload, tempbuff, len);
  809           }
  810           if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
  811             error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
  812         } else if (strcmp(long_options[option_index].name, "data-string") == 0) {
  813           delayed_options.raw_scan_options = true;
  814           if (o.extra_payload)
  815             fatal("Can't use the --data option(s) multiple times, or together.");
  816           o.extra_payload_length = strlen(optarg);
  817           if (o.extra_payload_length < 0 || o.extra_payload_length > MAX_PAYLOAD_ALLOWED)
  818             fatal("string length must be between 0 and %d", MAX_PAYLOAD_ALLOWED);
  819           if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
  820             error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
  821           o.extra_payload = strdup(optarg);
  822         } else if (strcmp(long_options[option_index].name, "data-length") == 0) {
  823           delayed_options.raw_scan_options = true;
  824           if (o.extra_payload)
  825             fatal("Can't use the --data option(s) multiple times, or together.");
  826           o.extra_payload_length = (int)strtol(optarg, NULL, 10);
  827           if (o.extra_payload_length < 0 || o.extra_payload_length > MAX_PAYLOAD_ALLOWED)
  828             fatal("data-length must be between 0 and %d", MAX_PAYLOAD_ALLOWED);
  829           if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
  830             error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
  831           o.extra_payload = (char *) safe_malloc(MAX(o.extra_payload_length, 1));
  832           get_random_bytes(o.extra_payload, o.extra_payload_length);
  833         } else if (strcmp(long_options[option_index].name, "send-eth") == 0) {
  834           o.sendpref = PACKET_SEND_ETH_STRONG;
  835         } else if (strcmp(long_options[option_index].name, "send-ip") == 0) {
  836           o.sendpref = PACKET_SEND_IP_STRONG;
  837         } else if (strcmp(long_options[option_index].name, "stylesheet") == 0) {
  838           o.setXSLStyleSheet(optarg);
  839         } else if (strcmp(long_options[option_index].name, "no-stylesheet") == 0) {
  840           o.setXSLStyleSheet(NULL);
  841         } else if (strcmp(long_options[option_index].name, "system-dns") == 0) {
  842           o.mass_dns = false;
  843         } else if (strcmp(long_options[option_index].name, "dns-servers") == 0) {
  844           o.dns_servers = strdup(optarg);
  845         } else if (strcmp(long_options[option_index].name, "resolve-all") == 0) {
  846           o.resolve_all = true;
  847         } else if (strcmp(long_options[option_index].name, "log-errors") == 0) {
  848           /*Nmap Log errors is deprecated and is now always enabled by default.
  849           This option is left in so as to not break anybody's scanning scripts.
  850           However it does nothing*/
  851         } else if (strcmp(long_options[option_index].name, "deprecated-xml-osclass") == 0) {
  852           o.deprecated_xml_osclass = true;
  853         } else if (strcmp(long_options[option_index].name, (char*)k) == 0) {
  854           log_write(LOG_STDOUT, "%s", (char*)(k+3));
  855           delayed_options.advanced = true;
  856         } else if (strcmp(long_options[option_index].name, "webxml") == 0) {
  857           o.setXSLStyleSheet("https://svn.nmap.org/nmap/docs/nmap.xsl");
  858         } else if (strcmp(long_options[option_index].name, "oN") == 0) {
  859           test_file_name(optarg, long_options[option_index].name);
  860           delayed_options.normalfilename = logfilename(optarg, &local_time);
  861         } else if (strcmp(long_options[option_index].name, "oG") == 0
  862                    || strcmp(long_options[option_index].name, "oM") == 0) {
  863           test_file_name(optarg, long_options[option_index].name);
  864           delayed_options.machinefilename = logfilename(optarg, &local_time);
  865           if (long_options[option_index].name[1] == 'M')
  866             delayed_options.warn_deprecated("oM", "oG");
  867         } else if (strcmp(long_options[option_index].name, "oS") == 0) {
  868           test_file_name(optarg, long_options[option_index].name);
  869           delayed_options.kiddiefilename = logfilename(optarg, &local_time);
  870         } else if (strcmp(long_options[option_index].name, "oH") == 0) {
  871           fatal("HTML output is not directly supported, though Nmap includes an XSL for transforming XML output into HTML.  See the man page.");
  872         } else if (strcmp(long_options[option_index].name, "oX") == 0) {
  873           test_file_name(optarg, long_options[option_index].name);
  874           delayed_options.xmlfilename = logfilename(optarg, &local_time);
  875         } else if (strcmp(long_options[option_index].name, "oA") == 0) {
  876           char buf[MAXPATHLEN];
  877           test_file_name(optarg, long_options[option_index].name);
  878           Snprintf(buf, sizeof(buf), "%s.nmap", logfilename(optarg, &local_time));
  879           delayed_options.normalfilename = strdup(buf);
  880           Snprintf(buf, sizeof(buf), "%s.gnmap", logfilename(optarg, &local_time));
  881           delayed_options.machinefilename = strdup(buf);
  882           Snprintf(buf, sizeof(buf), "%s.xml", logfilename(optarg, &local_time));
  883           delayed_options.xmlfilename = strdup(buf);
  884         } else if (strcmp(long_options[option_index].name, "thc") == 0) {
  885           log_write(LOG_STDOUT, "!!Greets to Van Hauser, Plasmoid, Skyper and the rest of THC!!\n");
  886           exit(0);
  887         } else if (strcmp(long_options[option_index].name, "badsum") == 0) {
  888           delayed_options.raw_scan_options = true;
  889           o.badsum = true;
  890         } else if (strcmp(long_options[option_index].name, "iL") == 0) {
  891           if (o.inputfd) {
  892             fatal("Only one input filename allowed");
  893           }
  894           if (!strcmp(optarg, "-")) {
  895             o.inputfd = stdin;
  896           } else {
  897             o.inputfd = fopen(optarg, "r");
  898             if (!o.inputfd) {
  899               fatal("Failed to open input file %s for reading", optarg);
  900             }
  901           }
  902         } else if (strcmp(long_options[option_index].name, "iR") == 0) {
  903           o.generate_random_ips = true;
  904           o.max_ips_to_scan = strtoul(optarg, &endptr, 10);
  905           if (*endptr != '\0') {
  906             fatal("ERROR: -iR argument must be the maximum number of random IPs you wish to scan (use 0 for unlimited)");
  907           }
  908         } else if (strcmp(long_options[option_index].name, "sI") == 0) {
  909           o.idlescan = 1;
  910           o.idleProxy = strdup(optarg);
  911           if (strlen(o.idleProxy) > FQDN_LEN) {
  912             fatal("ERROR: -sI argument must be less than %d characters", FQDN_LEN);
  913           }
  914         } else if (strcmp(long_options[option_index].name, "vv") == 0) {
  915           /* Compatibility hack ... ugly */
  916           o.verbose += 2;
  917           if (o.verbose > 10) o.verbose = 10;
  918         } else if (strcmp(long_options[option_index].name, "ff") == 0) {
  919           delayed_options.raw_scan_options = true;
  920           o.fragscan += 16;
  921         } else if (strcmp(long_options[option_index].name, "privileged") == 0) {
  922           o.isr00t = 1;
  923         } else if (strcmp(long_options[option_index].name, "unprivileged") == 0) {
  924           o.isr00t = 0;
  925         } else if (strcmp(long_options[option_index].name, "mtu") == 0) {
  926           delayed_options.raw_scan_options = true;
  927           o.fragscan = atoi(optarg);
  928           if (o.fragscan <= 0 || o.fragscan % 8 != 0)
  929             fatal("Data payload MTU must be >0 and multiple of 8");
  930         } else if (strcmp(long_options[option_index].name, "port-ratio") == 0) {
  931           char *ptr;
  932           o.topportlevel = strtod(optarg, &ptr);
  933           if (!ptr || o.topportlevel < 0 || o.topportlevel >= 1)
  934             fatal("--port-ratio should be between [0 and 1)");
  935         } else if (strcmp(long_options[option_index].name, "exclude-ports") == 0) {
  936           if (o.exclude_portlist)
  937             fatal("Only 1 --exclude-ports option allowed, separate multiple ranges with commas.");
  938           o.exclude_portlist = strdup(optarg);
  939         } else if (strcmp(long_options[option_index].name, "top-ports") == 0) {
  940           char *ptr;
  941           o.topportlevel = strtod(optarg, &ptr);
  942           if (!ptr || o.topportlevel < 1 || ((double)((int)o.topportlevel)) != o.topportlevel)
  943             fatal("--top-ports should be an integer 1 or greater");
  944         } else if (strcmp(long_options[option_index].name, "ip-options") == 0) {
  945           delayed_options.raw_scan_options = true;
  946           o.ipoptions    = (u8*) safe_malloc(4 * 10 + 1);
  947           if ((o.ipoptionslen = parse_ip_options(optarg, o.ipoptions, 4 * 10 + 1, &o.ipopt_firsthop, &o.ipopt_lasthop, errstr, sizeof(errstr))) == OP_FAILURE)
  948             fatal("%s", errstr);
  949           if (o.ipoptionslen > 4 * 10)
  950             fatal("Ip options can't be more than 40 bytes long");
  951           if (o.ipoptionslen % 4 != 0)
  952             fatal("Ip options must be multiple of 4 (read length is %i bytes)", o.ipoptionslen);
  953         } else if (strcmp(long_options[option_index].name, "traceroute") == 0) {
  954           o.traceroute = true;
  955         } else if (strcmp(long_options[option_index].name, "reason") == 0) {
  956           o.reason = true;
  957         } else if (strcmp(long_options[option_index].name, "min-rate") == 0) {
  958           if (sscanf(optarg, "%f", &o.min_packet_send_rate) != 1 || o.min_packet_send_rate <= 0.0)
  959             fatal("Argument to --min-rate must be a positive floating-point number");
  960         } else if (strcmp(long_options[option_index].name, "max-rate") == 0) {
  961           if (sscanf(optarg, "%f", &o.max_packet_send_rate) != 1 || o.max_packet_send_rate <= 0.0)
  962             fatal("Argument to --max-rate must be a positive floating-point number");
  963         } else if (strcmp(long_options[option_index].name, "adler32") == 0) {
  964           o.adler32 = true;
  965         } else if (strcmp(long_options[option_index].name, "stats-every") == 0) {
  966           d = tval2secs(optarg);
  967           if (d < 0 || d > LONG_MAX)
  968             fatal("Bogus --stats-every argument specified");
  969           o.stats_interval = d;
  970         } else if (strcmp(long_options[option_index].name, "disable-arp-ping") == 0) {
  971           o.implicitARPPing = false;
  972         } else if (strcmp(long_options[option_index].name, "route-dst") == 0) {
  973           /* The --route-dst debugging option: push these on a list to be
  974              resolved later after options like -6 and -S have been parsed. */
  975           route_dst_hosts.push_back(optarg);
  976         } else if (strcmp(long_options[option_index].name, "resume") == 0) {
  977           fatal("Cannot use --resume with other options. Usage: nmap --resume <filename>");
  978         } else {
  979           fatal("Unknown long option (%s) given@#!$#$", long_options[option_index].name);
  980         }
  981       break;
  982     case '4':
  983       /* This is basically useless for now, but serves as a placeholder to
  984        * ensure that -4 is a valid option */
  985       if (delayed_options.af == AF_INET6) {
  986         fatal("Cannot use both -4 and -6 in one scan.");
  987       }
  988       delayed_options.af = AF_INET;
  989       break;
  990     case '6':
  991 #if !HAVE_IPV6
  992       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.");
  993 #else
  994       if (delayed_options.af == AF_INET) {
  995         fatal("Cannot use both -4 and -6 in one scan.");
  996       }
  997       delayed_options.af = AF_INET6;
  998 #endif /* !HAVE_IPV6 */
  999       break;
 1000     case 'A':
 1001       delayed_options.advanced = true;
 1002       break;
 1003     case 'b':
 1004       o.bouncescan++;
 1005       if (parse_bounce_argument(&ftp, optarg) < 0) {
 1006         fatal("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");
 1007       }
 1008       break;
 1009     case 'D':
 1010       delayed_options.raw_scan_options = true;
 1011       delayed_options.decoy_arguments = optarg;
 1012       break;
 1013     case 'd':
 1014       if (optarg && isdigit(optarg[0])) {
 1015         int i = atoi(optarg);
 1016         o.debugging = o.verbose = box(0, 10, i);
 1017       } else {
 1018         const char *p;
 1019         if (o.debugging < 10) o.debugging++;
 1020         if (o.verbose < 10) o.verbose++;
 1021         for (p = optarg != NULL ? optarg : ""; *p == 'd'; p++) {
 1022           if (o.debugging < 10) o.debugging++;
 1023           if (o.verbose < 10) o.verbose++;
 1024         }
 1025         if (*p != '\0')
 1026           fatal("Invalid argument to -d: \"%s\".", optarg);
 1027       }
 1028       o.reason = true;
 1029       break;
 1030     case 'e':
 1031       Strncpy(o.device, optarg, sizeof(o.device));
 1032       break;
 1033     case 'F':
 1034       o.fastscan = true;
 1035       break;
 1036     case 'f':
 1037       delayed_options.raw_scan_options = true;
 1038       o.fragscan += 8;
 1039       break;
 1040     case 'g':
 1041       delayed_options.raw_scan_options = true;
 1042       o.magic_port = atoi(optarg);
 1043       o.magic_port_set = true;
 1044       if (o.magic_port == 0)
 1045         error("WARNING: a source port of zero may not work on all systems.");
 1046       break;
 1047     case 'h':
 1048       printusage();
 1049       exit(0);
 1050       break;
 1051     case '?':
 1052       error("See the output of nmap -h for a summary of options.");
 1053       exit(-1);
 1054       break;
 1055     case 'I':
 1056       error("WARNING: identscan (-I) no longer supported.  Ignoring -I");
 1057       break;
 1058       // o.identscan++; break;
 1059     case 'i':
 1060       delayed_options.warn_deprecated("i", "iL");
 1061       if (o.inputfd) {
 1062         fatal("Only one input filename allowed");
 1063       }
 1064       if (!strcmp(optarg, "-")) {
 1065         o.inputfd = stdin;
 1066       } else {
 1067         o.inputfd = fopen(optarg, "r");
 1068         if (!o.inputfd) {
 1069           fatal("Failed to open input file %s for reading", optarg);
 1070         }
 1071       }
 1072       break;
 1073     case 'M':
 1074       delayed_options.pre_max_parallelism = atoi(optarg);
 1075       if (delayed_options.pre_max_parallelism < 1)
 1076         fatal("Argument to -M must be at least 1!");
 1077       if (delayed_options.pre_max_parallelism > 900)
 1078         error("Warning: Your max-parallelism (-M) option is extraordinarily high, which can hurt reliability");
 1079       break;
 1080     case 'm':
 1081       delayed_options.warn_deprecated("m", "oG");
 1082       test_file_name(optarg, "oG");
 1083       delayed_options.machinefilename = logfilename(optarg, &local_time);
 1084       break;
 1085     case 'n':
 1086       o.noresolve = true;
 1087       break;
 1088     case 'O':
 1089       if (!optarg || *optarg == '2')
 1090         o.osscan = true;
 1091       else if (*optarg == '1')
 1092         fatal("First-generation OS detection (-O1) is no longer supported. Use -O instead.");
 1093       else
 1094         fatal("Unknown argument to -O.");
 1095       break;
 1096     case 'o':
 1097       delayed_options.warn_deprecated("o", "oN");
 1098       test_file_name(optarg, "o");
 1099       delayed_options.normalfilename = logfilename(optarg, &local_time);
 1100       break;
 1101     case 'P':
 1102       if (!optarg) {
 1103           delayed_options.warn_deprecated("P", "PE");
 1104           o.pingtype |= PINGTYPE_ICMP_PING;
 1105       }
 1106       else if (*optarg == '\0' || *optarg == 'I' || *optarg == 'E') {
 1107         if (*optarg != 'E') {
 1108           char buf[4];
 1109           Snprintf(buf, 3, "P%c", *optarg);
 1110           delayed_options.warn_deprecated(buf, "PE");
 1111         }
 1112         o.pingtype |= PINGTYPE_ICMP_PING;
 1113       }
 1114       else if (*optarg == 'M')
 1115         o.pingtype |= PINGTYPE_ICMP_MASK;
 1116       else if (*optarg == 'P')
 1117         o.pingtype |= PINGTYPE_ICMP_TS;
 1118       else if (*optarg == 'n' || *optarg == '0' || *optarg == 'N' || *optarg == 'D') {
 1119         if (*optarg != 'n') {
 1120           char buf[4];
 1121           Snprintf(buf, 3, "P%c", *optarg);
 1122           delayed_options.warn_deprecated(buf, "Pn");
 1123         }
 1124         error("Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.");
 1125         o.pingtype |= PINGTYPE_NONE;
 1126       }
 1127       else if (*optarg == 'R') {
 1128         if (o.verbose > 0)
 1129           error("The -PR option is deprecated. ARP scan is always done when possible.");
 1130       }
 1131       else if (*optarg == 'S') {
 1132         if (ports.syn_ping_count > 0)
 1133           fatal("Only one -PS option is allowed. Combine port ranges with commas.");
 1134         o.pingtype |= (PINGTYPE_TCP | PINGTYPE_TCP_USE_SYN);
 1135         if (*(optarg + 1) != '\0') {
 1136           getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.syn_ping_ports, &ports.syn_ping_count);
 1137           if (ports.syn_ping_count <= 0)
 1138             fatal("Bogus argument to -PS: %s", optarg + 1);
 1139         } else {
 1140           getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.syn_ping_ports, &ports.syn_ping_count);
 1141           assert(ports.syn_ping_count > 0);
 1142         }
 1143       } else if (*optarg == 'T' || *optarg == 'A') {
 1144         if (ports.ack_ping_count > 0)
 1145           fatal("Only one -PB, -PA, or -PT option is allowed. Combine port ranges with commas.");
 1146         /* validate_scan_lists takes case of changing this to
 1147            to SYN if not root or if IPv6. */
 1148         o.pingtype |= (PINGTYPE_TCP | PINGTYPE_TCP_USE_ACK);
 1149         if (*(optarg + 1) != '\0') {
 1150           getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
 1151           if (ports.ack_ping_count <= 0)
 1152             fatal("Bogus argument to -PA: %s", optarg + 1);
 1153         } else {
 1154           getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
 1155           assert(ports.ack_ping_count > 0);
 1156         }
 1157       } else if (*optarg == 'U') {
 1158         if (ports.udp_ping_count > 0)
 1159           fatal("Only one -PU option is allowed. Combine port ranges with commas.");
 1160         o.pingtype |= (PINGTYPE_UDP);
 1161         if (*(optarg + 1) != '\0') {
 1162           getpts_simple(optarg + 1, SCAN_UDP_PORT, &ports.udp_ping_ports, &ports.udp_ping_count);
 1163           if (ports.udp_ping_count <= 0)
 1164             fatal("Bogus argument to -PU: %s", optarg + 1);
 1165         } else {
 1166           getpts_simple(DEFAULT_UDP_PROBE_PORT_SPEC, SCAN_UDP_PORT, &ports.udp_ping_ports, &ports.udp_ping_count);
 1167           assert(ports.udp_ping_count > 0);
 1168         }
 1169       } else if (*optarg == 'Y') {
 1170         if (ports.sctp_ping_count > 0)
 1171           fatal("Only one -PY option is allowed. Combine port ranges with commas.");
 1172         o.pingtype |= (PINGTYPE_SCTP_INIT);
 1173         if (*(optarg + 1) != '\0') {
 1174           getpts_simple(optarg + 1, SCAN_SCTP_PORT, &ports.sctp_ping_ports, &ports.sctp_ping_count);
 1175           if (ports.sctp_ping_count <= 0)
 1176             fatal("Bogus argument to -PY: %s", optarg + 1);
 1177         } else {
 1178           getpts_simple(DEFAULT_SCTP_PROBE_PORT_SPEC, SCAN_SCTP_PORT, &ports.sctp_ping_ports, &ports.sctp_ping_count);
 1179           assert(ports.sctp_ping_count > 0);
 1180         }
 1181       } else if (*optarg == 'B') {
 1182         if (ports.ack_ping_count > 0)
 1183           fatal("Only one -PB, -PA, or -PT option is allowed. Combine port ranges with commas.");
 1184         o.pingtype = DEFAULT_IPV4_PING_TYPES;
 1185         if (*(optarg + 1) != '\0') {
 1186           getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
 1187           if (ports.ack_ping_count <= 0)
 1188             fatal("Bogus argument to -PB: %s", optarg + 1);
 1189         } else {
 1190           getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
 1191           assert(ports.ack_ping_count > 0);
 1192         }
 1193       } else if (*optarg == 'O') {
 1194         if (ports.proto_ping_count > 0)
 1195           fatal("Only one -PO option is allowed. Combine protocol ranges with commas.");
 1196         o.pingtype |= PINGTYPE_PROTO;
 1197         if (*(optarg + 1) != '\0') {
 1198           getpts_simple(optarg + 1, SCAN_PROTOCOLS, &ports.proto_ping_ports, &ports.proto_ping_count);
 1199           if (ports.proto_ping_count <= 0)
 1200             fatal("Bogus argument to -PO: %s", optarg + 1);
 1201         } else {
 1202           getpts_simple(DEFAULT_PROTO_PROBE_PORT_SPEC, SCAN_PROTOCOLS, &ports.proto_ping_ports, &ports.proto_ping_count);
 1203           assert(ports.proto_ping_count > 0);
 1204         }
 1205       } else {
 1206         fatal("Illegal Argument to -P, use -Pn, -PE, -PS, -PA, -PP, -PM, -PU, -PY, or -PO");
 1207       }
 1208       break;
 1209     case 'p':
 1210       if (o.portlist)
 1211         fatal("Only 1 -p option allowed, separate multiple ranges with commas.");
 1212       o.portlist = strdup(optarg);
 1213       break;
 1214     case 'R':
 1215       o.always_resolve = true;
 1216       break;
 1217     case 'r':
 1218       o.randomize_ports = false;
 1219       break;
 1220     case 'S':
 1221       if (o.spoofsource)
 1222         fatal("You can only use the source option once!  Use -D <decoy1> -D <decoy2> etc. for decoys\n");
 1223       delayed_options.spoofSource = strdup(optarg);
 1224       delayed_options.raw_scan_options = true;
 1225       o.spoofsource = true;
 1226       break;
 1227     case 's':
 1228       if (!optarg || !*optarg) {
 1229         printusage();
 1230         error("An option is required for -s, most common are -sT (tcp scan), -sS (SYN scan), -sF (FIN scan), -sU (UDP scan) and -sn (Ping scan)");
 1231         exit(-1);
 1232       }
 1233       p = optarg;
 1234       while (*p) {
 1235         switch (*p) {
 1236         case 'P':
 1237           delayed_options.warn_deprecated("sP", "sn");
 1238         case 'n':
 1239           o.noportscan = true;
 1240           break;
 1241         case 'A':
 1242           o.ackscan = true;
 1243           break;
 1244         case 'B':
 1245           fatal("No scan type 'B', did you mean bounce scan (-b)?");
 1246           break;
 1247 #ifndef NOLUA
 1248         case 'C':
 1249           o.script = true;
 1250           break;
 1251 #endif
 1252         case 'F':
 1253           o.finscan = 1;
 1254           break;
 1255         case 'L':
 1256           o.listscan = true;
 1257           o.noportscan = true;
 1258           o.pingtype |= PINGTYPE_NONE;
 1259           break;
 1260         case 'M':
 1261           o.maimonscan = 1;
 1262           break;
 1263         case 'N':
 1264           o.nullscan = 1;
 1265           break;
 1266         case 'O':
 1267           o.ipprotscan = 1;
 1268           break;
 1269           /* Alias for -sV since March 2011. */
 1270         case 'R':
 1271           o.servicescan = true;
 1272           delayed_options.warn_deprecated("sR", "sV");
 1273           error("WARNING: -sR is now an alias for -sV and activates version detection as well as RPC scan.");
 1274           break;
 1275         case 'S':
 1276           o.synscan = 1;
 1277           break;
 1278         case 'T':
 1279           o.connectscan = 1;
 1280           break;
 1281         case 'U':
 1282           o.udpscan++;
 1283           break;
 1284         case 'V':
 1285           o.servicescan = true;
 1286           break;
 1287         case 'W':
 1288           o.windowscan = 1;
 1289           break;
 1290         case 'X':
 1291           o.xmasscan++;
 1292           break;
 1293         case 'Y':
 1294           o.sctpinitscan = 1;
 1295           break;
 1296         case 'Z':
 1297           o.sctpcookieechoscan = 1;
 1298           break;
 1299         default:
 1300           printusage();
 1301           error("Scantype %c not supported\n", *p);
 1302           exit(-1);
 1303           break;
 1304         }
 1305         p++;
 1306       }
 1307       break;
 1308     case 'T':
 1309       p=optarg+1;*p=*p>'5'?*p:*(p-1)!=*p?'\0':*(p-1)='\0'==(*p-'1')?(error("%s",(char*)(k+8)),'5'):*p;
 1310       if (*optarg == '0' || (strcasecmp(optarg, "Paranoid") == 0)) {
 1311         o.timing_level = 0;
 1312         o.max_parallelism = 1;
 1313         o.scan_delay = 300000;
 1314         o.setInitialRttTimeout(300000);
 1315       } else if (*optarg == '1' || (strcasecmp(optarg, "Sneaky") == 0)) {
 1316         o.timing_level = 1;
 1317         o.max_parallelism = 1;
 1318         o.scan_delay = 15000;
 1319         o.setInitialRttTimeout(15000);
 1320       } else if (*optarg == '2' || (strcasecmp(optarg, "Polite") == 0)) {
 1321         o.timing_level = 2;
 1322         o.max_parallelism = 1;
 1323         o.scan_delay = 400;
 1324       } else if (*optarg == '3' || (strcasecmp(optarg, "Normal") == 0)) {
 1325         // Default timing, see NmapOps.cc
 1326       } else if (*optarg == '4' || (strcasecmp(optarg, "Aggressive") == 0)) {
 1327         o.timing_level = 4;
 1328         o.setMinRttTimeout(100);
 1329         o.setMaxRttTimeout(1250);
 1330         o.setInitialRttTimeout(500);
 1331         o.setMaxTCPScanDelay(10);
 1332         o.setMaxSCTPScanDelay(10);
 1333         o.setMaxRetransmissions(6);
 1334       } else if (*optarg == '5' || (strcasecmp(optarg, "Insane") == 0)) {
 1335         o.timing_level = 5;
 1336         o.setMinRttTimeout(50);
 1337         o.setMaxRttTimeout(300);
 1338         o.setInitialRttTimeout(250);
 1339         o.host_timeout = 900000;
 1340         o.setMaxTCPScanDelay(5);
 1341         o.setMaxSCTPScanDelay(5);
 1342         o.setMaxRetransmissions(2);
 1343 #ifndef NOLUA
 1344         o.scripttimeout = 600; // 10 minutes
 1345 #endif
 1346       } else {
 1347         fatal("Unknown timing mode (-T argument).  Use either \"Paranoid\", \"Sneaky\", \"Polite\", \"Normal\", \"Aggressive\", \"Insane\" or a number from 0 (Paranoid) to 5 (Insane)");
 1348       }
 1349       break;
 1350     case 'V':
 1351 #ifdef WIN32
 1352       /* For pcap_get_version, since we need to get the correct Npcap/WinPcap
 1353        * DLL loaded */
 1354       win_init();
 1355 #endif
 1356       display_nmap_version();
 1357       exit(0);
 1358       break;
 1359     case 'v':
 1360       if (optarg && isdigit(optarg[0])) {
 1361         int i = atoi(optarg);
 1362         o.verbose = box(0, 10, i);
 1363         if (o.verbose == 0) {
 1364           o.nmap_stdout = fopen(DEVNULL, "w");
 1365           if (!o.nmap_stdout)
 1366             fatal("Could not assign %s to stdout for writing", DEVNULL);
 1367         }
 1368       } else {
 1369         const char *p;
 1370         if (o.verbose < 10) o.verbose++;
 1371         for (p = optarg != NULL ? optarg : ""; *p == 'v'; p++)
 1372           if (o.verbose < 10) o.verbose++;
 1373         if (*p != '\0')
 1374           fatal("Invalid argument to -v: \"%s\".", optarg);
 1375       }
 1376       break;
 1377     }
 1378   }
 1379 
 1380 }
 1381 
 1382 void  apply_delayed_options() {
 1383   int i;
 1384   char tbuf[128];
 1385   struct sockaddr_storage ss;
 1386   size_t sslen;
 1387 
 1388   // Default IPv4
 1389   o.setaf(delayed_options.af == AF_UNSPEC ? AF_INET : delayed_options.af);
 1390 
 1391   if (o.verbose > 0) {
 1392     for (std::vector<std::string>::iterator it = delayed_options.verbose_out.begin(); it != delayed_options.verbose_out.end(); ++it) {
 1393       error("%s", it->c_str());
 1394     }
 1395   }
 1396   delayed_options.verbose_out.clear();
 1397 
 1398   if (delayed_options.advanced) {
 1399     o.servicescan = true;
 1400 #ifndef NOLUA
 1401     o.script = true;
 1402 #endif
 1403     if (o.isr00t) {
 1404       o.osscan = true;
 1405       o.traceroute = true;
 1406     }
 1407   }
 1408   if (o.spoofsource) {
 1409     int rc = resolve(delayed_options.spoofSource, 0, &ss, &sslen, o.af());
 1410     if (rc != 0) {
 1411       fatal("Failed to resolve/decode supposed %s source address \"%s\": %s",
 1412         (o.af() == AF_INET) ? "IPv4" : "IPv6", delayed_options.spoofSource,
 1413         gai_strerror(rc));
 1414     }
 1415     o.setSourceSockAddr(&ss, sslen);
 1416   }
 1417   // After the arguments are fully processed we now make any of the timing
 1418   // tweaks the user might've specified:
 1419   if (delayed_options.pre_max_parallelism != -1)
 1420     o.max_parallelism = delayed_options.pre_max_parallelism;
 1421   if (delayed_options.pre_scan_delay != -1) {
 1422     o.scan_delay = delayed_options.pre_scan_delay;
 1423     if (o.scan_delay > o.maxTCPScanDelay())
 1424       o.setMaxTCPScanDelay(o.scan_delay);
 1425     if (o.scan_delay > o.maxUDPScanDelay())
 1426       o.setMaxUDPScanDelay(o.scan_delay);
 1427     if (o.scan_delay > o.maxSCTPScanDelay())
 1428       o.setMaxSCTPScanDelay(o.scan_delay);
 1429     if (delayed_options.pre_max_parallelism != -1 || o.min_parallelism != 0)
 1430       error("Warning: --min-parallelism and --max-parallelism are ignored with --scan-delay.");
 1431   }
 1432   if (delayed_options.pre_max_scan_delay != -1) {
 1433     o.setMaxTCPScanDelay(delayed_options.pre_max_scan_delay);
 1434     o.setMaxUDPScanDelay(delayed_options.pre_max_scan_delay);
 1435     o.setMaxSCTPScanDelay(delayed_options.pre_max_scan_delay);
 1436   }
 1437   if (delayed_options.pre_init_rtt_timeout != -1)
 1438     o.setInitialRttTimeout(delayed_options.pre_init_rtt_timeout);
 1439   if (delayed_options.pre_min_rtt_timeout != -1)
 1440     o.setMinRttTimeout(delayed_options.pre_min_rtt_timeout);
 1441   if (delayed_options.pre_max_rtt_timeout != -1)
 1442     o.setMaxRttTimeout(delayed_options.pre_max_rtt_timeout);
 1443   if (delayed_options.pre_max_retries != -1)
 1444     o.setMaxRetransmissions(delayed_options.pre_max_retries);
 1445   if (delayed_options.pre_host_timeout != -1)
 1446     o.host_timeout = delayed_options.pre_host_timeout;
 1447 #ifndef NOLUA
 1448   if (delayed_options.pre_scripttimeout != -1)
 1449     o.scripttimeout = delayed_options.pre_scripttimeout;
 1450 #endif
 1451 
 1452 
 1453   if (o.osscan) {
 1454     if (o.af() == AF_INET)
 1455         o.reference_FPs = parse_fingerprint_reference_file("nmap-os-db");
 1456     else if (o.af() == AF_INET6)
 1457         o.os_labels_ipv6 = load_fp_matches();
 1458   }
 1459 
 1460   // Must check and change this before validate_scan_lists
 1461   if (o.pingtype & PINGTYPE_NONE)
 1462     o.pingtype = PINGTYPE_NONE;
 1463 
 1464   validate_scan_lists(ports, o);
 1465   o.ValidateOptions();
 1466 
 1467   // print ip options
 1468   if ((o.debugging || o.packetTrace()) && o.ipoptionslen) {
 1469     char buf[256]; // 256 > 5*40
 1470     bintohexstr(buf, sizeof(buf), (char*) o.ipoptions, o.ipoptionslen);
 1471     if (o.ipoptionslen >= 8)       // at least one ip address
 1472       log_write(LOG_STDOUT, "Binary ip options to be send:\n%s", buf);
 1473     log_write(LOG_STDOUT, "Parsed ip options to be send:\n%s\n",
 1474               format_ip_options(o.ipoptions, o.ipoptionslen));
 1475   }
 1476 
 1477   /* Open the log files, now that we know whether the user wants them appended
 1478      or overwritten */
 1479   if (delayed_options.normalfilename) {
 1480     log_open(LOG_NORMAL, o.append_output, delayed_options.normalfilename);
 1481     free(delayed_options.normalfilename);
 1482   }
 1483   if (delayed_options.machinefilename) {
 1484     log_open(LOG_MACHINE, o.append_output, delayed_options.machinefilename);
 1485     free(delayed_options.machinefilename);
 1486   }
 1487   if (delayed_options.kiddiefilename) {
 1488     log_open(LOG_SKID, o.append_output, delayed_options.kiddiefilename);
 1489     free(delayed_options.kiddiefilename);
 1490   }
 1491   if (delayed_options.xmlfilename) {
 1492     log_open(LOG_XML, o.append_output, delayed_options.xmlfilename);
 1493     free(delayed_options.xmlfilename);
 1494   }
 1495 
 1496   if (o.verbose > 1)
 1497     o.reason = true;
 1498 
 1499   // ISO 8601 date/time -- http://www.cl.cam.ac.uk/~mgk25/iso-time.html
 1500   if (strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M %Z", &local_time) <= 0)
 1501     fatal("Unable to properly format time");
 1502   log_write(LOG_STDOUT | LOG_SKID, "Starting %s %s ( %s ) at %s\n", NMAP_NAME, NMAP_VERSION, NMAP_URL, tbuf);
 1503   if (o.verbose) {
 1504     if (local_time.tm_mon == 8 && local_time.tm_mday == 1) {
 1505       unsigned int a = (local_time.tm_year - 97)%100;
 1506       log_write(LOG_STDOUT | LOG_SKID, "Happy %d%s Birthday to Nmap, may it live to be %d!\n", local_time.tm_year - 97,(a>=11&&a<=13?"th":(a%10==1?"st":(a%10==2?"nd":(a%10==3?"rd":"th")))), local_time.tm_year + 3);
 1507     } else if (local_time.tm_mon == 11 && local_time.tm_mday == 25) {
 1508       log_write(LOG_STDOUT | LOG_SKID, "Nmap wishes you a merry Christmas! Specify -sX for Xmas Scan (https://nmap.org/book/man-port-scanning-techniques.html).\n");
 1509     }
 1510   }
 1511 
 1512 #ifndef NOLUA
 1513   if (o.scripthelp) {
 1514     /* Special-case open_nse for --script-help only. */
 1515     open_nse();
 1516     exit(0);
 1517   }
 1518 #endif
 1519 
 1520   if (o.traceroute && !o.isr00t)
 1521     fatal("Traceroute has to be run as root");
 1522   if (o.traceroute && o.idlescan)
 1523     fatal("Traceroute does not support idle scan");
 1524 
 1525   if ((o.noportscan) && (o.portlist || o.fastscan))
 1526     fatal("You cannot use -F (fast scan) or -p (explicit port selection) when not doing a port scan");
 1527 
 1528   if (o.portlist && o.fastscan)
 1529     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");
 1530 
 1531   if (o.ipprotscan) {
 1532     if (o.portlist)
 1533       getpts(o.portlist, &ports);
 1534     else
 1535       getpts((char *) (o.fastscan ? "[P:0-]" : "0-"), &ports);  // Default protocols to scan
 1536   } else if (!o.noportscan) {
 1537     if (o.portlist) {
 1538       for (const char *p=o.portlist; *p != '\0'; p++) {
 1539         if (*(p+1) == ':') {
 1540           switch(*p) {
 1541             case 'T':
 1542               if (!o.TCPScan()) {
 1543                 error("WARNING: Your ports include \"T:\" but you haven't specified any TCP scan type.");
 1544               }
 1545               break;
 1546             case 'U':
 1547               if (!o.UDPScan()) {
 1548                 error("WARNING: Your ports include \"U:\" but you haven't specified UDP scan with -sU.");
 1549               }
 1550               break;
 1551             case 'S':
 1552               if (!o.SCTPScan()) {
 1553                 error("WARNING: Your ports include \"S:\" but you haven't specified any SCTP scan type.");
 1554               }
 1555               break;
 1556             case 'P':
 1557               if (!o.ipprotscan) {
 1558                 error("WARNING: Your ports include \"P:\" but you haven't specified IP Protocol scan with -sO.");
 1559               }
 1560               break;
 1561             default:
 1562               break;
 1563           }
 1564         }
 1565       }
 1566     }
 1567     gettoppts(o.topportlevel, o.portlist, &ports, o.exclude_portlist);
 1568   }
 1569 
 1570   // Uncomment the following line to use the common lisp port spec test suite
 1571   //printf("port spec: (%d %d %d %d)\n", ports.tcp_count, ports.udp_count, ports.sctp_count, ports.prot_count); exit(0);
 1572 
 1573 #ifdef WIN32
 1574   if (o.sendpref & PACKET_SEND_IP) {
 1575     error("WARNING: raw IP (rather than raw ethernet) packet sending attempted on Windows. This probably won't work.  Consider --send-eth next time.");
 1576   }
 1577 #endif
 1578   if (delayed_options.spoofmac) {
 1579     u8 mac_data[6];
 1580     int pos = 0; /* Next index of mac_data to fill in */
 1581     char tmphex[3];
 1582     /* A zero means set it all randomly.  Anything that is all digits
 1583        or colons is treated as a prefix, with remaining characters for
 1584        the 6-byte MAC (if any) chosen randomly.  Otherwise, it is
 1585        treated as a vendor string for lookup in nmap-mac-prefixes */
 1586     if (strcmp(delayed_options.spoofmac, "0") == 0) {
 1587       pos = 0;
 1588     } else {
 1589       const char *p = delayed_options.spoofmac;
 1590       while (*p) {
 1591         if (*p == ':')
 1592           p++;
 1593         if (isxdigit((int) (unsigned char) *p) && isxdigit((int) (unsigned char) * (p + 1))) {
 1594           if (pos >= 6)
 1595             fatal("Bogus --spoof-mac value encountered (%s) -- only up to 6 bytes permitted", delayed_options.spoofmac);
 1596           tmphex[0] = *p;
 1597           tmphex[1] = *(p + 1);
 1598           tmphex[2] = '\0';
 1599           mac_data[pos] = (u8) strtol(tmphex, NULL, 16);
 1600           pos++;
 1601           p += 2;
 1602         } else break;
 1603       }
 1604       if (*p) {
 1605         /* Failed to parse it as a MAC prefix -- treating as a vendor substring instead */
 1606         if (!MACCorp2Prefix(delayed_options.spoofmac, mac_data))
 1607           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.", delayed_options.spoofmac);
 1608         pos = 3;
 1609       }
 1610     }
 1611     if (pos < 6) {
 1612       get_random_bytes(mac_data + pos, 6 - pos);
 1613     }
 1614     /* Got the new MAC! */
 1615     const char *vend = MACPrefix2Corp(mac_data);
 1616     log_write(LOG_PLAIN,
 1617               "Spoofing MAC address %02X:%02X:%02X:%02X:%02X:%02X (%s)\n",
 1618               mac_data[0], mac_data[1], mac_data[2], mac_data[3], mac_data[4],
 1619               mac_data[5], vend ? vend : "No registered vendor");
 1620     o.setSpoofMACAddress(mac_data);
 1621 
 1622     /* If they want to spoof the MAC address, we should at least make
 1623        some effort to actually send raw ethernet frames rather than IP
 1624        packets (which would use the real IP */
 1625     if (o.sendpref != PACKET_SEND_IP_STRONG)
 1626       o.sendpref = PACKET_SEND_ETH_STRONG;
 1627   }
 1628 
 1629   /* Warn if setuid/setgid. */
 1630   check_setugid();
 1631 
 1632   /* Remove any ports that are in the exclusion list */
 1633   removepts(o.exclude_portlist, &ports);
 1634 
 1635   /* By now, we've got our port lists.  Give the user a warning if no
 1636    * ports are specified for the type of scan being requested.  Other things
 1637    * (such as OS ident scan) might break cause no ports were specified,  but
 1638    * we've given our warning...
 1639    */
 1640   if ((o.TCPScan()) && ports.tcp_count == 0)
 1641     error("WARNING: a TCP scan type was requested, but no tcp ports were specified.  Skipping this scan type.");
 1642   if (o.SCTPScan() && ports.sctp_count == 0)
 1643     error("WARNING: a SCTP scan type was requested, but no sctp ports were specified.  Skipping this scan type.");
 1644   if (o.UDPScan() && ports.udp_count == 0)
 1645     error("WARNING: UDP scan was requested, but no udp ports were specified.  Skipping this scan type.");
 1646   if (o.ipprotscan && ports.prot_count == 0)
 1647     error("WARNING: protocol scan was requested, but no protocols were specified to be scanned.  Skipping this scan type.");
 1648 
 1649   if (o.pingtype & PINGTYPE_TCP && ports.syn_ping_count+ports.ack_ping_count == 0)
 1650     error("WARNING: a TCP ping scan was requested, but after excluding requested TCP ports, none remain. Skipping this scan type.");
 1651   if (o.pingtype & PINGTYPE_UDP && ports.udp_ping_count == 0)
 1652     error("WARNING: a UDP ping scan was requested, but after excluding requested UDP ports, none remain. Skipping this scan type.");
 1653   if (o.pingtype & PINGTYPE_SCTP_INIT && ports.sctp_ping_count == 0)
 1654     error("WARNING: a SCTP ping scan was requested, but after excluding requested SCTP ports, none remain. Skipping this scan type.");
 1655   if (o.pingtype & PINGTYPE_PROTO && ports.proto_ping_count == 0)
 1656     error("WARNING: a IP Protocol ping scan was requested, but after excluding requested protocols, none remain. Skipping this scan type.");
 1657 
 1658 
 1659   /* We need to find what interface to route through if:
 1660    * --None have been specified AND
 1661    * --We are root and doing tcp ping OR
 1662    * --We are doing a raw sock scan and NOT pinging anyone */
 1663   if (o.SourceSockAddr() && !*o.device) {
 1664     if (ipaddr2devname(o.device, o.SourceSockAddr()) != 0) {
 1665       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 kind of fishy.");
 1666     }
 1667   }
 1668 
 1669   if (*o.device && !o.SourceSockAddr()) {
 1670     struct sockaddr_storage tmpsock;
 1671     memset(&tmpsock, 0, sizeof(tmpsock));
 1672     if (devname2ipaddr(o.device, &tmpsock) == -1) {
 1673       fatal("I cannot figure out what source address to use for device %s, does it even exist?", o.device);
 1674     }
 1675     o.setSourceSockAddr(&tmpsock, sizeof(tmpsock));
 1676   }
 1677 
 1678   if (delayed_options.exclude_file) {
 1679     o.excludefd = fopen(delayed_options.exclude_file, "r");
 1680     if (!o.excludefd)
 1681       fatal("Failed to open exclude file %s for reading", delayed_options.exclude_file);
 1682     free(delayed_options.exclude_file);
 1683   }
 1684   o.exclude_spec = delayed_options.exclude_spec;
 1685 
 1686   if (delayed_options.decoy_arguments) {
 1687     char *p = delayed_options.decoy_arguments, *q;
 1688     do {
 1689       q = strchr(p, ',');
 1690       if (q)
 1691         *q = '\0';
 1692       if (!strcasecmp(p, "me")) {
 1693         if (o.decoyturn != -1)
 1694           fatal("Can only use 'ME' as a decoy once.\n");
 1695         o.decoyturn = o.numdecoys++;
 1696       } else if (!strcasecmp(p, "rnd") || !strncasecmp(p, "rnd:", 4)) {
 1697         if (delayed_options.af == AF_INET6)
 1698           fatal("Random decoys can only be used with IPv4");
 1699         int i = 1;
 1700 
 1701         /* 'rnd:' is allowed and just gives them one */
 1702         if (strlen(p) > 4)
 1703           i = atoi(&p[4]);
 1704 
 1705         if (i < 1)
 1706           fatal("Bad 'rnd' decoy \"%s\"", p);
 1707 
 1708         if (o.numdecoys + i >= MAX_DECOYS - 1)
 1709           fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
 1710 
 1711         while (i--) {
 1712           do {
 1713             ((struct sockaddr_in *)&o.decoys[o.numdecoys])->sin_addr.s_addr = get_random_u32();
 1714           } while (ip_is_reserved(&((struct sockaddr_in *)&o.decoys[o.numdecoys])->sin_addr));
 1715           o.numdecoys++;
 1716         }
 1717       } else {
 1718         if (o.numdecoys >= MAX_DECOYS - 1)
 1719           fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
 1720 
 1721         /* Try to resolve it */
 1722         struct sockaddr_storage decoytemp;
 1723         size_t decoytemplen = sizeof(struct sockaddr_storage);
 1724         int rc;
 1725         if (delayed_options.af == AF_INET6){
 1726           rc = resolve(p, 0, (sockaddr_storage*)&decoytemp, &decoytemplen, AF_INET6);
 1727         }
 1728         else
 1729           rc = resolve(p, 0, (sockaddr_storage*)&decoytemp, &decoytemplen, AF_INET);
 1730         if (rc != 0)
 1731           fatal("Failed to resolve decoy host \"%s\": %s", p, gai_strerror(rc));
 1732         o.decoys[o.numdecoys] = decoytemp;
 1733         o.numdecoys++;
 1734       }
 1735       if (q) {
 1736         *q = ',';
 1737         p = q + 1;
 1738       }
 1739     } while (q);
 1740   }
 1741   /* Set up host address also in array of decoys! */
 1742   if (o.decoyturn == -1) {
 1743     o.decoyturn = (o.numdecoys == 0) ?  0 : get_random_uint() % o.numdecoys;
 1744     o.numdecoys++;
 1745     for (i = o.numdecoys - 1; i > o.decoyturn; i--)
 1746       o.decoys[i] = o.decoys[i - 1];
 1747   }
 1748 
 1749   if (delayed_options.raw_scan_options && (!o.isr00t || o.connectscan)) {
 1750     error("You have specified some options that require raw socket access.\n"
 1751           "These options will not be honored %s.",
 1752           o.isr00t ? "for TCP Connect scan" : "without the necessary privileges");
 1753   }
 1754 }
 1755 
 1756 // Free some global memory allocations.
 1757 // This is used for detecting memory leaks.
 1758 void nmap_free_mem() {
 1759   PortList::freePortMap();
 1760   cp_free();
 1761   free_services();
 1762   AllProbes::service_scan_free();
 1763   traceroute_hop_cache_clear();
 1764   nsock_set_default_engine(NULL);
 1765 }
 1766 
 1767 int nmap_main(int argc, char *argv[]) {
 1768   int i;
 1769   std::vector<Target *> Targets;
 1770   time_t now;
 1771   struct hostent *target = NULL;
 1772   time_t timep;
 1773   char mytime[128];
 1774   struct addrset *exclude_group;
 1775 #ifndef NOLUA
 1776   /* Only NSE scripts can add targets */
 1777   NewTargets *new_targets = NULL;
 1778   /* Pre-Scan and Post-Scan script results datastructure */
 1779   ScriptResults *script_scan_results = NULL;
 1780 #endif
 1781   unsigned int ideal_scan_group_sz = 0;
 1782   Target *currenths;
 1783   char myname[FQDN_LEN + 1];
 1784   int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
 1785                                 source addresses? */
 1786   unsigned int targetno;
 1787   char hostname[FQDN_LEN + 1] = "";
 1788   struct sockaddr_storage ss;
 1789   size_t sslen;
 1790   int err;
 1791 
 1792 #ifdef LINUX
 1793   /* Check for WSL and warn that things may not go well. */
 1794   struct utsname uts;
 1795   if (!uname(&uts)) {
 1796     if (strstr(uts.release, "Microsoft") != NULL) {
 1797       error("Warning: %s may not work correctly on Windows Subsystem for Linux.\n"
 1798           "For best performance and accuracy, use the native Windows build from %s/download.html#windows.",
 1799           NMAP_NAME, NMAP_URL);
 1800     }
 1801   }
 1802 #endif
 1803 
 1804   tzset();
 1805   now = time(NULL);
 1806   err = n_localtime(&now, &local_time);
 1807   if (err) {
 1808     fatal("n_localtime failed: %s", strerror(err));
 1809   }
 1810 
 1811   if (argc < 2){
 1812     printusage();
 1813     exit(-1);
 1814   }
 1815 
 1816   Targets.reserve(100);
 1817 #ifdef WIN32
 1818   win_pre_init();
 1819 #endif
 1820 
 1821   parse_options(argc, argv);
 1822 
 1823   if (o.debugging)
 1824     nbase_set_log(fatal, error);
 1825   else
 1826     nbase_set_log(fatal, NULL);
 1827 
 1828 
 1829   tty_init(); // Put the keyboard in raw mode
 1830 
 1831 #ifdef WIN32
 1832   // Must come after parse_options because of --unprivileged
 1833   // Must come before apply_delayed_options because it sets o.isr00t
 1834   win_init();
 1835 #endif
 1836 
 1837   apply_delayed_options();
 1838 
 1839   for (unsigned int i = 0; i < route_dst_hosts.size(); i++) {
 1840     const char *dst;
 1841     struct sockaddr_storage ss;
 1842     struct route_nfo rnfo;
 1843     size_t sslen;
 1844     int rc;
 1845 
 1846     dst = route_dst_hosts[i].c_str();
 1847     rc = resolve(dst, 0, &ss, &sslen, o.af());
 1848     if (rc != 0)
 1849       fatal("Can't resolve %s: %s.", dst, gai_strerror(rc));
 1850 
 1851     printf("%s\n", inet_ntop_ez(&ss, sslen));
 1852 
 1853     if (!route_dst(&ss, &rnfo, o.device, o.SourceSockAddr())) {
 1854       printf("Can't route %s (%s).", dst, inet_ntop_ez(&ss, sslen));
 1855     } else {
 1856       printf("%s %s", rnfo.ii.devname, rnfo.ii.devfullname);
 1857       printf(" srcaddr %s", inet_ntop_ez(&rnfo.srcaddr, sizeof(rnfo.srcaddr)));
 1858       if (rnfo.direct_connect)
 1859         printf(" direct");
 1860       else
 1861         printf(" nexthop %s", inet_ntop_ez(&rnfo.nexthop, sizeof(rnfo.nexthop)));
 1862     }
 1863     printf("\n");
 1864   }
 1865   route_dst_hosts.clear();
 1866 
 1867   if (delayed_options.iflist) {
 1868     print_iflist();
 1869     exit(0);
 1870   }
 1871 
 1872   /* If he wants to bounce off of an FTP site, that site better damn well be reachable! */
 1873   if (o.bouncescan) {
 1874     if (!inet_pton(AF_INET, ftp.server_name, &ftp.server)) {
 1875       if ((target = gethostbyname(ftp.server_name)))
 1876         memcpy(&ftp.server, target->h_addr_list[0], 4);
 1877       else {
 1878         fatal("Failed to resolve FTP bounce proxy hostname/IP: %s",
 1879               ftp.server_name);
 1880       }
 1881     } else if (o.verbose) {
 1882       log_write(LOG_STDOUT, "Resolved FTP bounce attack proxy to %s (%s).\n",
 1883                 ftp.server_name, inet_ntoa(ftp.server));
 1884     }
 1885   }
 1886   fflush(stdout);
 1887   fflush(stderr);
 1888 
 1889   timep = time(NULL);
 1890   err = n_ctime(mytime, sizeof(mytime), &timep);
 1891   if (err) {
 1892     fatal("n_ctime failed: %s", strerror(err));
 1893   }
 1894   chomp(mytime);
 1895 
 1896   if (!o.resuming) {
 1897     /* Brief info in case they forget what was scanned */
 1898     char *xslfname = o.XSLStyleSheet();
 1899     xml_start_document("nmaprun");
 1900     if (xslfname) {
 1901       xml_open_pi("xml-stylesheet");
 1902       xml_attribute("href", "%s", xslfname);
 1903       xml_attribute("type", "text/xsl");
 1904       xml_close_pi();
 1905       xml_newline();
 1906     }
 1907 
 1908     xml_start_comment();
 1909     xml_write_escaped(" %s %s scan initiated %s as: %s ", NMAP_NAME, NMAP_VERSION, mytime, join_quoted(argv, argc).c_str());
 1910     xml_end_comment();
 1911     xml_newline();
 1912 
 1913     xml_open_start_tag("nmaprun");
 1914     xml_attribute("scanner", "nmap");
 1915     xml_attribute("args", "%s", join_quoted(argv, argc).c_str());
 1916     xml_attribute("start", "%lu", (unsigned long) timep);
 1917     xml_attribute("startstr", "%s", mytime);
 1918     xml_attribute("version", "%s", NMAP_VERSION);
 1919     xml_attribute("xmloutputversion", NMAP_XMLOUTPUTVERSION);
 1920     xml_close_start_tag();
 1921     xml_newline();
 1922 
 1923     output_xml_scaninfo_records(&ports);
 1924 
 1925     xml_open_start_tag("verbose");
 1926     xml_attribute("level", "%d", o.verbose);
 1927     xml_close_empty_tag();
 1928     xml_newline();
 1929     xml_open_start_tag("debugging");
 1930     xml_attribute("level", "%d", o.debugging);
 1931     xml_close_empty_tag();
 1932     xml_newline();
 1933   } else {
 1934     xml_start_tag("nmaprun", false);
 1935   }
 1936 
 1937   log_write(LOG_NORMAL | LOG_MACHINE, "# ");
 1938   log_write(LOG_NORMAL | LOG_MACHINE, "%s %s scan initiated %s as: %s", NMAP_NAME, NMAP_VERSION, mytime, join_quoted(argv, argc).c_str());
 1939   log_write(LOG_NORMAL | LOG_MACHINE, "\n");
 1940 
 1941   /* Before we randomize the ports scanned, lets output them to machine
 1942      parseable output */
 1943   if (o.verbose)
 1944     output_ports_to_machine_parseable_output(&ports);
 1945 
 1946 #if defined(HAVE_SIGNAL) && defined(SIGPIPE)
 1947   signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
 1948                                of it, but we really shouldn't get an unexpected
 1949                                SIGPIPE */
 1950 #endif
 1951 
 1952   if (o.max_parallelism && (i = max_sd()) && i < o.max_parallelism) {
 1953     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);
 1954   }
 1955 
 1956   if (o.debugging > 1)
 1957     log_write(LOG_STDOUT, "The max # of sockets we are using is: %d\n", o.max_parallelism);
 1958 
 1959   // At this point we should fully know our timing parameters
 1960   if (o.debugging) {
 1961     log_write(LOG_PLAIN, "--------------- Timing report ---------------\n");
 1962     log_write(LOG_PLAIN, "  hostgroups: min %d, max %d\n", o.minHostGroupSz(), o.maxHostGroupSz());
 1963     log_write(LOG_PLAIN, "  rtt-timeouts: init %d, min %d, max %d\n", o.initialRttTimeout(), o.minRttTimeout(), o.maxRttTimeout());
 1964     log_write(LOG_PLAIN, "  max-scan-delay: TCP %d, UDP %d, SCTP %d\n", o.maxTCPScanDelay(), o.maxUDPScanDelay(), o.maxSCTPScanDelay());
 1965     log_write(LOG_PLAIN, "  parallelism: min %d, max %d\n", o.min_parallelism, o.max_parallelism);
 1966     log_write(LOG_PLAIN, "  max-retries: %d, host-timeout: %ld\n", o.getMaxRetransmissions(), o.host_timeout);
 1967     log_write(LOG_PLAIN, "  min-rate: %g, max-rate: %g\n", o.min_packet_send_rate, o.max_packet_send_rate);
 1968     log_write(LOG_PLAIN, "---------------------------------------------\n");
 1969   }
 1970 
 1971   /* Before we randomize the ports scanned, we must initialize PortList class. */
 1972   if (o.ipprotscan)
 1973     PortList::initializePortMap(IPPROTO_IP,  ports.prots, ports.prot_count);
 1974   if (o.TCPScan())
 1975     PortList::initializePortMap(IPPROTO_TCP, ports.tcp_ports, ports.tcp_count);
 1976   if (o.UDPScan())
 1977     PortList::initializePortMap(IPPROTO_UDP, ports.udp_ports, ports.udp_count);
 1978   if (o.SCTPScan())
 1979     PortList::initializePortMap(IPPROTO_SCTP, ports.sctp_ports, ports.sctp_count);
 1980 
 1981   if (o.randomize_ports) {
 1982     if (ports.tcp_count) {
 1983       shortfry(ports.tcp_ports, ports.tcp_count);
 1984       // move a few more common ports closer to the beginning to speed scan
 1985       random_port_cheat(ports.tcp_ports, ports.tcp_count);
 1986     }
 1987     if (ports.udp_count)
 1988       shortfry(ports.udp_ports, ports.udp_count);
 1989     if (ports.sctp_count)
 1990       shortfry(ports.sctp_ports, ports.sctp_count);
 1991     if (ports.prot_count)
 1992       shortfry(ports.prots, ports.prot_count);
 1993   }
 1994 
 1995   exclude_group = addrset_new();
 1996 
 1997   /* lets load our exclude list */
 1998   if (o.excludefd != NULL) {
 1999     load_exclude_file(exclude_group, o.excludefd);
 2000     fclose(o.excludefd);
 2001   }
 2002   if (o.exclude_spec != NULL) {
 2003     load_exclude_string(exclude_group, o.exclude_spec);
 2004   }
 2005 
 2006   if (o.debugging > 3)
 2007     dumpExclude(exclude_group);
 2008 
 2009 #ifndef NOLUA
 2010   if (o.scriptupdatedb) {
 2011     o.max_ips_to_scan = o.numhosts_scanned; // disable warnings?
 2012   }
 2013   if (o.servicescan)
 2014     o.scriptversion = true;
 2015   if (o.scriptversion || o.script || o.scriptupdatedb)
 2016     open_nse();
 2017 
 2018   /* Run the script pre-scanning phase */
 2019   if (o.script) {
 2020     new_targets = NewTargets::get();
 2021     script_scan_results = get_script_scan_results_obj();
 2022     script_scan(Targets, SCRIPT_PRE_SCAN);
 2023     printscriptresults(script_scan_results, SCRIPT_PRE_SCAN);
 2024     while (!script_scan_results->empty()) {
 2025       script_scan_results->front().clear();
 2026       script_scan_results->pop_front();
 2027     }
 2028   }
 2029 #endif
 2030 
 2031   if (o.ping_group_sz < o.minHostGroupSz())
 2032     o.ping_group_sz = o.minHostGroupSz();
 2033   HostGroupState hstate(o.ping_group_sz, o.randomize_hosts, argc, (const char **) argv);
 2034 
 2035   do {
 2036     ideal_scan_group_sz = determineScanGroupSize(o.numhosts_scanned, &ports);
 2037 
 2038     while (Targets.size() < ideal_scan_group_sz) {
 2039       o.current_scantype = HOST_DISCOVERY;
 2040       currenths = nexthost(&hstate, exclude_group, &ports, o.pingtype);
 2041       if (!currenths)
 2042         break;
 2043 
 2044       if (currenths->flags & HOST_UP && !o.listscan)
 2045         o.numhosts_up++;
 2046 
 2047       if ((o.noportscan && !o.traceroute
 2048 #ifndef NOLUA
 2049            && !o.script
 2050 #endif
 2051           ) || o.listscan) {
 2052         /* We're done with the hosts */
 2053         if (currenths->flags & HOST_UP || (o.verbose && !o.openOnly())) {
 2054           xml_start_tag("host");
 2055           write_host_header(currenths);
 2056           printmacinfo(currenths);
 2057           //  if (currenths->flags & HOST_UP)
 2058           //  log_write(LOG_PLAIN,"\n");
 2059           printtimes(currenths);
 2060           xml_end_tag();
 2061           xml_newline();
 2062           log_flush_all();
 2063         }
 2064         delete currenths;
 2065         o.numhosts_scanned++;
 2066         if (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned + Targets.size())
 2067           continue;
 2068         else
 2069           break;
 2070       }
 2071 
 2072       if (o.spoofsource) {
 2073         o.SourceSockAddr(&ss, &sslen);
 2074         currenths->setSourceSockAddr(&ss, sslen);
 2075       }
 2076 
 2077       /* I used to check that !currenths->weird_responses, but in some
 2078          rare cases, such IPs CAN be port successfully scanned and even
 2079          connected to */
 2080       if (!(currenths->flags & HOST_UP)) {
 2081         if (o.verbose && (!o.openOnly() || currenths->ports.hasOpenPorts())) {
 2082           xml_start_tag("host");
 2083           write_host_header(currenths);
 2084           xml_end_tag();
 2085           xml_newline();
 2086         }
 2087         delete currenths;
 2088         o.numhosts_scanned++;
 2089         if (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned + Targets.size())
 2090           continue;
 2091         else
 2092           break;
 2093       }
 2094 
 2095       if (o.RawScan()) {
 2096         if (currenths->SourceSockAddr(NULL, NULL) != 0) {
 2097           if (o.SourceSockAddr(&ss, &sslen) == 0) {
 2098             currenths->setSourceSockAddr(&ss, sslen);
 2099           } else {
 2100             if (gethostname(myname, FQDN_LEN) ||
 2101                 resolve(myname, 0, &ss, &sslen, o.af()) != 0)
 2102               fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
 2103 
 2104             o.setSourceSockAddr(&ss, sslen);
 2105             currenths->setSourceSockAddr(&ss, sslen);
 2106             if (! sourceaddrwarning) {
 2107               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>.",
 2108                     inet_socktop(&ss));
 2109               sourceaddrwarning = 1;
 2110             }
 2111           }
 2112         }
 2113 
 2114         if (!currenths->deviceName())
 2115           fatal("Do not have appropriate device name for target");
 2116 
 2117         /* Hosts in a group need to be somewhat homogeneous. Put this host in
 2118            the next group if necessary. See target_needs_new_hostgroup for the
 2119            details of when we need to split. */
 2120         if (Targets.size() && target_needs_new_hostgroup(&Targets[0], Targets.size(), currenths)) {
 2121           returnhost(&hstate);
 2122           o.numhosts_up--;
 2123           break;
 2124         }
 2125         o.decoys[o.decoyturn] = currenths->source();
 2126       }
 2127       Targets.push_back(currenths);
 2128     }
 2129 
 2130     if (Targets.size() == 0)
 2131       break; /* Couldn't find any more targets */
 2132 
 2133     // Set the variable for status printing
 2134     o.numhosts_scanning = Targets.size();
 2135 
 2136     // Our source must be set in decoy list because nexthost() call can
 2137     // change it (that issue really should be fixed when possible)
 2138     if (o.RawScan())
 2139       o.decoys[o.decoyturn] = Targets[0]->source();
 2140 
 2141     /* I now have the group for scanning in the Targets vector */
 2142 
 2143     if (!o.noportscan) {
 2144       // Ultra_scan sets o.scantype for us so we don't have to worry
 2145       if (o.synscan)
 2146         ultra_scan(Targets, &ports, SYN_SCAN);
 2147 
 2148       if (o.ackscan)
 2149         ultra_scan(Targets, &ports, ACK_SCAN);
 2150 
 2151       if (o.windowscan)
 2152         ultra_scan(Targets, &ports, WINDOW_SCAN);
 2153 
 2154       if (o.finscan)
 2155         ultra_scan(Targets, &ports, FIN_SCAN);
 2156 
 2157       if (o.xmasscan)
 2158         ultra_scan(Targets, &ports, XMAS_SCAN);
 2159 
 2160       if (o.nullscan)
 2161         ultra_scan(Targets, &ports, NULL_SCAN);
 2162 
 2163       if (o.maimonscan)
 2164         ultra_scan(Targets, &ports, MAIMON_SCAN);
 2165 
 2166       if (o.udpscan)
 2167         ultra_scan(Targets, &ports, UDP_SCAN);
 2168 
 2169       if (o.connectscan)
 2170         ultra_scan(Targets, &ports, CONNECT_SCAN);
 2171 
 2172       if (o.sctpinitscan)
 2173         ultra_scan(Targets, &ports, SCTP_INIT_SCAN);
 2174 
 2175       if (o.sctpcookieechoscan)
 2176         ultra_scan(Targets, &ports, SCTP_COOKIE_ECHO_SCAN);
 2177 
 2178       if (o.ipprotscan)
 2179         ultra_scan(Targets, &ports, IPPROT_SCAN);
 2180 
 2181       /* These lame functions can only handle one target at a time */
 2182       if (o.idlescan) {
 2183         for (targetno = 0; targetno < Targets.size(); targetno++) {
 2184           o.current_scantype = IDLE_SCAN;
 2185           keyWasPressed(); // Check if a status message should be printed
 2186           idle_scan(Targets[targetno], ports.tcp_ports,
 2187                     ports.tcp_count, o.idleProxy, &ports);
 2188         }
 2189       }
 2190       if (o.bouncescan) {
 2191         for (targetno = 0; targetno < Targets.size(); targetno++) {
 2192           o.current_scantype = BOUNCE_SCAN;
 2193           keyWasPressed(); // Check if a status message should be printed
 2194           if (ftp.sd <= 0)
 2195             ftp_anon_connect(&ftp);
 2196           if (ftp.sd > 0)
 2197             bounce_scan(Targets[targetno], ports.tcp_ports, ports.tcp_count, &ftp);
 2198         }
 2199       }
 2200 
 2201       if (o.servicescan) {
 2202         o.current_scantype = SERVICE_SCAN;
 2203         service_scan(Targets);
 2204       }
 2205     }
 2206 
 2207     if (o.osscan) {
 2208       OSScan os_engine;
 2209       os_engine.os_scan(Targets);
 2210     }
 2211 
 2212     if (o.traceroute)
 2213       traceroute(Targets);
 2214 
 2215 #ifndef NOLUA
 2216     if (o.script || o.scriptversion) {
 2217       script_scan(Targets, SCRIPT_SCAN);
 2218     }
 2219 #endif
 2220 
 2221     for (targetno = 0; targetno < Targets.size(); targetno++) {
 2222       currenths = Targets[targetno];
 2223       /* Now I can do the output and such for each host */
 2224       if (currenths->timedOut(NULL)) {
 2225         xml_open_start_tag("host");
 2226         xml_attribute("starttime", "%lu", (unsigned long) currenths->StartTime());
 2227         xml_attribute("endtime", "%lu", (unsigned long) currenths->EndTime());
 2228         xml_close_start_tag();
 2229         write_host_header(currenths);
 2230         xml_end_tag(); /* host */
 2231         xml_newline();
 2232         log_write(LOG_PLAIN, "Skipping host %s due to host timeout\n",
 2233                   currenths->NameIP(hostname, sizeof(hostname)));
 2234         log_write(LOG_MACHINE, "Host: %s (%s)\tStatus: Timeout\n",
 2235                   currenths->targetipstr(), currenths->HostName());
 2236       } else {
 2237         /* --open means don't show any hosts without open ports. */
 2238         if (o.openOnly() && !currenths->ports.hasOpenPorts())
 2239           continue;
 2240 
 2241         xml_open_start_tag("host");
 2242         xml_attribute("starttime", "%lu", (unsigned long) currenths->StartTime());
 2243         xml_attribute("endtime", "%lu", (unsigned long) currenths->EndTime());
 2244         xml_close_start_tag();
 2245         write_host_header(currenths);
 2246         printportoutput(currenths, &currenths->ports);
 2247         printmacinfo(currenths);
 2248         printosscanoutput(currenths);
 2249         printserviceinfooutput(currenths);
 2250 #ifndef NOLUA
 2251         printhostscriptresults(currenths);
 2252 #endif
 2253         if (o.traceroute)
 2254           printtraceroute(currenths);
 2255         printtimes(currenths);
 2256         log_write(LOG_PLAIN | LOG_MACHINE, "\n");
 2257         xml_end_tag(); /* host */
 2258         xml_newline();
 2259       }
 2260     }
 2261     log_flush_all();
 2262 
 2263     o.numhosts_scanned += Targets.size();
 2264 
 2265     /* Free all of the Targets */
 2266     while (!Targets.empty()) {
 2267       currenths = Targets.back();
 2268       delete currenths;
 2269       Targets.pop_back();
 2270     }
 2271     o.numhosts_scanning = 0;
 2272   } while (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned);
 2273 
 2274 #ifndef NOLUA
 2275   if (o.script) {
 2276     script_scan(Targets, SCRIPT_POST_SCAN);
 2277     printscriptresults(script_scan_results, SCRIPT_POST_SCAN);
 2278     while (!script_scan_results->empty()) {
 2279       script_scan_results->front().clear();
 2280       script_scan_results->pop_front();
 2281     }
 2282     delete new_targets;
 2283     new_targets = NULL;
 2284   }
 2285 #endif
 2286 
 2287   addrset_free(exclude_group);
 2288 
 2289   if (o.inputfd != NULL)
 2290     fclose(o.inputfd);
 2291 
 2292   printdatafilepaths();
 2293 
 2294   printfinaloutput();
 2295 
 2296   free_scan_lists(&ports);
 2297 
 2298   eth_close_cached();
 2299 
 2300   if (o.release_memory) {
 2301     nmap_free_mem();
 2302   }
 2303   return 0;
 2304 }
 2305 
 2306 /* Reads in a (normal or machine format) Nmap log file and gathers enough
 2307    state to allow Nmap to continue where it left off.  The important things
 2308    it must gather are:
 2309    1) The last host completed
 2310    2) The command arguments
 2311 */
 2312 
 2313 int gather_logfile_resumption_state(char *fname, int *myargc, char ***myargv) {
 2314   char *filestr;
 2315   s64 filelen;
 2316   char nmap_arg_buffer[4096]; /* roughly aligned with arg_parse limit */
 2317   struct sockaddr_storage *lastip = &o.resume_ip;
 2318   int af = AF_INET; // default without -6 is ipv4
 2319   size_t sslen;
 2320   char *p, *q, *found, *lastipstr; /* I love C! */
 2321   /* We mmap it read/write since we will change the last char to a newline if it is not already */
 2322   filestr = mmapfile(fname, &filelen, O_RDWR);
 2323   if (!filestr) {
 2324     pfatal("Could not mmap() %s file", fname);
 2325   }
 2326 
 2327   if (filelen < 20) {
 2328     fatal("Output file %s is too short -- no use resuming", fname);
 2329   }
 2330 
 2331   /* For now we terminate it with a NUL, but we will terminate the file with
 2332      a '\n' later */
 2333   filestr[filelen - 1] = '\0';
 2334 
 2335   /* First goal is to find the nmap args */
 2336   if ((p = strstr(filestr, " as: ")))
 2337     p += 5;
 2338   else
 2339     fatal("Unable to parse supposed log file %s.  Are you sure this is an Nmap output file?", fname);
 2340   /* Skip the program name */
 2341   while (*p && !isspace((int) (unsigned char) *p)){
 2342     if (*p == '"' || *p == '\'') {
 2343       /* Quoted, so find the matching quote.
 2344        * TODO:Doesn't handle escaped quotes, but we don't generate them either. */
 2345       p = strchr(p+1, *p);
 2346       if (!p) {
 2347         fatal("Unable to parse supposed log file %s: unclosed quote.", fname);
 2348       }
 2349     }
 2350     else if (!strncasecmp(p, "&quot;", 6)) {
 2351       /* We do XML unescaping later, but this is just special case of quoted
 2352        * program name. */
 2353       do {
 2354         p = strstr(p+1, "&");
 2355         if (!p) {
 2356           fatal("Unable to parse supposed log file %s: unclosed quote.", fname);
 2357         }
 2358       } while (strncasecmp(p, "&quot;", 6));
 2359       /* Only skip to the ';', because another increment happens below. */
 2360       p += 5;
 2361     }
 2362     p++;
 2363   }
 2364   if (!*p)
 2365     fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2366   p++; /* Skip the space between program name and first arg */
 2367   if (*p == '\n' || !*p)
 2368     fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2369 
 2370   q = strchr(p, '\n');
 2371   if (!q || ((unsigned int) (q - p) >= sizeof(nmap_arg_buffer) - 32))
 2372     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);
 2373 
 2374   strncpy(nmap_arg_buffer, "nmap --append-output ", sizeof(nmap_arg_buffer));
 2375   if ((q - p) + 21 + 1 >= (int) sizeof(nmap_arg_buffer))
 2376     fatal("0verfl0w");
 2377   memcpy(nmap_arg_buffer + 21, p, q - p);
 2378   nmap_arg_buffer[21 + q - p] = '\0';
 2379 
 2380   q = strstr(nmap_arg_buffer, "-->");
 2381   if (q) {
 2382     *q = '\0';
 2383      char *unescaped = xml_unescape(nmap_arg_buffer);
 2384      if (sizeof(nmap_arg_buffer) < strlen(unescaped) + 1)
 2385        fatal("0verfl0w");
 2386      memcpy(nmap_arg_buffer, unescaped, strlen(unescaped) + 1);
 2387      free(unescaped);
 2388   }
 2389 
 2390   if (strstr(nmap_arg_buffer, "--randomize-hosts") != NULL) {
 2391     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");
 2392   }
 2393 
 2394   *myargc = arg_parse(nmap_arg_buffer, myargv);
 2395   if (*myargc == -1) {
 2396     fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2397   }
 2398 
 2399   for (int i=0; i < *myargc; i++) {
 2400     if (!strncmp("-4", (*myargv)[i], 2)) {
 2401       af = AF_INET;
 2402     }
 2403     else if (!strncmp("-6", (*myargv)[i], 2)) {
 2404       af = AF_INET6;
 2405     }
 2406   }
 2407 
 2408   /* Now it is time to figure out the last IP that was scanned */
 2409   q = p;
 2410   found = NULL;
 2411   /* Lets see if its a grepable log first (-oG) */
 2412   while ((q = strstr(q, "\nHost: ")))
 2413     found = q = q + 7;
 2414 
 2415   if (found) {
 2416     q = strchr(found, ' ');
 2417     if (!q)
 2418       fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2419     *q = '\0';
 2420     if (resolve_numeric(found, 0, lastip, &sslen, af) != 0)
 2421       fatal("Unable to parse ip (%s) in supposed log file %s. Sorry", found, fname);
 2422     *q = ' ';
 2423   } else {
 2424     /* Let's see if it's an XML log (-oX) */
 2425     q = p;
 2426     found = NULL;
 2427     while ((q = strstr(q, "\n<address addr=\""))) {
 2428       q += 16;
 2429       found = strchr(q, '"');
 2430       if (!found)
 2431         fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2432       if ((af == AF_INET && !strncmp("\" addrtype=\"ipv4\"", found, 17))
 2433         || (af == AF_INET6 && !strncmp("\" addrtype=\"ipv6\"", found, 17))) {
 2434         found = q;
 2435       }
 2436     }
 2437     if (found) {
 2438       q = strchr(found, '"');
 2439       if (!q)
 2440         fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2441       *q = '\0';
 2442       if (resolve_numeric(found, 0, lastip, &sslen, af) != 0)
 2443         fatal("Unable to parse ip (%s) supposed log file %s.  Sorry", found, fname);
 2444       *q = '"';
 2445     } else {
 2446       /* OK, I guess (hope) it is a normal log then (-oN) */
 2447       q = p;
 2448       found = NULL;
 2449       while ((q = strstr(q, "\nNmap scan report for ")))
 2450         found = q = q + 22;
 2451 
 2452       /*  There may be some later IPs of the form :
 2453           "Nmap scan report for florence (x.x.7.10)" (dns reverse lookup)
 2454           or "Nmap scan report for x.x.7.10".
 2455       */
 2456       if (found) {
 2457         q = strchr(found, '\n');
 2458         if (!q)
 2459           fatal("Unable to parse supposed log file %s.  Sorry", fname);
 2460         *q = '\0';
 2461         p = strchr(found, '(');
 2462         if (!p) { /* No DNS reverse lookup, found should already contain IP */
 2463           lastipstr = strdup(found);
 2464         } else { /* DNS reverse lookup, IP is between parentheses */
 2465           *q = '\n';
 2466           q--;
 2467           *q = '\0';
 2468           lastipstr = strdup(p + 1);
 2469         }
 2470         *q = p ? ')' : '\n'; /* recover changed chars */
 2471         if (resolve_numeric(lastipstr, 0, lastip, &sslen, af) != 0)
 2472           fatal("Unable to parse ip (%s) in supposed log file %s.  Sorry", lastipstr, fname);
 2473         free(lastipstr);
 2474       } else {
 2475         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.");
 2476         lastip->ss_family = AF_UNSPEC;
 2477       }
 2478     }
 2479   }
 2480 
 2481   /* Ensure the log file ends with a newline */
 2482   filestr[filelen - 1] = '\n';
 2483   if (munmap(filestr, filelen) != 0)
 2484     gh_perror("%s: error in munmap(%p, %ld)", __func__, filestr, filelen);
 2485 
 2486   return 0;
 2487 }
 2488 
 2489 
 2490 static char *executable_dir(const char *argv0) {
 2491   char *path, *dir;
 2492 
 2493   path = executable_path(argv0);
 2494   if (path == NULL)
 2495     return NULL;
 2496   dir = path_get_dirname(path);
 2497   free(path);
 2498 
 2499   return dir;
 2500 }
 2501 
 2502 /* Returns true if the two given filenames refer to the same file. (Have the
 2503    same device and inode number.) */
 2504 static bool same_file(const char *filename_a, const char *filename_b) {
 2505   struct stat stat_a, stat_b;
 2506 
 2507   if (stat(filename_a, &stat_a) == -1)
 2508     return false;
 2509   if (stat(filename_b, &stat_b) == -1)
 2510     return false;
 2511 
 2512   return stat_a.st_dev == stat_b.st_dev && stat_a.st_ino == stat_b.st_ino;
 2513 }
 2514 
 2515 static int nmap_fetchfile_sub(char *filename_returned, int bufferlen, const char *file);
 2516 
 2517 /* Search for a file in the standard data file locations. The result is stored
 2518    in filename_returned, which must point to an allocated buffer of at least
 2519    bufferlen bytes. Returns true iff the search should be considered finished
 2520    (i.e., the caller shouldn't try to search anywhere else for the file).
 2521 
 2522    Options like --servicedb and --versiondb set explicit locations for
 2523    individual data files. If any of these were used those locations are checked
 2524    first, and no other locations are checked.
 2525 
 2526    After that, the following directories are searched in order:
 2527     * --datadir
 2528     * $NMAPDIR environment variable
 2529     * User's home Nmap directory:
 2530       - [Windows] %APPDATA%\nmap
 2531       - [Non-Windows] ~/.nmap
 2532     * The directory containing the nmap binary
 2533     * [Non-Windows only]:
 2534       - The directory containing the nmap binary plus "../share/nmap"
 2535       - NMAPDATADIR (usually $prefix/share/nmap)
 2536     */
 2537 int nmap_fetchfile(char *filename_returned, int bufferlen, const char *file) {
 2538   std::map<std::string, std::string>::iterator iter;
 2539   int res;
 2540 
 2541   /* Check the map of requested data file names. */
 2542   iter = o.requested_data_files.find(file);
 2543   if (iter != o.requested_data_files.end()) {
 2544     Strncpy(filename_returned, iter->second.c_str(), bufferlen);
 2545     /* If a special file name was requested, we must not return any other file
 2546        name. Return a positive result even if the file doesn't exist or is not
 2547        readable. It is the caller's responsibility to report the error if the
 2548        file can't be accessed. */
 2549     res = file_is_readable(filename_returned);
 2550     return res != 0 ? res : 1;
 2551   }
 2552 
 2553   res = nmap_fetchfile_sub(filename_returned, bufferlen, file);
 2554 
 2555   return res;
 2556 }
 2557 
 2558 #ifdef WIN32
 2559 static int nmap_fetchfile_userdir(char *buf, size_t buflen, const char *file) {
 2560   char appdata[MAX_PATH];
 2561   int res;
 2562 
 2563   if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdata) != S_OK)
 2564     return 0;
 2565   res = Snprintf(buf, buflen, "%s\\nmap\\%s", appdata, file);
 2566   if (res <= 0 || res >= buflen)
 2567     return 0;
 2568 
 2569   return file_is_readable(buf);
 2570 }
 2571 #else
 2572 static int nmap_fetchfile_userdir_uid(char *buf, size_t buflen, const char *file, int uid) {
 2573   struct passwd *pw;
 2574   int res;
 2575 
 2576   pw = getpwuid(uid);
 2577   if (pw == NULL)
 2578     return 0;
 2579   res = Snprintf(buf, buflen, "%s/.nmap/%s", pw->pw_dir, file);
 2580   if (res <= 0 || (size_t) res >= buflen)
 2581     return 0;
 2582 
 2583   return file_is_readable(buf);
 2584 }
 2585 
 2586 static int nmap_fetchfile_userdir(char *buf, size_t buflen, const char *file) {
 2587   int res;
 2588 
 2589   res = nmap_fetchfile_userdir_uid(buf, buflen, file, getuid());
 2590   if (res != 0)
 2591     return res;
 2592 
 2593   if (getuid() != geteuid()) {
 2594     res = nmap_fetchfile_userdir_uid(buf, buflen, file, geteuid());
 2595     if (res != 0)
 2596       return res;
 2597   }
 2598 
 2599   return 0;
 2600 }
 2601 #endif
 2602 
 2603 static int nmap_fetchfile_sub(char *filename_returned, int bufferlen, const char *file) {
 2604   char *dirptr;
 2605   int res;
 2606   int foundsomething = 0;
 2607   char dot_buffer[512];
 2608   static int warningcount = 0;
 2609 
 2610   if (o.datadir) {
 2611     res = Snprintf(filename_returned, bufferlen, "%s/%s", o.datadir, file);
 2612     if (res > 0 && res < bufferlen) {
 2613       foundsomething = file_is_readable(filename_returned);
 2614     }
 2615   }
 2616 
 2617   if (!foundsomething && (dirptr = getenv("NMAPDIR"))) {
 2618     res = Snprintf(filename_returned, bufferlen, "%s/%s", dirptr, file);
 2619     if (res > 0 && res < bufferlen) {
 2620       foundsomething = file_is_readable(filename_returned);
 2621     }
 2622   }
 2623 
 2624   if (!foundsomething)
 2625     foundsomething = nmap_fetchfile_userdir(filename_returned, bufferlen, file);
 2626 
 2627   const char *argv0;
 2628   char *dir;
 2629 
 2630   argv0 = get_program_name();
 2631   assert(argv0 != NULL);
 2632   dir = executable_dir(argv0);
 2633 
 2634   if (dir != NULL) {
 2635     if (!foundsomething) { /* Try the nMap directory */
 2636       res = Snprintf(filename_returned, bufferlen, "%s/%s", dir, file);
 2637       if (res > 0 && res < bufferlen) {
 2638         foundsomething = file_is_readable(filename_returned);
 2639       }
 2640     }
 2641 #ifndef WIN32
 2642     if (!foundsomething) {
 2643       res = Snprintf(filename_returned, bufferlen, "%s/../share/nmap/%s", dir, file);
 2644       if (res > 0 && res < bufferlen) {
 2645         foundsomething = file_is_readable(filename_returned);
 2646       }
 2647     }
 2648 #endif
 2649     free(dir);
 2650   }
 2651 
 2652 #ifndef WIN32
 2653   if (!foundsomething) {
 2654     res = Snprintf(filename_returned, bufferlen, "%s/%s", NMAPDATADIR, file);
 2655     if (res > 0 && res < bufferlen) {
 2656       foundsomething = file_is_readable(filename_returned);
 2657     }
 2658   }
 2659 #endif
 2660 
 2661   if (foundsomething && (*filename_returned != '.')) {
 2662     res = Snprintf(dot_buffer, sizeof(dot_buffer), "./%s", file);
 2663     if (res > 0 && res < bufferlen) {
 2664       if (file_is_readable(dot_buffer) && !same_file(filename_returned, dot_buffer)) {
 2665 #ifdef WIN32
 2666         if (warningcount++ < 1 && o.debugging)
 2667 #else
 2668         if (warningcount++ < 1)
 2669 #endif
 2670           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);
 2671       }
 2672     }
 2673   }
 2674 
 2675   if (foundsomething && o.debugging > 1)
 2676     log_write(LOG_PLAIN, "Fetchfile found %s\n", filename_returned);
 2677 
 2678   return foundsomething;
 2679 
 2680 }
 2681 
 2682 /* Extracts a whitespace-separated word from a string. Returns a zero-length
 2683    string if there are too few words. */
 2684 static std::string get_word(const char *str, unsigned int n) {
 2685   const char *p, *q;
 2686   unsigned int i;
 2687 
 2688   p = str;
 2689   for (i = 0; *p != '\0' && i <= n; i++) {
 2690     while (isspace((int) (unsigned char) *p))
 2691       p++;
 2692     q = p;
 2693     while (*q != '\0' && !isspace((int) (unsigned char) *q))
 2694       q++;
 2695     if (i == n)
 2696       return std::string(p, q - p);
 2697     p = q;
 2698   }
 2699 
 2700   return std::string();
 2701 }
 2702 
 2703 /* Helper for display_nmap_version. Tries to extract a word (presumably a
 2704    version number) from a string, but if that fails, returns the whole string
 2705    enclosed in parentheses as a failsafe. */
 2706 static std::string get_word_or_quote(const char *str, unsigned int n) {
 2707   std::string word;
 2708 
 2709   word = get_word(str, n);
 2710   if (word.length() == 0)
 2711     word = std::string("(") + str + std::string(")");
 2712 
 2713   return word;
 2714 }
 2715 
 2716 static void display_nmap_version() {
 2717   std::vector<std::string> with, without;
 2718   unsigned int i;
 2719 
 2720 #ifndef NOLUA
 2721 #ifdef LUA_INCLUDED
 2722   with.push_back(std::string("nmap-liblua-") + get_word_or_quote(LUA_RELEASE, 1));
 2723 #else
 2724   with.push_back(std::string("liblua-") + get_word_or_quote(LUA_RELEASE, 1));
 2725 #endif
 2726 #else
 2727   without.push_back("liblua");
 2728 #endif
 2729 
 2730 #if HAVE_OPENSSL
 2731   with.push_back(std::string("openssl-") + get_word_or_quote(OPENSSL_VERSION_TEXT, 1));
 2732 #else
 2733   without.push_back("openssl");
 2734 #endif
 2735 
 2736 #if HAVE_LIBSSH2
 2737 #ifdef LIBSSH2_INCLUDED
 2738   with.push_back(std::string("nmap-libssh2-") + get_word_or_quote(LIBSSH2_VERSION, 0));
 2739 #else
 2740   with.push_back(std::string("libssh2-") + get_word_or_quote(LIBSSH2_VERSION, 0));
 2741 #endif
 2742 #else
 2743   without.push_back("libssh2");
 2744 #endif
 2745 
 2746 #if HAVE_LIBZ
 2747 #ifdef ZLIB_INCLUDED
 2748   with.push_back(std::string("nmap-libz-") + get_word_or_quote(ZLIB_VERSION, 0));
 2749 #else
 2750   with.push_back(std::string("libz-") + get_word_or_quote(ZLIB_VERSION, 0));
 2751 #endif
 2752 #else
 2753   without.push_back("libz");
 2754 #endif
 2755 
 2756 #ifdef PCRE_INCLUDED
 2757   with.push_back(std::string("nmap-libpcre-") + get_word_or_quote(pcre_version(), 0));
 2758 #else
 2759   with.push_back(std::string("libpcre-") + get_word_or_quote(pcre_version(), 0));
 2760 #endif
 2761 
 2762 #ifdef WIN32
 2763   if (o.have_pcap) {
 2764     const char *pcap_version = pcap_lib_version();
 2765     const char *pcap_num = strpbrk(pcap_version, "0123456789");
 2766     if (pcap_num == NULL)
 2767       pcap_num = "(unknown)";
 2768     std::string pcap_num_str (pcap_num, strcspn(pcap_num, ","));
 2769     with.push_back(get_word_or_quote(pcap_version, 0) + std::string("-") + pcap_num_str);
 2770   }
 2771 #else
 2772   const char *pcap_version = pcap_lib_version();
 2773   std::string pcap_num_str = get_word_or_quote(pcap_version, 2);
 2774   with.push_back(
 2775 #ifdef PCAP_INCLUDED
 2776       std::string("nmap-") +
 2777 #endif
 2778       get_word_or_quote(pcap_version, 0) + std::string("-") + pcap_num_str);
 2779 #endif
 2780 
 2781 #ifdef DNET_INCLUDED
 2782   with.push_back(std::string("nmap-libdnet-") + DNET_VERSION);
 2783 #else
 2784   with.push_back(std::string("libdnet-") + DNET_VERSION);
 2785 #endif
 2786 
 2787 #if HAVE_IPV6
 2788   with.push_back("ipv6");
 2789 #else
 2790   without.push_back("ipv6");
 2791 #endif
 2792 
 2793   log_write(LOG_STDOUT, "%s version %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
 2794   log_write(LOG_STDOUT, "Platform: %s\n", NMAP_PLATFORM);
 2795   log_write(LOG_STDOUT, "Compiled with:");
 2796   for (i = 0; i < with.size(); i++)
 2797     log_write(LOG_STDOUT, " %s", with[i].c_str());
 2798   log_write(LOG_STDOUT, "\n");
 2799   log_write(LOG_STDOUT, "Compiled without:");
 2800   for (i = 0; i < without.size(); i++)
 2801     log_write(LOG_STDOUT, " %s", without[i].c_str());
 2802   log_write(LOG_STDOUT, "\n");
 2803   log_write(LOG_STDOUT, "Available nsock engines: %s\n", nsock_list_engines());
 2804 }