1 
2 /***************************************************************************
3  * scan_engine.h -- Includes much of the "engine" functions for scanning,  *
4  * such as ultra_scan.  It also includes dependent functions such as       *
5  * those for collecting SYN/connect scan responses.                        *
6  *                                                                         *
7  ***********************IMPORTANT NMAP LICENSE TERMS************************
8  *                                                                         *
9  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
10  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
11  *                                                                         *
12  * This program is distributed under the terms of the Nmap Public Source   *
13  * License (NPSL). The exact license text applying to a particular Nmap    *
14  * release or source code control revision is contained in the LICENSE     *
15  * file distributed with that version of Nmap or source code control       *
16  * revision. More Nmap copyright/legal information is available from       *
17  * https://nmap.org/book/man-legal.html, and further information on the    *
18  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
19  * summarizes some key points from the Nmap license, but is no substitute  *
20  * for the actual license text.                                            *
21  *                                                                         *
22  * Nmap is generally free for end users to download and use themselves,    *
23  * including commercial use. It is available from https://nmap.org.        *
24  *                                                                         *
25  * The Nmap license generally prohibits companies from using and           *
26  * redistributing Nmap in commercial products, but we sell a special Nmap  *
27  * OEM Edition with a more permissive license and special features for     *
28  * this purpose. See https://nmap.org/oem                                  *
29  *                                                                         *
30  * If you have received a written Nmap license agreement or contract       *
31  * stating terms other than these (such as an Nmap OEM license), you may   *
32  * choose to use and redistribute Nmap under those terms instead.          *
33  *                                                                         *
34  * The official Nmap Windows builds include the Npcap software             *
35  * (https://npcap.org) for packet capture and transmission. It is under    *
36  * separate license terms which forbid redistribution without special      *
37  * permission. So the official Nmap Windows builds may not be              *
38  * redistributed without special permission (such as an Nmap OEM           *
39  * license).                                                               *
40  *                                                                         *
41  * Source is provided to this software because we believe users have a     *
42  * right to know exactly what a program is going to do before they run it. *
43  * This also allows you to audit the software for security holes.          *
44  *                                                                         *
45  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
46  * and add new features.  You are highly encouraged to submit your         *
47  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
48  * for possible incorporation into the main distribution. Unless you       *
49  * specify otherwise, it is understood that you are offering us very       *
50  * broad rights to use your submissions as described in the Nmap Public    *
51  * Source License Contributor Agreement. This is important because we      *
52  * fund the project by selling licenses with various terms, and also       *
53  * because the inability to relicense code has caused devastating          *
54  * problems for other Free Software projects (such as KDE and NASM).       *
55  *                                                                         *
56  * The free version of Nmap is distributed in the hope that it will be     *
57  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
58  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
59  * indemnification and commercial support are all available through the    *
60  * Npcap OEM program--see https://nmap.org/oem.                            *
61  *                                                                         *
62  ***************************************************************************/
63 
64 /* $Id: scan_engine.h 38078 2020-10-02 16:12:22Z dmiller $ */
65 
66 #ifndef SCAN_ENGINE_H
67 #define SCAN_ENGINE_H
68 
69 #include "scan_lists.h"
70 #include "probespec.h"
71 
72 #include <dnet.h>
73 
74 #include "timing.h"
75 
76 #include <pcap.h>
77 #include <list>
78 #include <vector>
79 #include <set>
80 #include <algorithm>
81 class Target;
82 
83 /* 3rd generation Nmap scanning function.  Handles most Nmap port scan types */
84 void ultra_scan(std::vector<Target *> &Targets, struct scan_lists *ports,
85                 stype scantype, struct timeout_info *to = NULL);
86 
87 /* Determines an ideal number of hosts to be scanned (port scan, os
88    scan, version detection, etc.) in parallel after the ping scan is
89    completed.  This is a balance between efficiency (more hosts in
90    parallel often reduces scan time per host) and results latency (you
91    need to wait for all hosts to finish before Nmap can spit out the
92    results).  Memory consumption usually also increases with the
93    number of hosts scanned in parallel, though rarely to significant
94    levels. */
95 int determineScanGroupSize(int hosts_scanned_so_far,
96                            struct scan_lists *ports);
97 
98 class UltraScanInfo;
99 
100 struct ppkt { /* Beginning of ICMP Echo/Timestamp header         */
101   u8 type;
102   u8 code;
103   u16 checksum;
104   u16 id;
105   u16 seq;
106 };
107 
108 class ConnectProbe {
109 public:
110   ConnectProbe();
111   ~ConnectProbe();
112   int sd; /* Socket descriptor used for connection.  -1 if not valid. */
113 };
114 
115 struct IPExtraProbeData_icmp {
116   u16 ident;
117 };
118 
119 struct IPExtraProbeData_tcp {
120   u16 sport;
121   u32 seq; /* host byte order (like the other fields */
122 };
123 
124 struct IPExtraProbeData_udp {
125   u16 sport;
126 };
127 
128 struct IPExtraProbeData_sctp {
129   u16 sport;
130   u32 vtag;
131 };
132 
133 struct IPExtraProbeData {
134   u32 ipid; /* host byte order */
135   union {
136     struct IPExtraProbeData_icmp icmp;
137     struct IPExtraProbeData_tcp tcp;
138     struct IPExtraProbeData_udp udp;
139     struct IPExtraProbeData_sctp sctp;
140   } pd;
141 };
142 
143 /* At least for now, I'll just use this like a struct and access
144    all the data members directly */
145 class UltraProbe {
146 public:
147   UltraProbe();
148   ~UltraProbe();
149   enum UPType { UP_UNSET, UP_IP, UP_CONNECT, UP_ARP, UP_ND } type; /* The type of probe this is */
150 
151   /* Sets this UltraProbe as type UP_IP and creates & initializes the
152      internal IPProbe.  The relevant probespec is necessary for setIP
153      because pspec.type is ambiguous with just the ippacket (e.g. a
154      tcp packet could be PS_PROTO or PS_TCP). */
155   void setIP(u8 *ippacket, u32 iplen, const probespec *pspec);
156   /* Sets this UltraProbe as type UP_CONNECT, preparing to connect to given
157    port number*/
158   void setConnect(u16 portno);
159   /* Pass an arp packet, including ethernet header. Must be 42bytes */
160   void setARP(u8 *arppkt, u32 arplen);
161   void setND(u8 *ndpkt, u32 ndlen);
162   // The 4 accessors below all return in HOST BYTE ORDER
163   // source port used if TCP, UDP or SCTP
164   u16 sport() const;
165   // destination port used if TCP, UDP or SCTP
166   u16 dport() const;
ipid()167   u32 ipid() const {
168     return probes.IP.ipid;
169   }
170   u16 icmpid() const; // ICMP ident if protocol is ICMP
171   u32 tcpseq() const; // TCP sequence number if protocol is TCP
172   u32 sctpvtag() const; // SCTP vtag if protocol is SCTP
173   /* Number, such as IPPROTO_TCP, IPPROTO_UDP, etc. */
protocol()174   u8 protocol() const {
175     return mypspec.proto;
176   }
CP()177   ConnectProbe *CP() {
178     return probes.CP;  // if type == UP_CONNECT
179   }
180   // Arpprobe removed because not used.
181   //  ArpProbe *AP() { return probes.AP; } // if UP_ARP
182   // Returns the protocol number, such as IPPROTO_TCP, or IPPROTO_UDP, by
183   // reading the appropriate fields of the probespec.
184 
185   /* Get general details about the probe */
pspec()186   const probespec *pspec() const {
187     return &mypspec;
188   }
189 
190   /* Returns true if the given tryno and pingseq match those within this
191      probe. */
check_tryno_pingseq(unsigned int tryno,unsigned int pingseq)192   bool check_tryno_pingseq(unsigned int tryno, unsigned int pingseq) const {
193     return (pingseq == 0 && tryno == this->tryno) || (pingseq > 0 && pingseq == this->pingseq);
194   }
195 
196   u8 tryno; /* Try (retransmission) number of this probe */
197   u8 pingseq; /* 0 if this is not a scanping. Otherwise a positive ping seq#. */
198   /* If true, probe is considered no longer active due to timeout, but it
199      may be kept around a while, just in case a reply comes late */
200   bool timedout;
201   /* A packet may be timedout for a while before being retransmitted due to
202      packet sending rate limitations */
203   bool retransmitted;
204 
205   struct timeval sent;
206   /* Time the previous probe was sent, if this is a retransmit (tryno > 0) */
207   struct timeval prevSent;
isPing()208   bool isPing() {
209     return pingseq > 0;
210   }
211 
212 private:
213   probespec mypspec; /* Filled in by the appropriate set* function */
214   union {
215     IPExtraProbeData IP;
216     ConnectProbe *CP;
217     //    ArpProbe *AP;
218   } probes;
219 };
220 
221 /* Global info for the connect scan */
222 class ConnectScanInfo {
223 public:
224   ConnectScanInfo();
225   ~ConnectScanInfo();
226 
227   /* Watch a socket descriptor (add to fd_sets and maxValidSD).  Returns
228      true if the SD was absent from the list, false if you tried to
229      watch an SD that was already being watched. */
230   bool watchSD(int sd);
231 
232   /* Clear SD from the fd_sets and maxValidSD.  Returns true if the SD
233    was in the list, false if you tried to clear an sd that wasn't
234    there in the first place. */
235   bool clearSD(int sd);
236   int maxValidSD; /* The maximum socket descriptor in any of the fd_sets */
237   fd_set fds_read;
238   fd_set fds_write;
239   fd_set fds_except;
240   int numSDs; /* Number of socket descriptors being watched */
241   int maxSocketsAllowed; /* No more than this many sockets may be created @once */
242 };
243 
244 class HostScanStats;
245 
246 /* These are ultra_scan() statistics for the whole group of Targets */
247 class GroupScanStats {
248 public:
249   struct timeval timeout; /* The time at which we abort the scan */
250   /* Most recent host tested for sendability */
251   struct sockaddr_storage latestip;
252   GroupScanStats(UltraScanInfo *UltraSI);
253   ~GroupScanStats();
254   void probeSent(unsigned int nbytes);
255   /* Returns true if the GLOBAL system says that sending is OK. */
256   bool sendOK(struct timeval *when);
257   /* Total # of probes outstanding (active) for all Hosts */
258   int num_probes_active;
259   UltraScanInfo *USI; /* The USI which contains this GSS.  Use for at least
260                          getting the current time w/o gettimeofday() */
261   struct ultra_timing_vals timing;
262   struct timeout_info to; /* Group-wide packet rtt/timeout info */
263   int numtargets; /* Total # of targets scanned -- includes finished and incomplete hosts */
264   int numprobes; /* Number of probes/ports scanned on each host */
265   /* The last time waitForResponses finished (initialized to GSS creation time */
266   int probes_sent; /* Number of probes sent in total.  This DOES include pings and retransmissions */
267 
268   /* The most recently received probe response time -- initialized to scan
269      start time. */
270   struct timeval lastrcvd;
271   /* The time the most recent ping was sent (initialized to scan begin time) */
272   struct timeval lastping_sent;
273   /* Value of numprobes_sent at lastping_sent time -- to ensure that we don't
274      send too many pings when probes are going slowly. */
275   int lastping_sent_numprobes;
276 
277   /* These two variables control minimum- and maximum-rate sending (--min-rate
278      and --max-rate). send_no_earlier_than is for --max-rate and
279      send_no_later_than is for --min-rate; they have effect only when the
280      respective command-line option is given. An attempt is made to keep the
281      sending rate within the interval, however for send_no_later_than it is not
282      guaranteed. */
283   struct timeval send_no_earlier_than;
284   struct timeval send_no_later_than;
285 
286   /* The host to which global pings are sent. This is kept updated to be the
287      most recent host that was found up. */
288   HostScanStats *pinghost;
289 
290   struct timeval last_wait;
291   int probes_sent_at_last_wait;
292   // number of hosts that timed out during scan, or were already timedout
293   int num_hosts_timedout;
294   ConnectScanInfo *CSI;
295 };
296 
297 struct send_delay_nfo {
298   unsigned int delayms; /* Milliseconds to delay between probes */
299   /* The number of successful and dropped probes since the last time the delay
300      was changed. The ratio controls when the rate drops. */
301   unsigned int goodRespSinceDelayChanged;
302   unsigned int droppedRespSinceDelayChanged;
303   struct timeval last_boost; /* Most recent time of increase to delayms.  Init to creation time. */
304 };
305 
306 /* To test for rate limiting, there is a delay in sending the first packet
307    of a certain retransmission number.  These values help track that. */
308 struct rate_limit_detection_nfo {
309   unsigned int max_tryno_sent; /* What is the max tryno we have sent so far (starts at 0) */
310   bool rld_waiting; /* Are we currently waiting due to RLD? */
311   struct timeval rld_waittime; /* if RLD waiting, when can we send? */
312 };
313 
314 /* The ultra_scan() statistics that apply to individual target hosts in a
315    group */
316 class HostScanStats {
317 public:
318   Target *target; /* A copy of the Target that these stats refer to. */
319   HostScanStats(Target *t, UltraScanInfo *UltraSI);
320   ~HostScanStats();
321   int freshPortsLeft(); /* Returns the number of ports remaining to probe */
322   int next_portidx; /* Index of the next port to probe in the relevant
323                        ports array in USI.ports */
324   bool sent_arp; /* Has an ARP probe been sent for the target yet? */
325 
326   /* massping state. */
327   /* The index of the next ACK port in o.ping_ackprobes to probe during ping
328      scan. */
329   int next_ackportpingidx;
330   /* The index of the next SYN port in o.ping_synprobes to probe during ping
331      scan. */
332   int next_synportpingidx;
333   /* The index of the next UDP port in o.ping_udpprobes to probe during ping
334      scan. */
335   int next_udpportpingidx;
336   /* The index of the next SCTP port in o.ping_protoprobes to probe during ping
337      scan. */
338   int next_sctpportpingidx;
339   /* The index of the next IP protocol in o.ping_protoprobes to probe during ping
340      scan. */
341   int next_protoportpingidx;
342   /* Whether we have sent an ICMP echo request. */
343   bool sent_icmp_ping;
344   /* Whether we have sent an ICMP address mask request. */
345   bool sent_icmp_mask;
346   /* Whether we have sent an ICMP timestamp request. */
347   bool sent_icmp_ts;
348 
349   /* Have we warned that we've given up on a port for this host yet? Only one
350      port per host is reported. */
351   bool retry_capped_warned;
352 
353   void probeSent(unsigned int nbytes);
354 
355   /* How long I am currently willing to wait for a probe response
356      before considering it timed out.  Uses the host values from
357      target if they are available, otherwise from gstats.  Results
358      returned in MICROseconds.  */
359   unsigned long probeTimeout();
360 
361   /* How long I'll wait until completely giving up on a probe.
362      Timedout probes are often marked as such (and sometimes
363      considered a drop), but kept in the list juts in case they come
364      really late.  But after probeExpireTime(), I don't waste time
365      keeping them around. Give in MICROseconds */
366   unsigned long probeExpireTime(const UltraProbe *probe);
367   /* Returns OK if sending a new probe to this host is OK (to avoid
368      flooding). If when is non-NULL, fills it with the time that sending
369      will be OK assuming no pending probes are resolved by responses
370      (call it again if they do).  when will become now if it returns
371      true. */
372   bool sendOK(struct timeval *when);
373 
374   /* If there are pending probe timeouts, fills in when with the time of
375      the earliest one and returns true.  Otherwise returns false and
376      puts now in when. */
377   bool nextTimeout(struct timeval *when);
378   UltraScanInfo *USI; /* The USI which contains this HSS */
379 
380   /* Removes a probe from probes_outstanding, adjusts HSS and USS
381      active probe stats accordingly, then deletes the probe. */
382   void destroyOutstandingProbe(std::list<UltraProbe *>::iterator probeI);
383 
384   /* Removes all probes from probes_outstanding using
385      destroyOutstandingProbe. This is used in ping scan to quit waiting
386      for responses once a host is known to be up. Invalidates iterators
387      pointing into probes_outstanding. */
388   void destroyAllOutstandingProbes();
389 
390   /* Mark an outstanding probe as timedout.  Adjusts stats
391      accordingly.  For connect scans, this closes the socket. */
392   void markProbeTimedout(std::list<UltraProbe *>::iterator probeI);
393 
394   /* New (active) probes are appended to the end of this list.  When a
395      host times out, it will be marked as such, but may hang around on
396      the list for a while just in case a response comes in.  So use
397      num_probes_active to learn how many active (not timed out) probes
398      are outstanding.  Probes on the bench (reached the current
399      maximum tryno and expired) are not counted in
400      probes_outstanding.  */
401   std::list<UltraProbe *> probes_outstanding;
402   /* The number of probes in probes_outstanding, minus the inactive (timed out) ones */
403   unsigned int num_probes_active;
404   /* Probes timed out but not yet retransmitted because of congestion
405      control limits or because more retransmits may not be
406      necessary.  Note that probes on probe_bench are not included
407      in this value. */
408   unsigned int num_probes_waiting_retransmit;
num_probes_outstanding()409   unsigned int num_probes_outstanding() {
410     return probes_outstanding.size();
411   }
412 
413   /* The bench is a stock of probes (compacted into just the
414      probespec) that have met the current maximum tryno, and are on
415      ice until that tryno increases (so we can retransmit again), or
416      solidifies (so we can mark the port firewalled or whatever).  The
417      tryno of bench members is bench_tryno.  If the maximum tryno
418      increases, everyone on the bench is moved to the retry_stack.
419    */
420   std::vector<probespec> probe_bench;
421   unsigned int bench_tryno; /* # tryno of probes on the bench */
422   /* The retry_stack are probespecs that were on the bench but are now
423      slated to be retried.  It is kept sorted such that probes with highest
424      retry counts are on top, ready to be taken first. */
425   std::vector<probespec> retry_stack;
426   /* retry_stack_tries MUST BE KEPT IN SYNC WITH retry_stack.
427      retry_stack_tries[i] is the number of completed retries for the
428      probe in retry_stack[i] */
429   std::vector<u8> retry_stack_tries;
430   /* tryno of probes on the retry queue */
431   /* Moves the given probe from the probes_outstanding list, to
432      probe_bench, and decrements num_probes_waiting_retransmit accordingly */
433   void moveProbeToBench(std::list<UltraProbe *>::iterator probeI);
434   /* Dismiss all probe attempts on bench -- the ports are marked
435      'filtered' or whatever is appropriate for having no response */
436   void dismissBench();
437   /* Move all members of bench to retry_stack for probe retransmission */
438   void retransmitBench();
439 
440   bool completed(); /* Whether or not the scan of this Target has completed */
441   struct timeval completiontime; /* When this Target completed */
442 
443   /* This function provides the proper cwnd and ssthresh to use.  It
444      may differ from versions in timing member var because when no
445      responses have been received for this host, may look at others in
446      the group.  For CHANGING this host's timing, use the timing
447      memberval instead. */
448   void getTiming(struct ultra_timing_vals *tmng);
449   struct ultra_timing_vals timing;
450   /* The most recently received probe response time -- initialized to scan start time. */
451   struct timeval lastrcvd;
452   struct timeval lastping_sent; /* The time the most recent ping was sent (initialized to scan begin time) */
453 
454   /* Value of numprobes_sent at lastping_sent time -- to ensure that we
455      don't send too many pings when probes are going slowly. */
456   int lastping_sent_numprobes;
457   struct timeval lastprobe_sent; /* Most recent probe send (including pings) by host.  Init to scan begin time. */
458   /* gives the maximum try number (try numbers start at zero and
459      increments for each retransmission) that may be used, based on
460      the scan type, observed network reliability, timing mode, etc.
461      This may change during the scan based on network traffic.  If
462      capped is not null, it will be filled with true if the tryno is
463      at its upper limit.  That often calls for a warning to be issued,
464      and marking of remaining timedout ports firewalled or whatever is
465      appropriate.  If mayincrease is non-NULL, it is set to whether
466      the allowedTryno may increase again.  If it is false, any probes
467      which have reached the given limit may be dealt with. */
468   unsigned int allowedTryno(bool *capped, bool *mayincrease);
469 
470 
471   /* Provides the next ping sequence number.  This starts at one, goes
472    up to 255, then wraps around back to 1.  If inc is true, it is
473    incremented.  Otherwise you just get a peek at what the next one
474    will be. */
475   u8 nextPingSeq(bool inc = true) {
476     u8 ret = nxtpseq;
477     if (inc) {
478       nxtpseq++;
479       if (nxtpseq == 0)
480         nxtpseq++;
481     }
482     return ret;
483   }
484   /* This is the highest try number that has produced useful results
485      (such as port status change). */
486   unsigned int max_successful_tryno;
487   /* This starts as true because tryno may increase based on results, but
488      it becomes false if it becomes clear that tryno will not increase
489      further during the scan */
490   bool tryno_mayincrease;
491   int ports_finished; /* The number of ports of this host that have been determined */
492   int numprobes_sent; /* Number of port probes (not counting pings, but counting retransmits) sent to this host */
493   /* Boost the scan delay for this host, usually because too many packet
494      drops were detected. */
495   void boostScanDelay();
496   struct send_delay_nfo sdn;
497   struct rate_limit_detection_nfo rld;
498 
499 private:
500   u8 nxtpseq; /* the next scanping sequence number to use */
501 };
502 
503 /* A few extra performance tuning parameters specific to ultra_scan. */
504 struct ultra_scan_performance_vars : public scan_performance_vars {
505   /* When a successful ping response comes back, it counts as this many
506      "normal" responses, because the fact that pings are necessary means
507      we aren't getting much input. */
508   int ping_magnifier;
509   /* Try to send a scanping if no response has been received from a target host
510      in this many usecs */
511   int pingtime;
512   unsigned int tryno_cap; /* The maximum trynumber (starts at zero) allowed */
513 
514   void init();
515 };
516 
517 struct HssPredicate {
518 public:
519   int operator() (const HostScanStats *lhs, const HostScanStats *rhs) const;
520   static struct sockaddr_storage *ss;
521 };
522 
523 class UltraScanInfo {
524 public:
525   UltraScanInfo();
UltraScanInfo(std::vector<Target * > & Targets,struct scan_lists * pts,stype scantype)526   UltraScanInfo(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantype) {
527     Init(Targets, pts, scantype);
528   }
529   ~UltraScanInfo();
530   /* Must call Init if you create object with default constructor */
531   void Init(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantp);
532 
533   unsigned int numProbesPerHost();
534 
535   /* Consults with the group stats, and the hstats for every
536      incomplete hosts to determine whether any probes may be sent.
537      Returns true if they can be sent immediately.  If when is non-NULL,
538      it is filled with the next possible time that probes can be sent
539      (which will be now, if the function returns true */
540   bool sendOK(struct timeval *tv);
541   stype scantype;
542   bool tcp_scan; /* scantype is a type of TCP scan */
543   bool udp_scan;
544   bool sctp_scan; /* scantype is a type of SCTP scan */
545   bool prot_scan;
546   bool ping_scan; /* Includes trad. ping scan & arp scan */
547   bool ping_scan_arp; /* ONLY includes arp ping scan */
548   bool ping_scan_nd; /* ONLY includes ND ping scan */
549   bool noresp_open_scan; /* Whether no response means a port is open */
550 
551   /* massping state. */
552   /* If ping_scan is true (unless ping_scan_arp is also true), this is the set
553      of ping techniques to use (ICMP, raw ICMP, TCP connect, raw TCP, or raw
554      UDP). */
555   struct {
556     unsigned int rawicmpscan: 1,
557       connecttcpscan: 1,
558       rawtcpscan: 1,
559       rawudpscan: 1,
560       rawsctpscan: 1,
561       rawprotoscan: 1;
562   } ptech;
563 
564   bool isRawScan();
565 
566   struct timeval now; /* Updated after potentially meaningful delays.  This can
567                          be used to save a call to gettimeofday() */
568   GroupScanStats *gstats;
569   struct ultra_scan_performance_vars perf;
570   /* A circular buffer of the incompleteHosts.  nextIncompleteHost() gives
571      the next one.  The first time it is called, it will give the
572      first host in the list.  If incompleteHosts is empty, returns
573      NULL. */
574   HostScanStats *nextIncompleteHost();
575   /* Removes any hosts that have completed their scans from the incompleteHosts
576      list, and remove any hosts from completedHosts which have exceeded their
577      lifetime.  Returns the number of hosts removed. */
578   int removeCompletedHosts();
579   /* Find a HostScanStats by its IP address in the incomplete and completed
580      lists.  Returns NULL if none are found. */
581   HostScanStats *findHost(struct sockaddr_storage *ss);
582 
583   double getCompletionFraction();
584 
numIncompleteHosts()585   unsigned int numIncompleteHosts() {
586     return incompleteHosts.size();
587   }
588   /* Call this instead of checking for numIncompleteHosts() == 0 because it
589      avoids a potential traversal of the list to find the size. */
incompleteHostsEmpty()590   bool incompleteHostsEmpty() {
591     return incompleteHosts.empty();
592   }
593   bool numIncompleteHostsLessThan(unsigned int n);
594 
numInitialHosts()595   unsigned int numInitialHosts() {
596     return numInitialTargets;
597   }
598 
599   void log_overall_rates(int logt);
600   void log_current_rates(int logt, bool update = true);
601 
602   /* Any function which messes with (removes elements from)
603      incompleteHosts may have to manipulate nextI */
604   std::multiset<HostScanStats *, HssPredicate> incompleteHosts;
605   /* Hosts are moved from incompleteHosts to completedHosts as they are
606      completed. We keep them around because sometimes responses come back very
607      late, after we consider a host completed. */
608   std::multiset<HostScanStats *, HssPredicate> completedHosts;
609   /* How long (in msecs) we keep a host in completedHosts */
610   unsigned int completedHostLifetime;
611   /* The last time we went through completedHosts to remove hosts */
612   struct timeval lastCompletedHostRemoval;
613 
614   ScanProgressMeter *SPM;
615   PacketRateMeter send_rate_meter;
616   struct scan_lists *ports;
617   int rawsd; /* raw socket descriptor */
618   pcap_t *pd;
619   eth_t *ethsd;
620   u32 seqmask; /* This mask value is used to encode values in sequence
621                   numbers.  It is set randomly in UltraScanInfo::Init() */
622 private:
623 
624   unsigned int numInitialTargets;
625   std::multiset<HostScanStats *, HssPredicate>::iterator nextI;
626 
627 };
628 
629 /* Whether this is storing timing stats for a whole group or an
630    individual host */
631 enum ultra_timing_type { TIMING_HOST, TIMING_GROUP };
632 
633 const char *pspectype2ascii(int type);
634 
635 void ultrascan_port_probe_update(UltraScanInfo *USI, HostScanStats *hss,
636                                  std::list<UltraProbe *>::iterator probeI,
637                                  int newstate, struct timeval *rcvdtime,
638                                  bool adjust_timing_hint = true);
639 
640 void ultrascan_host_probe_update(UltraScanInfo *USI, HostScanStats *hss,
641                                         std::list<UltraProbe *>::iterator probeI,
642                                         int newstate, struct timeval *rcvdtime,
643                                         bool adjust_timing_hint = true);
644 
645 void ultrascan_ping_update(UltraScanInfo *USI, HostScanStats *hss,
646                                   std::list<UltraProbe *>::iterator probeI,
647                                   struct timeval *rcvdtime,
648                                   bool adjust_timing = true);
649 #endif /* SCAN_ENGINE_H */
650 
651