1 
2 /***************************************************************************
3  * netutil.h -- The main include file exposing the external API for        *
4  * libnetutil, a library that provides network-related functions or        *
5  * classes that make it easier to handle things like network interfaces,   *
6  * routing tables, raw packet manipulation, etc. The lib was originally    *
7  * written for use in the Nmap Security Scanner ( https://nmap.org ).       *
8  *                                                                         *
9  ***********************IMPORTANT NMAP LICENSE TERMS************************
10  *                                                                         *
11  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
12  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
13  *                                                                         *
14  * This program is distributed under the terms of the Nmap Public Source   *
15  * License (NPSL). The exact license text applying to a particular Nmap    *
16  * release or source code control revision is contained in the LICENSE     *
17  * file distributed with that version of Nmap or source code control       *
18  * revision. More Nmap copyright/legal information is available from       *
19  * https://nmap.org/book/man-legal.html, and further information on the    *
20  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
21  * summarizes some key points from the Nmap license, but is no substitute  *
22  * for the actual license text.                                            *
23  *                                                                         *
24  * Nmap is generally free for end users to download and use themselves,    *
25  * including commercial use. It is available from https://nmap.org.        *
26  *                                                                         *
27  * The Nmap license generally prohibits companies from using and           *
28  * redistributing Nmap in commercial products, but we sell a special Nmap  *
29  * OEM Edition with a more permissive license and special features for     *
30  * this purpose. See https://nmap.org/oem                                  *
31  *                                                                         *
32  * If you have received a written Nmap license agreement or contract       *
33  * stating terms other than these (such as an Nmap OEM license), you may   *
34  * choose to use and redistribute Nmap under those terms instead.          *
35  *                                                                         *
36  * The official Nmap Windows builds include the Npcap software             *
37  * (https://npcap.org) for packet capture and transmission. It is under    *
38  * separate license terms which forbid redistribution without special      *
39  * permission. So the official Nmap Windows builds may not be              *
40  * redistributed without special permission (such as an Nmap OEM           *
41  * license).                                                               *
42  *                                                                         *
43  * Source is provided to this software because we believe users have a     *
44  * right to know exactly what a program is going to do before they run it. *
45  * This also allows you to audit the software for security holes.          *
46  *                                                                         *
47  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
48  * and add new features.  You are highly encouraged to submit your         *
49  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
50  * for possible incorporation into the main distribution. Unless you       *
51  * specify otherwise, it is understood that you are offering us very       *
52  * broad rights to use your submissions as described in the Nmap Public    *
53  * Source License Contributor Agreement. This is important because we      *
54  * fund the project by selling licenses with various terms, and also       *
55  * because the inability to relicense code has caused devastating          *
56  * problems for other Free Software projects (such as KDE and NASM).       *
57  *                                                                         *
58  * The free version of Nmap is distributed in the hope that it will be     *
59  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
60  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
61  * indemnification and commercial support are all available through the    *
62  * Npcap OEM program--see https://nmap.org/oem.                            *
63  *                                                                         *
64  ***************************************************************************/
65 
66 /* $Id: netutil.h 18098 2010-06-14 11:50:12Z luis $ */
67 
68 #ifndef _NETUTIL_H_
69 #define _NETUTIL_H_ 1
70 
71 #ifdef __cplusplus
72 extern "C" {
73 #endif
74 #include <pcap.h>
75 #ifdef __cplusplus
76 }
77 #endif
78 
79 #include "dnet.h"
80 #include <nbase.h>
81 
82 /* It is VERY important to never change the value of these two constants.
83  * Specially, OP_FAILURE should never be positive, as some pieces of code take
84  * that for granted. */
85 enum { OP_FAILURE = -1, OP_SUCCESS = 0 };
86 
87 
88 /* For systems without SCTP in netinet/in.h, such as MacOS X or Win */
89 #ifndef IPPROTO_SCTP
90 #define IPPROTO_SCTP 132
91 #endif
92 
93 /* Container used for information common to IPv4 and IPv6 headers, used by
94    ip_get_data. */
95 struct abstract_ip_hdr {
96   u8 version; /* 4 or 6. */
97   struct sockaddr_storage src;
98   struct sockaddr_storage dst;
99   u8 proto; /* IPv4 proto or IPv6 next header. */
100   u8 ttl;   /* IPv4 TTL or IPv6 hop limit. */
101   u32 ipid; /* IPv4 IP ID or IPv6 flow label. */
102 };
103 
104 #if defined(__GNUC__)
105 #define NORETURN __attribute__((noreturn))
106 #elif defined(_MSC_VER)
107 #define NORETURN __declspec(noreturn)
108 #else
109 #define NORETURN
110 #endif
111 
112 NORETURN void netutil_fatal(const char *str, ...)
113      __attribute__ ((format (printf, 1, 2)));
114 
115 int netutil_error(const char *str, ...)
116      __attribute__ ((format (printf, 1, 2)));
117 
118 /* This function converts zero-terminated 'txt' string to binary 'data'.
119    It is used to parse user input for ip options. Some examples of possible input
120    strings and results:
121    	'\x01*2\xA2'	-> [0x01,0x01,0xA2]	// with 'x' number is parsed in hex
122    	'\01\01\255'	-> [0x01,0x01,0xFF]	// without 'x' its in decimal
123    	'\x01\x00*2'	-> [0x01,0x00,0x00]	// '*' is copying char
124    	'R'		-> Record Route with 9 slots
125    	'S 192.168.0.1 172.16.0.1' -> Strict Route with 2 slots
126    	'L 192.168.0.1 172.16.0.1' -> Loose Route with 2 slots
127    	'T'		-> Record Timestamp with 9 slots
128    	'U'		-> Record Timestamp and Ip Address with 4 slots
129    On success, the function returns the length of the final binary
130    options stored in "data". In case of error, OP_FAILURE is returned
131    and the "errstr" buffer is filled with an error message
132    (unless it's NULL). Note that the returned error message does NOT
133    contain a newline character at the end. */
134 int parse_ip_options(const char *txt, u8 *data, int datalen, int* firsthopoff, int* lasthopoff, char *errstr, size_t errstrlen);
135 
136 /* Resolves the given hostname or IP address with getaddrinfo, and stores the
137    first result (if any) in *ss and *sslen. The value of port will be set in the
138    appropriate place in *ss; set to 0 if you don't care. af may be AF_UNSPEC, in
139    which case getaddrinfo may return e.g. both IPv4 and IPv6 results; which one
140    is first depends on the system configuration. Returns 0 on success, or a
141    getaddrinfo return code (suitable for passing to gai_strerror) on failure.
142    *ss and *sslen are always defined when this function returns 0. */
143 int resolve(const char *hostname, unsigned short port,
144   struct sockaddr_storage *ss, size_t *sslen, int af);
145 
146 /* As resolve, but do not do DNS resolution of hostnames; the first argument
147    must be the string representation of a numeric IP address. */
148 int resolve_numeric(const char *ip, unsigned short port,
149   struct sockaddr_storage *ss, size_t *sslen, int af);
150 
151 /*
152  * Returns 1 if this is a reserved IP address, where "reserved" means
153  * either a private address, non-routable address, or even a non-reserved
154  * but unassigned address which has an extremely high probability of being
155  * black-holed.
156  *
157  * We try to optimize speed when ordering the tests. This optimization
158  * assumes that all byte values are equally likely in the input.
159  *
160  * Warning: This function needs frequent attention because IANA has been
161  * allocating address blocks many times per year (although it's questionable
162  * how much longer this trend can be kept up).
163  *
164  * Check
165  * <http://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.txt>
166  * for the most recent assigments and
167  * <http://www.cymru.com/Documents/bogon-bn-nonagg.txt> for bogon
168  * netblocks.
169  */
170 int ip_is_reserved(struct in_addr *ip);
171 
172 
173 /* A couple of trivial functions that maintain a cache of IP to MAC
174  * Address entries. Function mac_cache_get() looks for the IPv4 address
175  * in ss and fills in the 'mac' parameter and returns true if it is
176  * found.  Otherwise (not found), the function returns false.
177  * Function mac_cache_set() adds an entry with the given ip (ss) and
178  * mac address.  An existing entry for the IP ss will be overwritten
179  * with the new MAC address.  mac_cache_set() always returns true. */
180 int mac_cache_get(const struct sockaddr_storage *ss, u8 *mac);
181 int mac_cache_set(const struct sockaddr_storage *ss, u8 *mac);
182 
183 const void *ip_get_data(const void *packet, unsigned int *len,
184   struct abstract_ip_hdr *hdr);
185 const void *ip_get_data_any(const void *packet, unsigned int *len,
186   struct abstract_ip_hdr *hdr);
187 /* Get the upper-layer protocol from an IPv4 packet. */
188 const void *ipv4_get_data(const struct ip *ip, unsigned int *len);
189 /* Get the upper-layer protocol from an IPv6 packet. This skips over known
190    extension headers. The length of the upper-layer payload is stored in *len.
191    The protocol is stored in *nxt. Returns NULL in case of error. */
192 const void *ipv6_get_data(const struct ip6_hdr *ip6, unsigned int *len, u8 *nxt);
193 const void *ipv6_get_data_any(const struct ip6_hdr *ip6, unsigned int *len, u8 *nxt);
194 const void *icmp_get_data(const struct icmp_hdr *icmp, unsigned int *len);
195 const void *icmpv6_get_data(const struct icmpv6_hdr *icmpv6, unsigned int *len);
196 
197 /* Standard BSD internet checksum routine. */
198 unsigned short in_cksum(u16 *ptr, int nbytes);
199 
200 /* Calculate the Internet checksum of some given data concatentated with the
201    IPv4 pseudo-header. See RFC 1071 and TCP/IP Illustrated sections 3.2, 11.3,
202    and 17.3. */
203 unsigned short ipv4_pseudoheader_cksum(const struct in_addr *src,
204   const struct in_addr *dst, u8 proto, u16 len, const void *hstart);
205 
206 /* Calculate the Internet checksum of some given data concatenated with the
207    IPv6 pseudo-header. See RFC 2460 section 8.1. */
208 u16 ipv6_pseudoheader_cksum(const struct in6_addr *src,
209   const struct in6_addr *dst, u8 nxt, u32 len, const void *hstart);
210 
211 void sethdrinclude(int sd);
212 void set_ipoptions(int sd, void *opts, size_t optslen);
213 void set_ttl(int sd, int ttl);
214 
215 /* Returns whether the system supports pcap_get_selectable_fd() properly */
216 int pcap_selectable_fd_valid();
217 int pcap_selectable_fd_one_to_one();
218 
219 /* Call this instead of pcap_get_selectable_fd directly (or your code
220    won't compile on Windows).  On systems which don't seem to support
221    the pcap_get_selectable_fd() function properly, returns -1,
222    otherwise simply calls pcap_selectable_fd and returns the
223    results.  If you just want to test whether the function is supported,
224    use pcap_selectable_fd_valid() instead. */
225 int my_pcap_get_selectable_fd(pcap_t *p);
226 
227 
228 /* These two function return -1 if we can't use select() on the pcap
229  * device, 0 for timeout, and >0 for success. If select() fails we bail
230  * out because it couldn't work with the file descriptor we got from
231  * my_pcap_get_selectable_fd() */
232 int pcap_select(pcap_t *p, struct timeval *timeout);
233 int pcap_select(pcap_t *p, long usecs);
234 
235 typedef enum { devt_ethernet, devt_loopback, devt_p2p, devt_other  } devtype;
236 
237 #define MAX_LINK_HEADERSZ 24
238 struct link_header {
239   int datalinktype; /* pcap_datalink(), such as DLT_EN10MB */
240   int headerlen; /* 0 if header was too big or unavailaable */
241   u8 header[MAX_LINK_HEADERSZ];
242 };
243 
244 /* Relevant (to Nmap) information about an interface */
245 struct interface_info {
246   char devname[16];
247   char devfullname[16]; /* can include alias info, such as eth0:2. */
248   struct sockaddr_storage addr;
249   u16 netmask_bits; /* CIDR-style.  So 24 means class C (255.255.255.0)*/
250   devtype device_type; /* devt_ethernet, devt_loopback, devt_p2p, devt_other */
251   unsigned int ifindex; /* index (as used by if_indextoname and sin6_scope_id) */
252   int device_up; /* True if the device is up (enabled) */
253   int mtu; /* Interface's MTU size */
254   u8 mac[6]; /* Interface MAC address if device_type is devt_ethernet */
255 };
256 
257 struct route_nfo {
258   struct interface_info ii;
259 
260 /* true if the target is directly connected on the network (no routing
261    required). */
262   int direct_connect;
263 
264 /* This is the source address that should be used by the packets.  It
265    may be different than ii.addr if you are using localhost interface
266    to scan the IP of another interface on the machine */
267   struct sockaddr_storage srcaddr;
268 
269   /* If direct_connect is 0, this is filled in with the next hop
270      required to route to the target */
271   struct sockaddr_storage nexthop;
272 };
273 
274 struct sys_route {
275   struct interface_info *device;
276   struct sockaddr_storage dest;
277   u16 netmask_bits;
278   struct sockaddr_storage gw; /* gateway - 0 if none */
279   int metric;
280 };
281 
282 struct eth_nfo {
283   char srcmac[6];
284   char dstmac[6];
285   eth_t *ethsd; // Optional, but improves performance.  Set to NULL if unavail
286   char devname[16]; // Only needed if ethsd is NULL.
287 };
288 
289 /* A simple function that caches the eth_t from dnet for one device,
290    to avoid opening, closing, and re-opening it thousands of tims.  If
291    you give a different device, this function will close the first
292    one.  Thus this should never be used by programs that need to deal
293    with multiple devices at once.  In addition, you MUST NEVER
294    eth_close() A DEVICE OBTAINED FROM THIS FUNCTION.  Instead, you can
295    call eth_close_cached() to close whichever device (if any) is
296    cached.  Returns NULL if it fails to open the device. */
297 eth_t *eth_open_cached(const char *device);
298 
299 /* See the description for eth_open_cached */
300 void eth_close_cached();
301 
302 /* Takes a protocol number like IPPROTO_TCP, IPPROTO_UDP, or
303  * IPPROTO_IP and returns a ascii representation (or "unknown" if it
304  * doesn't recognize the number).  Returned string is in lowercase. */
305 const char *proto2ascii_lowercase(u8 proto) ;
306 
307 /* Same as proto2ascii() but returns a string in uppercase. */
308 const char *proto2ascii_uppercase(u8 proto);
309 
310 /* Get an ASCII information about a tcp option which is pointed by
311    optp, with a length of len. The result is stored in the result
312    buffer. The result may look like "<mss 1452,sackOK,timestamp
313    45848914 0,nop,wscale 7>" */
314 void tcppacketoptinfo(u8 *optp, int len, char *result, int bufsize);
315 
316 /* Convert an IP address to the device (IE ppp0 eth0) using that
317  * address.  Supplied "dev" must be able to hold at least 32 bytes.
318  * Returns 0 on success or -1 in case of error. */
319 int ipaddr2devname( char *dev, const struct sockaddr_storage *addr );
320 
321 /* Convert a network interface name (IE ppp0 eth0) to an IP address.
322  * Returns 0 on success or -1 in case of error. */
323 int devname2ipaddr(char *dev, struct sockaddr_storage *addr);
324 
325 int sockaddr_equal(const struct sockaddr_storage *a,
326   const struct sockaddr_storage *b);
327 
328 int sockaddr_equal_netmask(const struct sockaddr_storage *a,
329   const struct sockaddr_storage *b, u16 nbits);
330 
331 int sockaddr_equal_zero(const struct sockaddr_storage *s);
332 
333 /* Returns an allocated array of struct interface_info representing the
334    available interfaces. The number of interfaces is returned in *howmany. This
335    function just does caching of results; the real work is done in
336    getinterfaces_dnet() or getinterfaces_siocgifconf().
337    On error, NULL is returned, howmany is set to -1 and the supplied
338    error buffer "errstr", if not NULL, will contain an error message. */
339 struct interface_info *getinterfaces(int *howmany, char *errstr, size_t errstrlen);
340 
341 /* This struct is abused to carry either routes or interfaces, depending on the
342    function it's used in. */
343 struct dnet_collector_route_nfo {
344   struct sys_route *routes;
345   int numroutes;
346   int capacity; /* Capacity of routes or ifaces, depending on context */
347   struct interface_info *ifaces;
348   int numifaces;
349 };
350 
351 /* Looks for an interface with the given name (iname) and address
352    family type, and returns the corresponding interface_info if found.
353    Will accept a match of devname or devfullname. Returns NULL if
354    none found */
355 struct interface_info *getInterfaceByName(const char *iname, int af);
356 
357 /* Parse the system routing table, converting each route into a
358    sys_route entry.  Returns an array of sys_routes.  numroutes is set
359    to the number of routes in the array.  The routing table is only
360    read the first time this is called -- later results are cached.
361    The returned route array is sorted by netmask with the most
362    specific matches first.
363    On error, NULL is returned, howmany is set to -1 and the supplied
364    error buffer "errstr", if not NULL, will contain an error message. */
365 struct sys_route *getsysroutes(int *howmany, char *errstr, size_t errstrlen);
366 
367 /* Tries to determine whether the supplied address corresponds to
368  * localhost. (eg: the address is something like 127.x.x.x, the address
369  * matches one of the local network interfaces' address, etc).
370  * Returns 1 if the address is thought to be localhost and 0 otherwise */
371 int islocalhost(const struct sockaddr_storage *ss);
372 
373 /* Determines whether the supplied address corresponds to a private,
374  * non-Internet-routable address. See RFC1918 for details.
375  * Also checks for link-local addresses per RFC3927.
376  * Returns 1 if the address is private or 0 otherwise. */
377 int isipprivate(const struct sockaddr_storage *addr);
378 
379 /* Takes binary data found in the IP Options field of an IPv4 packet
380  * and returns a string containing an ASCII description of the options
381  * found. The function returns a pointer to a static buffer that
382  * subsequent calls will overwrite. On error, NULL is returned. */
383 char *format_ip_options(const u8* ipopt, int ipoptlen);
384 
385 /* Returns a buffer of ASCII information about an IP packet that may
386  * look like "TCP 127.0.0.1:50923 > 127.0.0.1:3 S ttl=61 id=39516
387  * iplen=40 seq=625950769" or "ICMP PING (0/1) ttl=61 id=39516 iplen=40".
388  * Returned buffer is static so it is NOT safe to call this in
389  * multi-threaded environments without appropriate sync protection, or
390  * call it twice in the same sentence (eg: as two printf parameters).
391  * Obviously, the caller should never attempt to free() the buffer. The
392  * returned buffer is guaranteed to be NULL-terminated but no
393  * assumptions should be made concerning its length.
394  *
395  * The function provides full support for IPv4,TCP,UDP,SCTP and ICMPv4.
396  * It also provides support for standard IPv6 but not for its extension
397  * headers. If an IPv6 packet contains an ICMPv6 Header, the output will
398  * reflect this but no parsing of ICMPv6 contents will be performed.
399  *
400  * The output has three different levels of detail. Parameter "detail"
401  * determines how verbose the output should be. It should take one of
402  * the following values:
403  *
404  *    LOW_DETAIL    (0x01): Traditional output.
405  *    MEDIUM_DETAIL (0x02): More verbose than traditional.
406  *    HIGH_DETAIL   (0x03): Contents of virtually every field of the
407  *                          protocol headers .
408  */
409 #define LOW_DETAIL     1
410 #define MEDIUM_DETAIL  2
411 #define HIGH_DETAIL    3
412 const char *ippackethdrinfo(const u8 *packet, u32 len, int detail);
413 
414 
415 /* Takes an IPv4 destination address (dst) and tries to determine the
416  * source address and interface necessary to route to this address.
417  * If no route is found, 0 is returned and "rnfo" is undefined.  If
418  * a route is found, 1 is returned and "rnfo" is filled in with all
419  * of the routing details. If the source address needs to be spoofed,
420  * it should be passed through "spoofss" (otherwise NULL should be
421  * specified), along with a suitable network device (parameter "device").
422  * Even if spoofss is NULL, if user specified a network device with -e,
423  * it should still be passed. Note that it's OK to pass either NULL or
424  * an empty string as the "device", as long as spoofss==NULL. */
425 int route_dst(const struct sockaddr_storage *dst, struct route_nfo *rnfo,
426               const char *device, const struct sockaddr_storage *spoofss);
427 
428 /* Send an IP packet over a raw socket. */
429 int send_ip_packet_sd(int sd, const struct sockaddr_in *dst, const u8 *packet, unsigned int packetlen);
430 
431 /* Send an IP packet over an ethernet handle. */
432 int send_ip_packet_eth(const struct eth_nfo *eth, const u8 *packet, unsigned int packetlen);
433 
434 /* Sends the supplied pre-built IPv4 packet. The packet is sent through
435  * the raw socket "sd" if "eth" is NULL. Otherwise, it gets sent at raw
436  * ethernet level. */
437 int send_ip_packet_eth_or_sd(int sd, const struct eth_nfo *eth,
438   const struct sockaddr_in *dst, const u8 *packet, unsigned int packetlen);
439 
440 /* Sends an IPv4 packet. */
441 int send_ipv6_packet_eth_or_sd(int sd, const struct eth_nfo *eth,
442   const struct sockaddr_in6 *dst, const u8 *packet, unsigned int packetlen);
443 
444 /* Create and send all fragments of a pre-built IPv4 packet.
445  * Minimal MTU for IPv4 is 68 and maximal IPv4 header size is 60
446  * which gives us a right to cut TCP header after 8th byte */
447 int send_frag_ip_packet(int sd, const struct eth_nfo *eth,
448   const struct sockaddr_in *dst,
449   const u8 *packet, unsigned int packetlen, u32 mtu);
450 
451 /* Wrapper for system function sendto(), which retries a few times when
452  * the call fails. It also prints informational messages about the
453  * errors encountered. It returns the number of bytes sent or -1 in
454  * case of error. */
455 int Sendto(const char *functionname, int sd, const unsigned char *packet,
456            int len, unsigned int flags, struct sockaddr *to, int tolen);
457 
458 /* This function is  used to obtain a packet capture handle to look at
459  * packets on the network. It is actually a wrapper for libpcap's
460  * pcap_open_live() that takes care of compatibility issues and error
461  * checking.  Prints an error and fatal()s if the call fails, so a
462  * valid pcap_t will always be returned. */
463 pcap_t *my_pcap_open_live(const char *device, int snaplen, int promisc, int to_ms);
464 
465 /* Set a pcap filter */
466 void set_pcap_filter(const char *device, pcap_t *pd, const char *bpf, ...);
467 
468 /* Issues an ARP request for the MAC of targetss (which will be placed
469    in targetmac if obtained) from the source IP (srcip) and source mac
470    (srcmac) given.  "The request is ussued using device dev to the
471    broadcast MAC address.  The transmission is attempted up to 3
472    times.  If none of these elicit a response, false will be returned.
473    If the mac is determined, true is returned. The last parameter is
474    a pointer to a callback function that can be used for packet traceing.
475    This is intended to be used by Nmap only. Any other calling this
476    should pass NULL instead. */
477 bool doArp(const char *dev, const u8 *srcmac,
478                   const struct sockaddr_storage *srcip,
479                   const struct sockaddr_storage *targetip,
480                   u8 *targetmac,
481                   void (*traceArp_callback)(int, const u8 *, u32 , struct timeval *));
482 
483 
484 /* Issues an Neighbor Solicitation for the MAC of targetss (which will be placed
485    in targetmac if obtained) from the source IP (srcip) and source mac
486    (srcmac) given.  "The request is ussued using device dev to the
487    multicast MAC address.  The transmission is attempted up to 3
488    times.  If none of these elicit a response, false will be returned.
489    If the mac is determined, true is returned. The last parameter is
490    a pointer to a callback function that can be used for packet tracing.
491    This is intended to be used by Nmap only. Any other calling this
492    should pass NULL instead. */
493 bool doND(const char *dev, const u8 *srcmac,
494                   const struct sockaddr_storage *srcip,
495                    const struct sockaddr_storage *targetip,
496                    u8 *targetmac,
497                    void (*traceArp_callback)(int, const u8 *, u32 , struct timeval *)
498                     ) ;
499 
500 /* Attempts to read one IPv4/Ethernet ARP reply packet from the pcap
501    descriptor pd.  If it receives one, fills in sendermac (must pass
502    in 6 bytes), senderIP, and rcvdtime (can be NULL if you don't care)
503    and returns 1.  If it times out and reads no arp requests, returns
504    0.  to_usec is the timeout period in microseconds.  Use 0 to avoid
505    blocking to the extent possible.  Returns -1 or exits if there is
506    an error.  The last parameter is a pointer to a callback function
507    that can be used for packet tracing. This is intended to be used
508    by Nmap only. Any other calling this should pass NULL instead. */
509 int read_arp_reply_pcap(pcap_t *pd, u8 *sendermac,
510                         struct in_addr *senderIP, long to_usec,
511                         struct timeval *rcvdtime,
512                         void (*traceArp_callback)(int, const u8 *, u32 , struct timeval *));
513 int read_ns_reply_pcap(pcap_t *pd, u8 *sendermac,
514                         struct sockaddr_in6 *senderIP, long to_usec,
515                         struct timeval *rcvdtime, bool *has_mac,
516                         void (*traceArp_callback)(int, const u8 *, u32 , struct timeval *));
517 
518 /* Attempts to read one IP packet from the pcap descriptor pd. Input parameters are pd,
519    to_usec, and accept_callback. If a received frame passes accept_callback,
520    then the output parameters p, head, rcvdtime, datalink, and offset are filled
521    in, and the function returns 1. If no frame passes before the timeout, then
522    the function returns 0 and the output parameters are undefined. */
523 int read_reply_pcap(pcap_t *pd, long to_usec,
524   bool (*accept_callback)(const unsigned char *, const struct pcap_pkthdr *, int, size_t),
525   const unsigned char **p, struct pcap_pkthdr **head, struct timeval *rcvdtime,
526   int *datalink, size_t *offset);
527 
528 /* Read a single host specification from a file, as for -iL and --excludefile.
529    It returns the length of the string read; an overflow is indicated when the
530    return value is >= n. Returns 0 if there was no specification to be read. The
531    buffer is always null-terminated. */
532 size_t read_host_from_file(FILE *fp, char *buf, size_t n);
533 
534 /* Return next target host specification from the supplied stream.
535  * if parameter "random" is set to true, then the function will
536  * return a random, non-reserved, IP address in decimal-dot notation */
537 const char *grab_next_host_spec(FILE *inputfd, bool random, int argc, const char **fakeargv);
538 
539 #ifdef WIN32
540 /* Convert a dnet interface name into the long pcap style.  This also caches the
541    data to speed things up.  Fills out pcapdev (up to pcapdevlen) and returns
542    true if it finds anything. Otherwise returns false.  This is only necessary
543    on Windows. */
544 int DnetName2PcapName(const char *dnetdev, char *pcapdev, int pcapdevlen);
545 #endif
546 
547 /** Tries to increase the open file descriptor limit for this process.
548   * @param "desired" is the number of desired max open descriptors. Pass a
549   * negative value to set the maximum allowed.
550   * @return the number of max open descriptors that could be set, or 0 in case
551   * of failure.
552   * @warning if "desired" is less than the current limit, no action is
553   * performed. This function may only be used to increase the limit, not to
554   * decrease it. */
555 int set_max_open_descriptors(int desired_max);
556 
557 /** Returns the open file descriptor limit for this process.
558   * @return the number of max open descriptors or 0 in case of failure. */
559 int get_max_open_descriptors();
560 
561 /* Maximize the open file descriptor limit for this process go up to the
562    max allowed  */
563 int max_sd();
564 
565 #endif /* _NETUTIL_H_ */
566