1 
2 /***************************************************************************
3  * timing.h -- Functions related to computing scan timing (such as keeping *
4  * track of and adjusting smoothed round trip times, statistical           *
5  * deviations, timeout values, etc.  Various user options (such as the     *
6  * timing policy (-T)) also play a role in these calculations.             *
7  *                                                                         *
8  ***********************IMPORTANT NMAP LICENSE TERMS************************
9  *                                                                         *
10  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
11  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
12  *                                                                         *
13  * This program is distributed under the terms of the Nmap Public Source   *
14  * License (NPSL). The exact license text applying to a particular Nmap    *
15  * release or source code control revision is contained in the LICENSE     *
16  * file distributed with that version of Nmap or source code control       *
17  * revision. More Nmap copyright/legal information is available from       *
18  * https://nmap.org/book/man-legal.html, and further information on the    *
19  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
20  * summarizes some key points from the Nmap license, but is no substitute  *
21  * for the actual license text.                                            *
22  *                                                                         *
23  * Nmap is generally free for end users to download and use themselves,    *
24  * including commercial use. It is available from https://nmap.org.        *
25  *                                                                         *
26  * The Nmap license generally prohibits companies from using and           *
27  * redistributing Nmap in commercial products, but we sell a special Nmap  *
28  * OEM Edition with a more permissive license and special features for     *
29  * this purpose. See https://nmap.org/oem                                  *
30  *                                                                         *
31  * If you have received a written Nmap license agreement or contract       *
32  * stating terms other than these (such as an Nmap OEM license), you may   *
33  * choose to use and redistribute Nmap under those terms instead.          *
34  *                                                                         *
35  * The official Nmap Windows builds include the Npcap software             *
36  * (https://npcap.org) for packet capture and transmission. It is under    *
37  * separate license terms which forbid redistribution without special      *
38  * permission. So the official Nmap Windows builds may not be              *
39  * redistributed without special permission (such as an Nmap OEM           *
40  * license).                                                               *
41  *                                                                         *
42  * Source is provided to this software because we believe users have a     *
43  * right to know exactly what a program is going to do before they run it. *
44  * This also allows you to audit the software for security holes.          *
45  *                                                                         *
46  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
47  * and add new features.  You are highly encouraged to submit your         *
48  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
49  * for possible incorporation into the main distribution. Unless you       *
50  * specify otherwise, it is understood that you are offering us very       *
51  * broad rights to use your submissions as described in the Nmap Public    *
52  * Source License Contributor Agreement. This is important because we      *
53  * fund the project by selling licenses with various terms, and also       *
54  * because the inability to relicense code has caused devastating          *
55  * problems for other Free Software projects (such as KDE and NASM).       *
56  *                                                                         *
57  * The free version of Nmap is distributed in the hope that it will be     *
58  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
59  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
60  * indemnification and commercial support are all available through the    *
61  * Npcap OEM program--see https://nmap.org/oem.                            *
62  *                                                                         *
63  ***************************************************************************/
64 
65 /* $Id: timing.h 38078 2020-10-02 16:12:22Z dmiller $ */
66 
67 #ifndef NMAP_TIMING_H
68 #define NMAP_TIMING_H
69 
70 #if TIME_WITH_SYS_TIME
71 # include <sys/time.h>
72 # include <time.h>
73 #else
74 # if HAVE_SYS_TIME_H
75 #  include <sys/time.h>
76 # else
77 #  include <time.h>
78 # endif
79 #endif
80 
81 #include <nbase.h> /* u32 */
82 
83 /* Based on TCP congestion control techniques from RFC2581. */
84 struct ultra_timing_vals {
85   double cwnd; /* Congestion window - in probes */
86   int ssthresh; /* The threshold above which mode is changed from slow start
87                    to congestion avoidance */
88   /* The number of replies we would expect if every probe produced a reply. This
89      is almost like the total number of probes sent but it is not incremented
90      until a reply is received or a probe times out. This and
91      num_replies_received are used to scale congestion window increments. */
92   int num_replies_expected;
93   /* The number of replies we've received to probes of any type. */
94   int num_replies_received;
95   /* Number of updates to this timing structure (generally packet receipts). */
96   int num_updates;
97   /* Last time values were adjusted for a drop (you usually only want
98      to adjust again based on probes sent after that adjustment so a
99      sudden batch of drops doesn't destroy timing.  Init to now */
100   struct timeval last_drop;
101 
102   double cc_scale(const struct scan_performance_vars *perf);
103   void ack(const struct scan_performance_vars *perf, double scale = 1.0);
104   void drop(unsigned in_flight,
105     const struct scan_performance_vars *perf, const struct timeval *now);
106   void drop_group(unsigned in_flight,
107     const struct scan_performance_vars *perf, const struct timeval *now);
108 };
109 
110 /* These are mainly initializers for ultra_timing_vals. */
111 struct scan_performance_vars {
112   int low_cwnd;  /* The lowest cwnd (congestion window) allowed */
113   int host_initial_cwnd; /* Initial congestion window for ind. hosts */
114   int group_initial_cwnd; /* Initial congestion window for all hosts as a group */
115   int max_cwnd; /* I should never have more than this many probes
116                    outstanding */
117   int slow_incr; /* How many probes are incremented for each response
118                     in slow start mode */
119   int ca_incr; /* How many probes are incremented per (roughly) rtt in
120                   congestion avoidance mode */
121   int cc_scale_max; /* The maximum scaling factor for congestion window
122                        increments. */
123   int initial_ssthresh;
124   double group_drop_cwnd_divisor; /* all-host group cwnd divided by this
125                                      value if any packet drop occurs */
126   double group_drop_ssthresh_divisor; /* used to drop the group ssthresh when
127                                          any drop occurs */
128   double host_drop_ssthresh_divisor; /* used to drop the host ssthresh when
129                                          any drop occurs */
130 
131   /* Do initialization after the global NmapOps table has been filled in. */
132   void init();
133 };
134 
135 struct timeout_info {
136   int srtt; /* Smoothed rtt estimate (microseconds) */
137   int rttvar; /* Rout trip time variance */
138   int timeout; /* Current timeout threshold (microseconds) */
139 };
140 
141 /* Call this function on a newly allocated struct timeout_info to
142    initialize the values appropriately */
143 void initialize_timeout_info(struct timeout_info *to);
144 
145 /* Same as adjust_timeouts(), except this one allows you to specify
146  the receive time too (which could be because it was received a while
147  back or it could be for efficiency because the caller already knows
148  the current time */
149 void adjust_timeouts2(const struct timeval *sent,
150                       const struct timeval *received,
151                       struct timeout_info *to);
152 
153 /* Adjust our timeout values based on the time the latest probe took for a
154    response.  We update our RTT averages, etc. */
155 void adjust_timeouts(struct timeval sent, struct timeout_info *to);
156 
157 #define DEFAULT_CURRENT_RATE_HISTORY 5.0
158 
159 /* Sleeps if necessary to ensure that it isn't called twice within less
160    time than o.send_delay.  If it is passed a non-null tv, the POST-SLEEP
161    time is recorded in it */
162 void enforce_scan_delay(struct timeval *tv);
163 
164 /* This class measures current and lifetime average rates for some quantity. */
165 class RateMeter {
166   public:
167     RateMeter(double current_rate_history = DEFAULT_CURRENT_RATE_HISTORY);
168 
169     void start(const struct timeval *now = NULL);
170     void stop(const struct timeval *now = NULL);
171     void update(double amount, const struct timeval *now = NULL);
172     double getOverallRate(const struct timeval *now = NULL) const;
173     double getCurrentRate(const struct timeval *now = NULL, bool update = true);
174     double getTotal(void) const;
175     double elapsedTime(const struct timeval *now = NULL) const;
176 
177   private:
178     /* How many seconds to look back when calculating the "current" rates. */
179     double current_rate_history;
180 
181     /* When this meter started recording. */
182     struct timeval start_tv;
183     /* When this meter stopped recording. */
184     struct timeval stop_tv;
185     /* The last time the current sample rates were updated. */
186     struct timeval last_update_tv;
187 
188     double total;
189     double current_rate;
190 
191     static bool isSet(const struct timeval *tv);
192 };
193 
194 /* A specialization of RateMeter that measures packet and byte rates. */
195 class PacketRateMeter {
196   public:
197     PacketRateMeter(double current_rate_history = DEFAULT_CURRENT_RATE_HISTORY);
198 
199     void start(const struct timeval *now = NULL);
200     void stop(const struct timeval *now = NULL);
201     void update(u32 len, const struct timeval *now = NULL);
202     double getOverallPacketRate(const struct timeval *now = NULL) const;
203     double getCurrentPacketRate(const struct timeval *now = NULL, bool update = true);
204     double getOverallByteRate(const struct timeval *now = NULL) const;
205     double getCurrentByteRate(const struct timeval *now = NULL, bool update = true);
206     unsigned long long getNumPackets(void) const;
207     unsigned long long getNumBytes(void) const;
208 
209   private:
210     RateMeter packet_rate_meter;
211     RateMeter byte_rate_meter;
212 };
213 
214 class ScanProgressMeter {
215  public:
216   /* A COPY of stypestr is made and saved for when stats are printed */
217   ScanProgressMeter(const char *stypestr);
218   ~ScanProgressMeter();
219 /* Decides whether a timing report is likely to even be
220    printed.  There are stringent limitations on how often they are
221    printed, as well as the verbosity level that must exist.  So you
222    might as well check this before spending much time computing
223    progress info.  now can be NULL if caller doesn't have the current
224    time handy.  Just because this function returns true does not mean
225    that the next printStatsIfNecessary will always print something.
226    It depends on whether time estimates have changed, which this func
227    doesn't even know about. */
228   bool mayBePrinted(const struct timeval *now);
229 
230 /* Prints an estimate of when this scan will complete.  It only does
231    so if mayBePrinted() is true, and it seems reasonable to do so
232    because the estimate has changed significantly.  Returns whether
233    or not a line was printed.*/
234   bool printStatsIfNecessary(double perc_done, const struct timeval *now);
235 
236   /* Prints an estimate of when this scan will complete. */
237   bool printStats(double perc_done, const struct timeval *now);
238 
239   /* Prints that this task is complete. */
endTask(const struct timeval * now,const char * additional_info)240   bool endTask(const struct timeval *now, const char *additional_info) { return beginOrEndTask(now, additional_info, false); }
241 
242   struct timeval begin; /* When this ScanProgressMeter was instantiated */
243  private:
244   struct timeval last_print_test; /* Last time printStatsIfNecessary was called */
245   struct timeval last_print; /* The most recent time the ETC was printed */
246   char *scantypestr;
247   struct timeval last_est; /* The latest PRINTED estimate */
248 
249   bool beginOrEndTask(const struct timeval *now, const char *additional_info, bool beginning);
250 };
251 
252 #endif /* NMAP_TIMING_H */
253 
254