xref: /freebsd/contrib/libpcap/sockutils.c (revision 7a7741af18d6c8a804cc643cb7ecda9d730c6aa6)
1 /*
2  * Copyright (c) 2002 - 2003
3  * NetGroup, Politecnico di Torino (Italy)
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the Politecnico di Torino nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32 
33 #include <config.h>
34 
35 /*
36  * \file sockutils.c
37  *
38  * The goal of this file is to provide a common set of primitives for socket
39  * manipulation.
40  *
41  * Although the socket interface defined in the RFC 2553 (and its updates)
42  * is excellent, there are still differences between the behavior of those
43  * routines on UN*X and Windows, and between UN*Xes.
44  *
45  * These calls provide an interface similar to the socket interface, but
46  * that hides the differences between operating systems.  It does not
47  * attempt to significantly improve on the socket interface in other
48  * ways.
49  */
50 
51 #include "ftmacros.h"
52 
53 #include <string.h>
54 #include <errno.h>	/* for the errno variable */
55 #include <stdio.h>	/* for the stderr file */
56 #include <stdlib.h>	/* for malloc() and free() */
57 #include <limits.h>	/* for INT_MAX */
58 
59 #include "pcap-int.h"
60 
61 #include "sockutils.h"
62 #include "portability.h"
63 
64 #ifdef _WIN32
65   /*
66    * Winsock initialization.
67    *
68    * Ask for Winsock 2.2.
69    */
70   #define WINSOCK_MAJOR_VERSION 2
71   #define WINSOCK_MINOR_VERSION 2
72 
73   static int sockcount = 0;	/*!< Variable that allows calling the WSAStartup() only one time */
74 #endif
75 
76 /* Some minor differences between UNIX and Win32 */
77 #ifdef _WIN32
78   #define SHUT_WR SD_SEND	/* The control code for shutdown() is different in Win32 */
79 #endif
80 
81 /* Size of the buffer that has to keep error messages */
82 #define SOCK_ERRBUF_SIZE 1024
83 
84 /* Constants; used in order to keep strings here */
85 #define SOCKET_NO_NAME_AVAILABLE "No name available"
86 #define SOCKET_NO_PORT_AVAILABLE "No port available"
87 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
88 
89 /*
90  * On UN*X, send() and recv() return ssize_t.
91  *
92  * On Windows, send() and recv() return an int.
93  *
94  *   With MSVC, there *is* no ssize_t.
95  *
96  *   With MinGW, there is an ssize_t type; it is either an int (32 bit)
97  *   or a long long (64 bit).
98  *
99  * So, on Windows, if we don't have ssize_t defined, define it as an
100  * int, so we can use it, on all platforms, as the type of variables
101  * that hold the return values from send() and recv().
102  */
103 #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
104 typedef int ssize_t;
105 #endif
106 
107 /****************************************************
108  *                                                  *
109  * Locally defined functions                        *
110  *                                                  *
111  ****************************************************/
112 
113 static int sock_ismcastaddr(const struct sockaddr *saddr);
114 
115 /****************************************************
116  *                                                  *
117  * Function bodies                                  *
118  *                                                  *
119  ****************************************************/
120 
121 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
122 const uint8_t *fuzzBuffer;
123 size_t fuzzSize;
124 size_t fuzzPos;
125 
126 void sock_initfuzz(const uint8_t *Data, size_t Size) {
127 	fuzzPos = 0;
128 	fuzzSize = Size;
129 	fuzzBuffer = Data;
130 }
131 
132 static int fuzz_recv(char *bufp, int remaining) {
133 	if (remaining > fuzzSize - fuzzPos) {
134 		remaining = fuzzSize - fuzzPos;
135 	}
136 	if (fuzzPos < fuzzSize) {
137 		memcpy(bufp, fuzzBuffer + fuzzPos, remaining);
138 	}
139 	fuzzPos += remaining;
140 	return remaining;
141 }
142 #endif
143 
144 int sock_geterrcode(void)
145 {
146 #ifdef _WIN32
147 	return GetLastError();
148 #else
149 	return errno;
150 #endif
151 }
152 
153 /*
154  * Format an error message given an errno value (UN*X) or a Winsock error
155  * (Windows).
156  */
157 void sock_vfmterrmsg(char *errbuf, size_t errbuflen, int errcode,
158     const char *fmt, va_list ap)
159 {
160 	if (errbuf == NULL)
161 		return;
162 
163 #ifdef _WIN32
164 	pcapint_vfmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
165 	    fmt, ap);
166 #else
167 	pcapint_vfmt_errmsg_for_errno(errbuf, errbuflen, errcode,
168 	    fmt, ap);
169 #endif
170 }
171 
172 void sock_fmterrmsg(char *errbuf, size_t errbuflen, int errcode,
173     const char *fmt, ...)
174 {
175 	va_list ap;
176 
177 	va_start(ap, fmt);
178 	sock_vfmterrmsg(errbuf, errbuflen, errcode, fmt, ap);
179 	va_end(ap);
180 }
181 
182 /*
183  * Format an error message for the last socket error.
184  */
185 void sock_geterrmsg(char *errbuf, size_t errbuflen, const char *fmt, ...)
186 {
187 	va_list ap;
188 
189 	va_start(ap, fmt);
190 	sock_vfmterrmsg(errbuf, errbuflen, sock_geterrcode(), fmt, ap);
191 	va_end(ap);
192 }
193 
194 /*
195  * Types of error.
196  *
197  * These are sorted by how likely they are to be the "underlying" problem,
198  * so that lower-rated errors for a given address in a given family
199  * should not overwrite higher-rated errors for another address in that
200  * family, and higher-rated errors should overwrite lower-rated errors.
201  */
202 typedef enum {
203 	SOCK_CONNERR,		/* connection error */
204 	SOCK_HOSTERR,		/* host error */
205 	SOCK_NETERR,		/* network error */
206 	SOCK_AFNOTSUPERR,	/* address family not supported */
207 	SOCK_UNKNOWNERR,	/* unknown error */
208 	SOCK_NOERR		/* no error */
209 } sock_errtype;
210 
211 static sock_errtype sock_geterrtype(int errcode)
212 {
213 	switch (errcode) {
214 
215 #ifdef _WIN32
216 	case WSAECONNRESET:
217 	case WSAECONNABORTED:
218 	case WSAECONNREFUSED:
219 #else
220 	case ECONNRESET:
221 	case ECONNABORTED:
222 	case ECONNREFUSED:
223 #endif
224 		/*
225 		 * Connection error; this means the problem is probably
226 		 * that there's no server set up on the remote machine,
227 		 * or that it is set up, but it's IPv4-only or IPv6-only
228 		 * and we're trying the wrong address family.
229 		 *
230 		 * These overwrite all other errors, as they indicate
231 		 * that, even if something else went wrong in another
232 		 * attempt, this probably wouldn't work even if the
233 		 * other problems were fixed.
234 		 */
235 		return (SOCK_CONNERR);
236 
237 #ifdef _WIN32
238 	case WSAENETUNREACH:
239 	case WSAETIMEDOUT:
240 	case WSAEHOSTDOWN:
241 	case WSAEHOSTUNREACH:
242 #else
243 	case ENETUNREACH:
244 	case ETIMEDOUT:
245 	case EHOSTDOWN:
246 	case EHOSTUNREACH:
247 #endif
248 		/*
249 		 * Network errors that could be IPv4-specific, IPv6-
250 		 * specific, or present with both.
251 		 *
252 		 * Don't overwrite connection errors, but overwrite
253 		 * everything else.
254 		 */
255 		return (SOCK_HOSTERR);
256 
257 #ifdef _WIN32
258 	case WSAENETDOWN:
259 	case WSAENETRESET:
260 #else
261 	case ENETDOWN:
262 	case ENETRESET:
263 #endif
264 		/*
265 		 * Network error; this means we don't know whether
266 		 * there's a server set up on the remote machine,
267 		 * and we don't have a reason to believe that IPv6
268 		 * any worse or better than IPv4.
269 		 *
270 		 * These probably indicate a local failure, e.g.
271 		 * an interface is down.
272 		 *
273 		 * Don't overwrite connection errors or host errors,
274 		 * but overwrite everything else.
275 		 */
276 		return (SOCK_NETERR);
277 
278 #ifdef _WIN32
279 	case WSAEAFNOSUPPORT:
280 #else
281 	case EAFNOSUPPORT:
282 #endif
283 		/*
284 		 * "Address family not supported" probably means
285 		 * "No soup^WIPv6 for you!".
286 		 *
287 		 * Don't overwrite connection errors, host errors, or
288 		 * network errors (none of which we should get for this
289 		 * address family if it's not supported), but overwrite
290 		 * everything else.
291 		 */
292 		return (SOCK_AFNOTSUPERR);
293 
294 	default:
295 		/*
296 		 * Anything else.
297 		 *
298 		 * Don't overwrite any errors.
299 		 */
300 		return (SOCK_UNKNOWNERR);
301 	}
302 }
303 
304 /*
305  * \brief This function initializes the socket mechanism if it hasn't
306  * already been initialized or reinitializes it after it has been
307  * cleaned up.
308  *
309  * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
310  * initialize Winsock.
311  *
312  * \param errbuf: a pointer to an user-allocated buffer that will contain
313  * the complete error message. This buffer has to be at least 'errbuflen'
314  * in length. It can be NULL; in this case no error message is supplied.
315  *
316  * \param errbuflen: length of the buffer that will contains the error.
317  * The error message cannot be larger than 'errbuflen - 1' because the
318  * last char is reserved for the string terminator.
319  *
320  * \return '0' if everything is fine, '-1' if some errors occurred. The
321  * error message is returned in the buffer pointed to by 'errbuf' variable.
322  */
323 #ifdef _WIN32
324 int sock_init(char *errbuf, int errbuflen)
325 {
326 	if (sockcount == 0)
327 	{
328 		WSADATA wsaData;			/* helper variable needed to initialize Winsock */
329 
330 		if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
331 		    WINSOCK_MINOR_VERSION), &wsaData) != 0)
332 		{
333 			if (errbuf)
334 				snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
335 			return -1;
336 		}
337 	}
338 
339 	sockcount++;
340 	return 0;
341 }
342 #else
343 int sock_init(char *errbuf _U_, int errbuflen _U_)
344 {
345 	/*
346 	 * Nothing to do on UN*Xes.
347 	 */
348 	return 0;
349 }
350 #endif
351 
352 /*
353  * \brief This function cleans up the socket mechanism if we have no
354  * sockets left open.
355  *
356  * On UN*Xes, it doesn't need to do anything; on Windows, it needs
357  * to clean up Winsock.
358  *
359  * \return No error values.
360  */
361 void sock_cleanup(void)
362 {
363 #ifdef _WIN32
364 	sockcount--;
365 
366 	if (sockcount == 0)
367 		WSACleanup();
368 #endif
369 }
370 
371 /*
372  * \brief It checks if the sockaddr variable contains a multicast address.
373  *
374  * \return '0' if the address is multicast, '-1' if it is not.
375  */
376 static int sock_ismcastaddr(const struct sockaddr *saddr)
377 {
378 	if (saddr->sa_family == PF_INET)
379 	{
380 		struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
381 		if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
382 		else return -1;
383 	}
384 	else
385 	{
386 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
387 		if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
388 		else return -1;
389 	}
390 }
391 
392 struct addr_status {
393 	struct addrinfo *info;
394 	int errcode;
395 	sock_errtype errtype;
396 };
397 
398 /*
399  * Sort by IPv4 address vs. IPv6 address.
400  */
401 static int compare_addrs_to_try_by_address_family(const void *a, const void *b)
402 {
403 	const struct addr_status *addr_a = (const struct addr_status *)a;
404 	const struct addr_status *addr_b = (const struct addr_status *)b;
405 
406 	return addr_a->info->ai_family - addr_b->info->ai_family;
407 }
408 
409 /*
410  * Sort by error type and, within a given error type, by error code and,
411  * within a given error code, by IPv4 address vs. IPv6 address.
412  */
413 static int compare_addrs_to_try_by_status(const void *a, const void *b)
414 {
415 	const struct addr_status *addr_a = (const struct addr_status *)a;
416 	const struct addr_status *addr_b = (const struct addr_status *)b;
417 
418 	if (addr_a->errtype == addr_b->errtype)
419 	{
420 		if (addr_a->errcode == addr_b->errcode)
421 		{
422 			return addr_a->info->ai_family - addr_b->info->ai_family;
423 		}
424 		return addr_a->errcode - addr_b->errcode;
425 	}
426 
427 	return addr_a->errtype - addr_b->errtype;
428 }
429 
430 static PCAP_SOCKET sock_create_socket(struct addrinfo *addrinfo, char *errbuf,
431     int errbuflen)
432 {
433 	PCAP_SOCKET sock;
434 #ifdef SO_NOSIGPIPE
435 	int on = 1;
436 #endif
437 
438 	sock = socket(addrinfo->ai_family, addrinfo->ai_socktype,
439 	    addrinfo->ai_protocol);
440 	if (sock == INVALID_SOCKET)
441 	{
442 		sock_geterrmsg(errbuf, errbuflen, "socket() failed");
443 		return INVALID_SOCKET;
444 	}
445 
446 	/*
447 	 * Disable SIGPIPE, if we have SO_NOSIGPIPE.  We don't want to
448 	 * have to deal with signals if the peer closes the connection,
449 	 * especially in client programs, which may not even be aware that
450 	 * they're sending to sockets.
451 	 */
452 #ifdef SO_NOSIGPIPE
453 	if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
454 	    sizeof (int)) == -1)
455 	{
456 		sock_geterrmsg(errbuf, errbuflen,
457 		    "setsockopt(SO_NOSIGPIPE) failed");
458 		closesocket(sock);
459 		return INVALID_SOCKET;
460 	}
461 #endif
462 	return sock;
463 }
464 
465 /*
466  * \brief It initializes a network connection both from the client and the server side.
467  *
468  * In case of a client socket, this function calls socket() and connect().
469  * In the meanwhile, it checks for any socket error.
470  * If an error occurs, it writes the error message into 'errbuf'.
471  *
472  * In case of a server socket, the function calls socket(), bind() and listen().
473  *
474  * This function is usually preceded by the sock_initaddress().
475  *
476  * \param host: for client sockets, the host name to which we're trying
477  * to connect.
478  *
479  * \param addrinfo: pointer to an addrinfo variable which will be used to
480  * open the socket and such. This variable is the one returned by the previous call to
481  * sock_initaddress().
482  *
483  * \param server: '1' if this is a server socket, '0' otherwise.
484  *
485  * \param nconn: number of the connections that are allowed to wait into the listen() call.
486  * This value has no meanings in case of a client socket.
487  *
488  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
489  * error message. This buffer has to be at least 'errbuflen' in length.
490  * It can be NULL; in this case the error cannot be printed.
491  *
492  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
493  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
494  *
495  * \return the socket that has been opened (that has to be used in the following sockets calls)
496  * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
497  * in the 'errbuf' variable.
498  */
499 PCAP_SOCKET sock_open(const char *host, struct addrinfo *addrinfo,
500     int server, int nconn, char *errbuf, int errbuflen)
501 {
502 	PCAP_SOCKET sock;
503 
504 	/* This is a server socket */
505 	if (server)
506 	{
507 		int on;
508 
509 		/*
510 		 * Attempt to create the socket.
511 		 */
512 		sock = sock_create_socket(addrinfo, errbuf, errbuflen);
513 		if (sock == INVALID_SOCKET)
514 		{
515 			return INVALID_SOCKET;
516 		}
517 
518 		/*
519 		 * Allow a new server to bind the socket after the old one
520 		 * exited, even if lingering sockets are still present.
521 		 *
522 		 * Don't treat an error as a failure.
523 		 */
524 		on = 1;
525 		(void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
526 		    (char *)&on, sizeof (on));
527 
528 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
529 		/*
530 		 * Force the use of IPv6-only addresses.
531 		 *
532 		 * RFC 3493 indicates that you can support IPv4 on an
533 		 * IPv6 socket:
534 		 *
535 		 *    https://tools.ietf.org/html/rfc3493#section-3.7
536 		 *
537 		 * and that this is the default behavior.  This means
538 		 * that if we first create an IPv6 socket bound to the
539 		 * "any" address, it is, in effect, also bound to the
540 		 * IPv4 "any" address, so when we create an IPv4 socket
541 		 * and try to bind it to the IPv4 "any" address, it gets
542 		 * EADDRINUSE.
543 		 *
544 		 * Not all network stacks support IPv4 on IPv6 sockets;
545 		 * pre-NT 6 Windows stacks don't support it, and the
546 		 * OpenBSD stack doesn't support it for security reasons
547 		 * (see the OpenBSD inet6(4) man page).  Therefore, we
548 		 * don't want to rely on this behavior.
549 		 *
550 		 * So we try to disable it, using either the IPV6_V6ONLY
551 		 * option from RFC 3493:
552 		 *
553 		 *    https://tools.ietf.org/html/rfc3493#section-5.3
554 		 *
555 		 * or the IPV6_BINDV6ONLY option from older UN*Xes.
556 		 */
557 #ifndef IPV6_V6ONLY
558   /* For older systems */
559   #define IPV6_V6ONLY IPV6_BINDV6ONLY
560 #endif /* IPV6_V6ONLY */
561 		if (addrinfo->ai_family == PF_INET6)
562 		{
563 			on = 1;
564 			if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
565 			    (char *)&on, sizeof (int)) == -1)
566 			{
567 				if (errbuf)
568 					snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
569 				closesocket(sock);
570 				return INVALID_SOCKET;
571 			}
572 		}
573 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
574 
575 		/* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
576 		if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
577 		{
578 			sock_geterrmsg(errbuf, errbuflen, "bind() failed");
579 			closesocket(sock);
580 			return INVALID_SOCKET;
581 		}
582 
583 		if (addrinfo->ai_socktype == SOCK_STREAM)
584 			if (listen(sock, nconn) == -1)
585 			{
586 				sock_geterrmsg(errbuf, errbuflen,
587 				    "listen() failed");
588 				closesocket(sock);
589 				return INVALID_SOCKET;
590 			}
591 
592 		/* server side ended */
593 		return sock;
594 	}
595 	else	/* we're the client */
596 	{
597 		struct addr_status *addrs_to_try;
598 		struct addrinfo *tempaddrinfo;
599 		size_t numaddrinfos;
600 		size_t i;
601 		int current_af = AF_UNSPEC;
602 
603 		/*
604 		 * We have to loop though all the addrinfos returned.
605 		 * For instance, we can have both IPv6 and IPv4 addresses,
606 		 * but the service we're trying to connect to is unavailable
607 		 * in IPv6, so we have to try in IPv4 as well.
608 		 *
609 		 * How many addrinfos do we have?
610 		 */
611 		numaddrinfos =  0;
612 		for (tempaddrinfo = addrinfo; tempaddrinfo != NULL;
613 		    tempaddrinfo = tempaddrinfo->ai_next)
614 		{
615 			numaddrinfos++;
616 		}
617 
618 		if (numaddrinfos == 0)
619 		{
620 			snprintf(errbuf, errbuflen,
621 			    "There are no addresses in the address list");
622 			return INVALID_SOCKET;
623 		}
624 
625 		/*
626 		 * Allocate an array of struct addr_status and fill it in.
627 		 */
628 		addrs_to_try = calloc(numaddrinfos, sizeof *addrs_to_try);
629 		if (addrs_to_try == NULL)
630 		{
631 			snprintf(errbuf, errbuflen,
632 			    "Out of memory connecting to %s", host);
633 			return INVALID_SOCKET;
634 		}
635 
636 		for (tempaddrinfo = addrinfo, i = 0; tempaddrinfo != NULL;
637 		    tempaddrinfo = tempaddrinfo->ai_next, i++)
638 		{
639 			addrs_to_try[i].info = tempaddrinfo;
640 			addrs_to_try[i].errcode = 0;
641 			addrs_to_try[i].errtype = SOCK_NOERR;
642 		}
643 
644 		/*
645 		 * Sort the structures to put the IPv4 addresses before the
646 		 * IPv6 addresses; we will have to create an IPv4 socket
647 		 * for the IPv4 addresses and an IPv6 socket for the IPv6
648 		 * addresses (one of the arguments to socket() is the
649 		 * address/protocol family to use, and IPv4 and IPv6 are
650 		 * separate address/protocol families).
651 		 */
652 		qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
653 		    compare_addrs_to_try_by_address_family);
654 
655 		/* Start out with no socket. */
656 		sock = INVALID_SOCKET;
657 
658 		/*
659 		 * Now try them all.
660 		 */
661 		for (i = 0; i < numaddrinfos; i++)
662 		{
663 			tempaddrinfo = addrs_to_try[i].info;
664 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
665 			break;
666 #endif
667 			/*
668 			 * If we have a socket, but it's for a
669 			 * different address family, close it.
670 			 */
671 			if (sock != INVALID_SOCKET &&
672 			    current_af != tempaddrinfo->ai_family)
673 			{
674 				closesocket(sock);
675 				sock = INVALID_SOCKET;
676 			}
677 
678 			/*
679 			 * If we don't have a socket, open one
680 			 * for *this* address's address family.
681 			 */
682 			if (sock == INVALID_SOCKET)
683 			{
684 				sock = sock_create_socket(tempaddrinfo,
685 				    errbuf, errbuflen);
686 				if (sock == INVALID_SOCKET)
687 				{
688 					free(addrs_to_try);
689 					return INVALID_SOCKET;
690 				}
691 			}
692 			if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
693 			{
694 				addrs_to_try[i].errcode = sock_geterrcode();
695 				addrs_to_try[i].errtype =
696 				   sock_geterrtype(addrs_to_try[i].errcode);
697 			}
698 			else
699 				break;
700 		}
701 
702 		/*
703 		 * Check how we exited from the previous loop.
704 		 * If tempaddrinfo is equal to NULL, it means that all
705 		 * the connect() attempts failed.  Construct an
706 		 * error message.
707 		 */
708 		if (i == numaddrinfos)
709 		{
710 			int same_error_for_all;
711 			int first_error;
712 
713 			closesocket(sock);
714 
715 			/*
716 			 * Sort the statuses to group together categories
717 			 * of errors, errors within categories, and
718 			 * address families within error sets.
719 			 */
720 			qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
721 			    compare_addrs_to_try_by_status);
722 
723 			/*
724 			 * Are all the errors the same?
725 			 */
726 			same_error_for_all = 1;
727 			first_error = addrs_to_try[0].errcode;
728 			for (i = 1; i < numaddrinfos; i++)
729 			{
730 				if (addrs_to_try[i].errcode != first_error)
731 				{
732 					same_error_for_all = 0;
733 					break;
734 				}
735 			}
736 
737 			if (same_error_for_all) {
738 				/*
739 				 * Yes.  No need to show the IP
740 				 * addresses.
741 				 */
742 				if (addrs_to_try[0].errtype == SOCK_CONNERR) {
743 					/*
744 					 * Connection error; note that
745 					 * the daemon might not be set
746 					 * up correctly, or set up at all.
747 					 */
748 					sock_fmterrmsg(errbuf, errbuflen,
749 					    addrs_to_try[0].errcode,
750 					    "Is the server properly installed? Cannot connect to %s",
751 					    host);
752 				} else {
753 					sock_fmterrmsg(errbuf, errbuflen,
754 					    addrs_to_try[0].errcode,
755 					    "Cannot connect to %s", host);
756 				}
757 			} else {
758 				/*
759 				 * Show all the errors and the IP addresses
760 				 * to which they apply.
761 				 */
762 				char *errbufptr;
763 				size_t bufspaceleft;
764 				size_t msglen;
765 
766 				snprintf(errbuf, errbuflen,
767 				    "Connect to %s failed: ", host);
768 
769 				msglen = strlen(errbuf);
770 				errbufptr = errbuf + msglen;
771 				bufspaceleft = errbuflen - msglen;
772 
773 				for (i = 0; i < numaddrinfos &&
774 				    addrs_to_try[i].errcode != SOCK_NOERR;
775 				    i++)
776 				{
777 					/*
778 					 * Get the string for the address
779 					 * and port that got this error.
780 					 */
781 					sock_getascii_addrport((struct sockaddr_storage *) addrs_to_try[i].info->ai_addr,
782 					    errbufptr, (int)bufspaceleft,
783 					    NULL, 0, NI_NUMERICHOST, NULL, 0);
784 					msglen = strlen(errbuf);
785 					errbufptr = errbuf + msglen;
786 					bufspaceleft = errbuflen - msglen;
787 
788 					if (i + 1 < numaddrinfos &&
789 					    addrs_to_try[i + 1].errcode == addrs_to_try[i].errcode)
790 					{
791 						/*
792 						 * There's another error
793 						 * after this, and it has
794 						 * the same error code.
795 						 *
796 						 * Append a comma, as the
797 						 * list of addresses with
798 						 * this error has another
799 						 * entry.
800 						 */
801 						snprintf(errbufptr, bufspaceleft,
802 						    ", ");
803 					}
804 					else
805 					{
806 						/*
807 						 * Either there are no
808 						 * more errors after this,
809 						 * or the next error is
810 						 * different.
811 						 *
812 						 * Append a colon and
813 						 * the message for tis
814 						 * error, followed by a
815 						 * comma if there are
816 						 * more errors.
817 						 */
818 						sock_fmterrmsg(errbufptr,
819 						    bufspaceleft,
820 						    addrs_to_try[i].errcode,
821 						    "%s", "");
822 						msglen = strlen(errbuf);
823 						errbufptr = errbuf + msglen;
824 						bufspaceleft = errbuflen - msglen;
825 
826 						if (i + 1 < numaddrinfos &&
827 						    addrs_to_try[i + 1].errcode != SOCK_NOERR)
828 						{
829 							/*
830 							 * More to come.
831 							 */
832 							snprintf(errbufptr,
833 							    bufspaceleft,
834 							    ", ");
835 						}
836 					}
837 					msglen = strlen(errbuf);
838 					errbufptr = errbuf + msglen;
839 					bufspaceleft = errbuflen - msglen;
840 				}
841 			}
842 			free(addrs_to_try);
843 			return INVALID_SOCKET;
844 		}
845 		else
846 		{
847 			free(addrs_to_try);
848 			return sock;
849 		}
850 	}
851 }
852 
853 /*
854  * \brief Closes the present (TCP and UDP) socket connection.
855  *
856  * This function sends a shutdown() on the socket in order to disable send() calls
857  * (while recv() ones are still allowed). Then, it closes the socket.
858  *
859  * \param sock: the socket identifier of the connection that has to be closed.
860  *
861  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
862  * error message. This buffer has to be at least 'errbuflen' in length.
863  * It can be NULL; in this case the error cannot be printed.
864  *
865  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
866  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
867  *
868  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
869  * in the 'errbuf' variable.
870  */
871 int sock_close(PCAP_SOCKET sock, char *errbuf, int errbuflen)
872 {
873 	/*
874 	 * SHUT_WR: subsequent calls to the send function are disallowed.
875 	 * For TCP sockets, a FIN will be sent after all data is sent and
876 	 * acknowledged by the Server.
877 	 */
878 	if (shutdown(sock, SHUT_WR))
879 	{
880 		sock_geterrmsg(errbuf, errbuflen, "shutdown() failed");
881 		/* close the socket anyway */
882 		closesocket(sock);
883 		return -1;
884 	}
885 
886 	closesocket(sock);
887 	return 0;
888 }
889 
890 /*
891  * gai_strerror() has some problems:
892  *
893  * 1) on Windows, Microsoft explicitly says it's not thread-safe;
894  * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
895  *    thread-safe, so an implementation might use a static buffer
896  *    for unknown error codes;
897  * 3) the error message for the most likely error, EAI_NONAME, is
898  *    truly horrible on several platforms ("nodename nor servname
899  *    provided, or not known"?  It's typically going to be "not
900  *    known", not "oopsie, I passed null pointers for the host name
901  *    and service name", not to mention they forgot the "neither");
902  *
903  * so we roll our own.
904  */
905 static void
906 get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
907     const char *hostname, const char *portname)
908 {
909 	char hostport[PCAP_ERRBUF_SIZE];
910 
911 	if (hostname != NULL && portname != NULL)
912 		snprintf(hostport, PCAP_ERRBUF_SIZE, "host and port %s:%s",
913 		    hostname, portname);
914 	else if (hostname != NULL)
915 		snprintf(hostport, PCAP_ERRBUF_SIZE, "host %s",
916 		    hostname);
917 	else if (portname != NULL)
918 		snprintf(hostport, PCAP_ERRBUF_SIZE, "port %s",
919 		    portname);
920 	else
921 		snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
922 	switch (err)
923 	{
924 #ifdef EAI_ADDRFAMILY
925 		case EAI_ADDRFAMILY:
926 			snprintf(errbuf, errbuflen,
927 			    "%sAddress family for %s not supported",
928 			    prefix, hostport);
929 			break;
930 #endif
931 
932 		case EAI_AGAIN:
933 			snprintf(errbuf, errbuflen,
934 			    "%s%s could not be resolved at this time",
935 			    prefix, hostport);
936 			break;
937 
938 		case EAI_BADFLAGS:
939 			snprintf(errbuf, errbuflen,
940 			    "%sThe ai_flags parameter for looking up %s had an invalid value",
941 			    prefix, hostport);
942 			break;
943 
944 		case EAI_FAIL:
945 			snprintf(errbuf, errbuflen,
946 			    "%sA non-recoverable error occurred when attempting to resolve %s",
947 			    prefix, hostport);
948 			break;
949 
950 		case EAI_FAMILY:
951 			snprintf(errbuf, errbuflen,
952 			    "%sThe address family for looking up %s was not recognized",
953 			    prefix, hostport);
954 			break;
955 
956 		case EAI_MEMORY:
957 			snprintf(errbuf, errbuflen,
958 			    "%sOut of memory trying to allocate storage when looking up %s",
959 			    prefix, hostport);
960 			break;
961 
962 		/*
963 		 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
964 		 *
965 		 * RFC 3493 has only EAI_NONAME.
966 		 *
967 		 * Some implementations define EAI_NODATA and EAI_NONAME
968 		 * to the same value, others don't.  If EAI_NODATA is
969 		 * defined and isn't the same as EAI_NONAME, we handle
970 		 * EAI_NODATA.
971 		 */
972 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
973 		case EAI_NODATA:
974 			snprintf(errbuf, errbuflen,
975 			    "%sNo address associated with %s",
976 			    prefix, hostport);
977 			break;
978 #endif
979 
980 		case EAI_NONAME:
981 			snprintf(errbuf, errbuflen,
982 			    "%sThe %s couldn't be resolved",
983 			    prefix, hostport);
984 			break;
985 
986 		case EAI_SERVICE:
987 			snprintf(errbuf, errbuflen,
988 			    "%sThe service value specified when looking up %s as not recognized for the socket type",
989 			    prefix, hostport);
990 			break;
991 
992 		case EAI_SOCKTYPE:
993 			snprintf(errbuf, errbuflen,
994 			    "%sThe socket type specified when looking up %s as not recognized",
995 			    prefix, hostport);
996 			break;
997 
998 #ifdef EAI_SYSTEM
999 		case EAI_SYSTEM:
1000 			/*
1001 			 * Assumed to be UN*X.
1002 			 */
1003 			pcapint_fmt_errmsg_for_errno(errbuf, errbuflen, errno,
1004 			    "%sAn error occurred when looking up %s",
1005 			    prefix, hostport);
1006 			break;
1007 #endif
1008 
1009 #ifdef EAI_BADHINTS
1010 		case EAI_BADHINTS:
1011 			snprintf(errbuf, errbuflen,
1012 			    "%sInvalid value for hints when looking up %s",
1013 			    prefix, hostport);
1014 			break;
1015 #endif
1016 
1017 #ifdef EAI_PROTOCOL
1018 		case EAI_PROTOCOL:
1019 			snprintf(errbuf, errbuflen,
1020 			    "%sResolved protocol when looking up %s is unknown",
1021 			    prefix, hostport);
1022 			break;
1023 #endif
1024 
1025 #ifdef EAI_OVERFLOW
1026 		case EAI_OVERFLOW:
1027 			snprintf(errbuf, errbuflen,
1028 			    "%sArgument buffer overflow when looking up %s",
1029 			    prefix, hostport);
1030 			break;
1031 #endif
1032 
1033 		default:
1034 			snprintf(errbuf, errbuflen,
1035 			    "%sgetaddrinfo() error %d when looking up %s",
1036 			    prefix, err, hostport);
1037 			break;
1038 	}
1039 }
1040 
1041 /*
1042  * \brief Checks that the address, port and flags given are valid and it returns an 'addrinfo' structure.
1043  *
1044  * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
1045  * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
1046  * If an error occurs, it writes the error message into 'errbuf'.
1047  *
1048  * \param host: a pointer to a string identifying the host. It can be
1049  * a host name, a numeric literal address, or NULL or "" (useful
1050  * in case of a server socket which has to bind to all addresses).
1051  *
1052  * \param port: a pointer to a user-allocated buffer containing the network port to use.
1053  *
1054  * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
1055  * addrinfo structure appropriately.
1056  *
1057  * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
1058  * (passed by reference), which will be allocated by this function and returned back to the caller.
1059  * This variable will be used in the next sockets calls.
1060  *
1061  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1062  * error message. This buffer has to be at least 'errbuflen' in length.
1063  * It can be NULL; in this case the error cannot be printed.
1064  *
1065  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1066  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1067  *
1068  * \return a pointer to the first element in a list of addrinfo structures
1069  * if everything is fine, NULL if some errors occurred. The error message
1070  * is returned in the 'errbuf' variable.
1071  *
1072  * \warning The list of addrinfo structures returned has to be deleted by
1073  * the programmer by calling freeaddrinfo() when it is no longer needed.
1074  *
1075  * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
1076  * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
1077  * the programmer to look at that function in order to set the 'hints' variable appropriately.
1078  */
1079 struct addrinfo *sock_initaddress(const char *host, const char *port,
1080     struct addrinfo *hints, char *errbuf, int errbuflen)
1081 {
1082 	struct addrinfo *addrinfo;
1083 	int retval;
1084 
1085 	/*
1086 	 * We allow both the host and port to be null, but getaddrinfo()
1087 	 * is not guaranteed to do so; to handle that, if port is null,
1088 	 * we provide "0" as the port number.
1089 	 *
1090 	 * This results in better error messages from get_gai_errstring(),
1091 	 * as those messages won't talk about a problem with the port if
1092 	 * no port was specified.
1093 	 */
1094 	retval = getaddrinfo(host, port == NULL ? "0" : port, hints, &addrinfo);
1095 	if (retval != 0)
1096 	{
1097 		/*
1098 		 * That call failed.
1099 		 * Determine whether the problem is that the host is bad.
1100 		 */
1101 		if (errbuf)
1102 		{
1103 			if (host != NULL && port != NULL) {
1104 				/*
1105 				 * Try with just a host, to distinguish
1106 				 * between "host is bad" and "port is
1107 				 * bad".
1108 				 */
1109 				int try_retval;
1110 
1111 				try_retval = getaddrinfo(host, NULL, hints,
1112 				    &addrinfo);
1113 				if (try_retval == 0) {
1114 					/*
1115 					 * Worked with just the host,
1116 					 * so assume the problem is
1117 					 * with the port.
1118 					 *
1119 					 * Free up the address info first.
1120 					 */
1121 					freeaddrinfo(addrinfo);
1122 					get_gai_errstring(errbuf, errbuflen,
1123 					    "", retval, NULL, port);
1124 				} else {
1125 					/*
1126 					 * Didn't work with just the host,
1127 					 * so assume the problem is
1128 					 * with the host; we assume
1129 					 * the original error indicates
1130 					 * the underlying problem.
1131 					 */
1132 					get_gai_errstring(errbuf, errbuflen,
1133 					    "", retval, host, NULL);
1134 				}
1135 			} else {
1136 				/*
1137 				 * Either the host or port was null, so
1138 				 * there's nothing to determine; report
1139 				 * the error from the original call.
1140 				 */
1141 				get_gai_errstring(errbuf, errbuflen, "",
1142 				    retval, host, port);
1143 			}
1144 		}
1145 		return NULL;
1146 	}
1147 	/*
1148 	 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
1149 	 * addrinfo has more han one pointers
1150 	 */
1151 
1152 	/*
1153 	 * This software only supports PF_INET and PF_INET6.
1154 	 *
1155 	 * XXX - should we just check that at least *one* address is
1156 	 * either PF_INET or PF_INET6, and, when using the list,
1157 	 * ignore all addresses that are neither?  (What, no IPX
1158 	 * support? :-))
1159 	 */
1160 	if ((addrinfo->ai_family != PF_INET) &&
1161 	    (addrinfo->ai_family != PF_INET6))
1162 	{
1163 		if (errbuf)
1164 			snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
1165 		freeaddrinfo(addrinfo);
1166 		return NULL;
1167 	}
1168 
1169 	/*
1170 	 * You can't do multicast (or broadcast) TCP.
1171 	 */
1172 	if ((addrinfo->ai_socktype == SOCK_STREAM) &&
1173 	    (sock_ismcastaddr(addrinfo->ai_addr) == 0))
1174 	{
1175 		if (errbuf)
1176 			snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
1177 		freeaddrinfo(addrinfo);
1178 		return NULL;
1179 	}
1180 
1181 	return addrinfo;
1182 }
1183 
1184 /*
1185  * \brief It sends the amount of data contained into 'buffer' on the given socket.
1186  *
1187  * This function basically calls the send() socket function and it checks that all
1188  * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
1189  * it writes the error message into 'errbuf'.
1190  * In case the socket buffer does not have enough space, it loops until all data
1191  * has been sent.
1192  *
1193  * \param socket: the connected socket currently opened.
1194  *
1195  * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
1196  *
1197  * \param size: number of bytes that have to be sent.
1198  *
1199  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1200  * error message. This buffer has to be at least 'errbuflen' in length.
1201  * It can be NULL; in this case the error cannot be printed.
1202  *
1203  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1204  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1205  *
1206  * \return '0' if everything is fine, '-1' if an error other than
1207  * "connection reset" or "peer has closed the receive side" occurred,
1208  * '-2' if we got one of those errors.
1209  * For errors, an error message is returned in the 'errbuf' variable.
1210  */
1211 int sock_send(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, const char *buffer,
1212     size_t size, char *errbuf, int errbuflen)
1213 {
1214 	int remaining;
1215 	ssize_t nsent;
1216 
1217 	if (size > INT_MAX)
1218 	{
1219 		if (errbuf)
1220 		{
1221 			snprintf(errbuf, errbuflen,
1222 			    "Can't send more than %u bytes with sock_send",
1223 			    INT_MAX);
1224 		}
1225 		return -1;
1226 	}
1227 	remaining = (int)size;
1228 
1229 	do {
1230 #ifdef HAVE_OPENSSL
1231 		if (ssl) return ssl_send(ssl, buffer, remaining, errbuf, errbuflen);
1232 #endif
1233 
1234 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1235 		nsent = remaining;
1236 #else
1237 #ifdef MSG_NOSIGNAL
1238 		/*
1239 		 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
1240 		 * on errors on stream-oriented sockets when the other
1241 		 * end breaks the connection.
1242 		 * The EPIPE error is still returned.
1243 		 */
1244 		nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
1245 #else
1246 		nsent = send(sock, buffer, remaining, 0);
1247 #endif
1248 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1249 
1250 		if (nsent == -1)
1251 		{
1252 			/*
1253 			 * If the client closed the connection out from
1254 			 * under us, there's no need to log that as an
1255 			 * error.
1256 			 */
1257 			int errcode;
1258 
1259 #ifdef _WIN32
1260 			errcode = GetLastError();
1261 			if (errcode == WSAECONNRESET ||
1262 			    errcode == WSAECONNABORTED)
1263 			{
1264 				/*
1265 				 * WSAECONNABORTED appears to be the error
1266 				 * returned in Winsock when you try to send
1267 				 * on a connection where the peer has closed
1268 				 * the receive side.
1269 				 */
1270 				return -2;
1271 			}
1272 			sock_fmterrmsg(errbuf, errbuflen, errcode,
1273 			    "send() failed");
1274 #else
1275 			errcode = errno;
1276 			if (errcode == ECONNRESET || errcode == EPIPE)
1277 			{
1278 				/*
1279 				 * EPIPE is what's returned on UN*X when
1280 				 * you try to send on a connection when
1281 				 * the peer has closed the receive side.
1282 				 */
1283 				return -2;
1284 			}
1285 			sock_fmterrmsg(errbuf, errbuflen, errcode,
1286 			    "send() failed");
1287 #endif
1288 			return -1;
1289 		}
1290 
1291 		remaining -= nsent;
1292 		buffer += nsent;
1293 	} while (remaining != 0);
1294 
1295 	return 0;
1296 }
1297 
1298 /*
1299  * \brief It copies the amount of data contained in 'data' into 'outbuf'.
1300  * and it checks for buffer overflows.
1301  *
1302  * This function basically copies 'size' bytes of data contained in 'data'
1303  * into 'outbuf', starting at offset 'offset'. Before that, it checks that the
1304  * resulting buffer will not be larger	than 'totsize'. Finally, it updates
1305  * the 'offset' variable in order to point to the first empty location of the buffer.
1306  *
1307  * In case the function is called with 'checkonly' equal to 1, it does not copy
1308  * the data into the buffer. It only checks for buffer overflows and it updates the
1309  * 'offset' variable. This mode can be useful when the buffer already contains the
1310  * data (maybe because the producer writes directly into the target buffer), so
1311  * only the buffer overflow check has to be made.
1312  * In this case, both 'data' and 'outbuf' can be NULL values.
1313  *
1314  * This function is useful in case the userland application does not know immediately
1315  * all the data it has to write into the socket. This function provides a way to create
1316  * the "stream" step by step, appending the new data to the old one. Then, when all the
1317  * data has been bufferized, the application can call the sock_send() function.
1318  *
1319  * \param data: a void pointer to the data that has to be copied.
1320  *
1321  * \param size: number of bytes that have to be copied.
1322  *
1323  * \param outbuf: user-allocated buffer (of size 'totsize') into which data
1324  * has to be copied.
1325  *
1326  * \param offset: an index into 'outbuf' which keeps the location of its first
1327  * empty location.
1328  *
1329  * \param totsize: total size of the buffer into which data is being copied.
1330  *
1331  * \param checkonly: '1' if we do not want to copy data into the buffer and we
1332  * want just do a buffer overflow control, '0' if data has to be copied as well.
1333  *
1334  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1335  * error message. This buffer has to be at least 'errbuflen' in length.
1336  * It can be NULL; in this case the error cannot be printed.
1337  *
1338  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1339  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1340  *
1341  * \return '0' if everything is fine, '-1' if some errors occurred. The error message
1342  * is returned in the 'errbuf' variable. When the function returns, 'outbuf' will
1343  * have the new string appended, and 'offset' will keep the length of that buffer.
1344  * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
1345  *
1346  * \warning This function assumes that the buffer in which data has to be stored is
1347  * large 'totbuf' bytes.
1348  *
1349  * \warning In case of 'checkonly', be carefully to call this function *before* copying
1350  * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
1351  */
1352 int sock_bufferize(const void *data, int size, char *outbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
1353 {
1354 	if ((*offset + size) > totsize)
1355 	{
1356 		if (errbuf)
1357 			snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
1358 		return -1;
1359 	}
1360 
1361 	if (!checkonly)
1362 		memcpy(outbuf + (*offset), data, size);
1363 
1364 	(*offset) += size;
1365 
1366 	return 0;
1367 }
1368 
1369 /*
1370  * \brief It waits on a connected socket and it manages to receive data.
1371  *
1372  * This function basically calls the recv() socket function and it checks that no
1373  * error occurred. If that happens, it writes the error message into 'errbuf'.
1374  *
1375  * This function changes its behavior according to the 'receiveall' flag: if we
1376  * want to receive exactly 'size' byte, it loops on the recv()	until all the requested
1377  * data is arrived. Otherwise, it returns the data currently available.
1378  *
1379  * In case the socket does not have enough data available, it cycles on the recv()
1380  * until the requested data (of size 'size') is arrived.
1381  * In this case, it blocks until the number of bytes read is equal to 'size'.
1382  *
1383  * \param sock: the connected socket currently opened.
1384  *
1385  * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
1386  *
1387  * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
1388  * that we are expecting to be read.
1389  *
1390  * \param flags:
1391  *
1392  *   SOCK_RECEIVALL_XXX:
1393  *
1394  *	if SOCK_RECEIVEALL_NO, return as soon as some data is ready
1395  *	if SOCK_RECEIVALL_YES, wait until 'size' data has been
1396  *	    received (in case the socket does not have enough data available).
1397  *
1398  *   SOCK_EOF_XXX:
1399  *
1400  *	if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
1401  *	    and return an error on any subsequent read that returns 0;
1402  *	if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
1403  *
1404  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1405  * error message. This buffer has to be at least 'errbuflen' in length.
1406  * It can be NULL; in this case the error cannot be printed.
1407  *
1408  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1409  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1410  *
1411  * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
1412  * The error message is returned in the 'errbuf' variable.
1413  */
1414 
1415 int sock_recv(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
1416     int flags, char *errbuf, int errbuflen)
1417 {
1418 	int recv_flags = 0;
1419 	char *bufp = buffer;
1420 	int remaining;
1421 	ssize_t nread;
1422 
1423 	if (size == 0)
1424 	{
1425 		return 0;
1426 	}
1427 	if (size > INT_MAX)
1428 	{
1429 		if (errbuf)
1430 		{
1431 			snprintf(errbuf, errbuflen,
1432 			    "Can't read more than %u bytes with sock_recv",
1433 			    INT_MAX);
1434 		}
1435 		return -1;
1436 	}
1437 
1438 	if (flags & SOCK_MSG_PEEK)
1439 		recv_flags |= MSG_PEEK;
1440 
1441 	bufp = (char *) buffer;
1442 	remaining = (int) size;
1443 
1444 	/*
1445 	 * We don't use MSG_WAITALL because it's not supported in
1446 	 * Win32.
1447 	 */
1448 	for (;;) {
1449 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1450 		nread = fuzz_recv(bufp, remaining);
1451 #elif defined(HAVE_OPENSSL)
1452 		if (ssl)
1453 		{
1454 			/*
1455 			 * XXX - what about MSG_PEEK?
1456 			 */
1457 			nread = ssl_recv(ssl, bufp, remaining, errbuf, errbuflen);
1458 			if (nread == -2) return -1;
1459 		}
1460 		else
1461 			nread = recv(sock, bufp, remaining, recv_flags);
1462 #else
1463 		nread = recv(sock, bufp, remaining, recv_flags);
1464 #endif
1465 
1466 		if (nread == -1)
1467 		{
1468 #ifndef _WIN32
1469 			if (errno == EINTR)
1470 				return -3;
1471 #endif
1472 			sock_geterrmsg(errbuf, errbuflen, "recv() failed");
1473 			return -1;
1474 		}
1475 
1476 		if (nread == 0)
1477 		{
1478 			if ((flags & SOCK_EOF_IS_ERROR) ||
1479 			    (remaining != (int) size))
1480 			{
1481 				/*
1482 				 * Either we've already read some data,
1483 				 * or we're always supposed to return
1484 				 * an error on EOF.
1485 				 */
1486 				if (errbuf)
1487 				{
1488 					snprintf(errbuf, errbuflen,
1489 					    "The other host terminated the connection.");
1490 				}
1491 				return -1;
1492 			}
1493 			else
1494 				return 0;
1495 		}
1496 
1497 		/*
1498 		 * Do we want to read the amount requested, or just return
1499 		 * what we got?
1500 		 */
1501 		if (!(flags & SOCK_RECEIVEALL_YES))
1502 		{
1503 			/*
1504 			 * Just return what we got.
1505 			 */
1506 			return (int) nread;
1507 		}
1508 
1509 		bufp += nread;
1510 		remaining -= nread;
1511 
1512 		if (remaining == 0)
1513 			return (int) size;
1514 	}
1515 }
1516 
1517 /*
1518  * Receives a datagram from a socket.
1519  *
1520  * Returns the size of the datagram on success or -1 on error.
1521  */
1522 int sock_recv_dgram(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer,
1523     size_t size, char *errbuf, int errbuflen)
1524 {
1525 	ssize_t nread;
1526 #ifndef _WIN32
1527 	struct msghdr message;
1528 	struct iovec iov;
1529 #endif
1530 
1531 	if (size == 0)
1532 	{
1533 		return 0;
1534 	}
1535 	if (size > INT_MAX)
1536 	{
1537 		if (errbuf)
1538 		{
1539 			snprintf(errbuf, errbuflen,
1540 			    "Can't read more than %u bytes with sock_recv_dgram",
1541 			    INT_MAX);
1542 		}
1543 		return -1;
1544 	}
1545 
1546 #ifdef HAVE_OPENSSL
1547 	// TODO: DTLS
1548 	if (ssl)
1549 	{
1550 		snprintf(errbuf, errbuflen, "DTLS not implemented yet");
1551 		return -1;
1552 	}
1553 #endif
1554 
1555 	/*
1556 	 * This should be a datagram socket, so we should get the
1557 	 * entire datagram in one recv() or recvmsg() call, and
1558 	 * don't need to loop.
1559 	 */
1560 #ifdef _WIN32
1561 	nread = recv(sock, buffer, (int)size, 0);
1562 	if (nread == SOCKET_ERROR)
1563 	{
1564 		/*
1565 		 * To quote the MSDN documentation for recv(),
1566 		 * "If the datagram or message is larger than
1567 		 * the buffer specified, the buffer is filled
1568 		 * with the first part of the datagram, and recv
1569 		 * generates the error WSAEMSGSIZE. For unreliable
1570 		 * protocols (for example, UDP) the excess data is
1571 		 * lost..."
1572 		 *
1573 		 * So if the message is bigger than the buffer
1574 		 * supplied to us, the excess data is discarded,
1575 		 * and we'll report an error.
1576 		 */
1577 		sock_fmterrmsg(errbuf, errbuflen, sock_geterrcode(),
1578 		    "recv() failed");
1579 		return -1;
1580 	}
1581 #else /* _WIN32 */
1582 	/*
1583 	 * The Single UNIX Specification says that a recv() on
1584 	 * a socket for a message-oriented protocol will discard
1585 	 * the excess data.  It does *not* indicate that the
1586 	 * receive will fail with, for example, EMSGSIZE.
1587 	 *
1588 	 * Therefore, we use recvmsg(), which appears to be
1589 	 * the only way to get a "message truncated" indication
1590 	 * when receiving a message for a message-oriented
1591 	 * protocol.
1592 	 */
1593 	message.msg_name = NULL;	/* we don't care who it's from */
1594 	message.msg_namelen = 0;
1595 	iov.iov_base = buffer;
1596 	iov.iov_len = size;
1597 	message.msg_iov = &iov;
1598 	message.msg_iovlen = 1;
1599 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1600 	message.msg_control = NULL;	/* we don't care about control information */
1601 	message.msg_controllen = 0;
1602 #endif
1603 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1604 	message.msg_flags = 0;
1605 #endif
1606 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1607 	nread = fuzz_recv(buffer, size);
1608 #else
1609 	nread = recvmsg(sock, &message, 0);
1610 #endif
1611 	if (nread == -1)
1612 	{
1613 		if (errno == EINTR)
1614 			return -3;
1615 		sock_geterrmsg(errbuf, errbuflen, "recv() failed");
1616 		return -1;
1617 	}
1618 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1619 	/*
1620 	 * XXX - Solaris supports this, but only if you ask for the
1621 	 * X/Open version of recvmsg(); should we use that, or will
1622 	 * that cause other problems?
1623 	 */
1624 	if (message.msg_flags & MSG_TRUNC)
1625 	{
1626 		/*
1627 		 * Message was bigger than the specified buffer size.
1628 		 *
1629 		 * Report this as an error, as the Microsoft documentation
1630 		 * implies we'd do in a similar case on Windows.
1631 		 */
1632 		snprintf(errbuf, errbuflen, "recv(): Message too long");
1633 		return -1;
1634 	}
1635 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1636 #endif /* _WIN32 */
1637 
1638 	/*
1639 	 * The size we're reading fits in an int, so the return value
1640 	 * will fit in an int.
1641 	 */
1642 	return (int)nread;
1643 }
1644 
1645 /*
1646  * \brief It discards N bytes that are currently waiting to be read on the current socket.
1647  *
1648  * This function is useful in case we receive a message we cannot understand (e.g.
1649  * wrong version number when receiving a network packet), so that we have to discard all
1650  * data before reading a new message.
1651  *
1652  * This function will read 'size' bytes from the socket and discard them.
1653  * It defines an internal buffer in which data will be copied; however, in case
1654  * this buffer is not large enough, it will cycle in order to read everything as well.
1655  *
1656  * \param sock: the connected socket currently opened.
1657  *
1658  * \param size: number of bytes that have to be discarded.
1659  *
1660  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1661  * error message. This buffer has to be at least 'errbuflen' in length.
1662  * It can be NULL; in this case the error cannot be printed.
1663  *
1664  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1665  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1666  *
1667  * \return '0' if everything is fine, '-1' if some errors occurred.
1668  * The error message is returned in the 'errbuf' variable.
1669  */
1670 int sock_discard(PCAP_SOCKET sock, SSL *ssl, int size, char *errbuf,
1671     int errbuflen)
1672 {
1673 #define TEMP_BUF_SIZE 32768
1674 
1675 	char buffer[TEMP_BUF_SIZE];		/* network buffer, to be used when the message is discarded */
1676 
1677 	/*
1678 	 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1679 	 * Our feeling is that a buffer if 32KB is enough for most of the application;
1680 	 * in case this is not enough, the "while" loop discards the message by calling the
1681 	 * sockrecv() several times.
1682 	 * We do not want to create a bigger variable because this causes the program to exit on
1683 	 * some platforms (e.g. BSD)
1684 	 */
1685 	while (size > TEMP_BUF_SIZE)
1686 	{
1687 		if (sock_recv(sock, ssl, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1688 			return -1;
1689 
1690 		size -= TEMP_BUF_SIZE;
1691 	}
1692 
1693 	/*
1694 	 * If there is still data to be discarded
1695 	 * In this case, the data can fit into the temporary buffer
1696 	 */
1697 	if (size)
1698 	{
1699 		if (sock_recv(sock, ssl, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1700 			return -1;
1701 	}
1702 
1703 	return 0;
1704 }
1705 
1706 /*
1707  * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1708  *
1709  * This function is useful after an accept() call in order to check if the connecting
1710  * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1711  * allowed host; this function checks the sockaddr_storage structure of the connecting host
1712  * against this host list, and it returns '0' is the host is included in this list.
1713  *
1714  * \param hostlist: pointer to a string that contains the list of the allowed host.
1715  *
1716  * \param sep: a string that keeps the separators used between the hosts (for example the
1717  * space character) in the host list.
1718  *
1719  * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1720  *
1721  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1722  * error message. This buffer has to be at least 'errbuflen' in length.
1723  * It can be NULL; in this case the error cannot be printed.
1724  *
1725  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1726  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1727  *
1728  * \return It returns:
1729  * - '1' if the host list is empty
1730  * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1731  * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1732  * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1733  */
1734 int sock_check_hostlist(const char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
1735 {
1736 	/* checks if the connecting host is among the ones allowed */
1737 	if ((hostlist) && (hostlist[0]))
1738 	{
1739 		char *token;					/* temp, needed to separate items into the hostlist */
1740 		struct addrinfo *addrinfo, *ai_next;
1741 		char *temphostlist;
1742 		char *lasts;
1743 		int getaddrinfo_failed = 0;
1744 
1745 		/*
1746 		 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1747 		 * So, we have to create a new temporary string in which the original content is kept
1748 		 */
1749 		temphostlist = strdup(hostlist);
1750 		if (temphostlist == NULL)
1751 		{
1752 			sock_geterrmsg(errbuf, errbuflen,
1753 			    "sock_check_hostlist(), malloc() failed");
1754 			return -2;
1755 		}
1756 
1757 		token = pcapint_strtok_r(temphostlist, sep, &lasts);
1758 
1759 		/* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1760 		addrinfo = NULL;
1761 
1762 		while (token != NULL)
1763 		{
1764 			struct addrinfo hints;
1765 			int retval;
1766 
1767 			addrinfo = NULL;
1768 			memset(&hints, 0, sizeof(struct addrinfo));
1769 			hints.ai_family = PF_UNSPEC;
1770 			hints.ai_socktype = SOCK_STREAM;
1771 
1772 			retval = getaddrinfo(token, NULL, &hints, &addrinfo);
1773 			if (retval != 0)
1774 			{
1775 				if (errbuf)
1776 					get_gai_errstring(errbuf, errbuflen,
1777 					    "Allowed host list error: ",
1778 					    retval, token, NULL);
1779 
1780 				/*
1781 				 * Note that at least one call to getaddrinfo()
1782 				 * failed.
1783 				 */
1784 				getaddrinfo_failed = 1;
1785 
1786 				/* Get next token */
1787 				token = pcapint_strtok_r(NULL, sep, &lasts);
1788 				continue;
1789 			}
1790 
1791 			/* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1792 			ai_next = addrinfo;
1793 			while (ai_next)
1794 			{
1795 				if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1796 				{
1797 					free(temphostlist);
1798 					freeaddrinfo(addrinfo);
1799 					return 0;
1800 				}
1801 
1802 				/*
1803 				 * If we are here, it means that the current address does not matches
1804 				 * Let's try with the next one in the header chain
1805 				 */
1806 				ai_next = ai_next->ai_next;
1807 			}
1808 
1809 			freeaddrinfo(addrinfo);
1810 			addrinfo = NULL;
1811 
1812 			/* Get next token */
1813 			token = pcapint_strtok_r(NULL, sep, &lasts);
1814 		}
1815 
1816 		if (addrinfo)
1817 		{
1818 			freeaddrinfo(addrinfo);
1819 			addrinfo = NULL;
1820 		}
1821 
1822 		free(temphostlist);
1823 
1824 		if (getaddrinfo_failed) {
1825 			/*
1826 			 * At least one getaddrinfo() call failed;
1827 			 * treat that as an error, so rpcapd knows
1828 			 * that it should log it locally as well
1829 			 * as telling the client about it.
1830 			 */
1831 			return -2;
1832 		} else {
1833 			/*
1834 			 * All getaddrinfo() calls succeeded, but
1835 			 * the host wasn't in the list.
1836 			 */
1837 			if (errbuf)
1838 				snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1839 			return -1;
1840 		}
1841 	}
1842 
1843 	/* No hostlist, so we have to return 'empty list' */
1844 	return 1;
1845 }
1846 
1847 /*
1848  * \brief Compares two addresses contained into two sockaddr_storage structures.
1849  *
1850  * This function is useful to compare two addresses, given their internal representation,
1851  * i.e. an sockaddr_storage structure.
1852  *
1853  * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1854  * sockaddr_in6, properly casted in order to be compliant to the function interface.
1855  *
1856  * This function will return '0' if the two addresses matches, '-1' if not.
1857  *
1858  * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1859  * accept() call), containing the first address to compare.
1860  *
1861  * \param second: a sockaddr_storage structure containing the second address to compare.
1862  *
1863  * \return '0' if the addresses are equal, '-1' if they are different.
1864  */
1865 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
1866 {
1867 	if (first->ss_family == second->ss_family)
1868 	{
1869 		if (first->ss_family == AF_INET)
1870 		{
1871 			if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
1872 				&(((struct sockaddr_in *) second)->sin_addr),
1873 				sizeof(struct in_addr)) == 0)
1874 				return 0;
1875 		}
1876 		else /* address family is AF_INET6 */
1877 		{
1878 			if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
1879 				&(((struct sockaddr_in6 *) second)->sin6_addr),
1880 				sizeof(struct in6_addr)) == 0)
1881 				return 0;
1882 		}
1883 	}
1884 
1885 	return -1;
1886 }
1887 
1888 /*
1889  * \brief It gets the address/port the system picked for this socket (on connected sockets).
1890  *
1891  * It is used to return the address and port the server picked for our socket on the local machine.
1892  * It works only on:
1893  * - connected sockets
1894  * - server sockets
1895  *
1896  * On unconnected client sockets it does not work because the system dynamically chooses a port
1897  * only when the socket calls a send() call.
1898  *
1899  * \param sock: the connected socket currently opened.
1900  *
1901  * \param address: it contains the address that will be returned by the function. This buffer
1902  * must be properly allocated by the user. The address can be either literal or numeric depending
1903  * on the value of 'Flags'.
1904  *
1905  * \param addrlen: the length of the 'address' buffer.
1906  *
1907  * \param port: it contains the port that will be returned by the function. This buffer
1908  * must be properly allocated by the user.
1909  *
1910  * \param portlen: the length of the 'port' buffer.
1911  *
1912  * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1913  * that determine if the resulting address must be in numeric / literal form, and so on.
1914  *
1915  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1916  * error message. This buffer has to be at least 'errbuflen' in length.
1917  * It can be NULL; in this case the error cannot be printed.
1918  *
1919  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1920  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1921  *
1922  * \return It returns '-1' if this function succeeds, '0' otherwise.
1923  * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1924  * In any case, the returned strings are '0' terminated.
1925  *
1926  * \warning If the socket is using a connectionless protocol, the address may not be available
1927  * until I/O occurs on the socket.
1928  */
1929 int sock_getmyinfo(PCAP_SOCKET sock, char *address, int addrlen, char *port,
1930     int portlen, int flags, char *errbuf, int errbuflen)
1931 {
1932 	struct sockaddr_storage mysockaddr;
1933 	socklen_t sockaddrlen;
1934 
1935 
1936 	sockaddrlen = sizeof(struct sockaddr_storage);
1937 
1938 	if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1939 	{
1940 		sock_geterrmsg(errbuf, errbuflen, "getsockname() failed");
1941 		return 0;
1942 	}
1943 
1944 	/* Returns the numeric address of the host that triggered the error */
1945 	return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1946 }
1947 
1948 /*
1949  * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1950  *
1951  * This function is basically an extended version of the inet_ntop(), which does not exist in
1952  * Winsock because the same result can be obtained by using the getnameinfo().
1953  * However, differently from inet_ntop(), this function is able to return also literal names
1954  * (e.g. 'localhost') dependently from the 'Flags' parameter.
1955  *
1956  * The function accepts a sockaddr_storage variable (which can be returned by several functions
1957  * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1958  * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1959  * a standard IPv6 address like "::1".
1960  *
1961  * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1962  * are the ones allowed in the standard getnameinfo() socket function.
1963  *
1964  * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1965  * need to be translated from network form into the presentation form. This structure must be
1966  * zero-ed prior using it, and the address family field must be filled with the proper value.
1967  * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1968  * calling this function.
1969  *
1970  * \param address: it contains the address that will be returned by the function. This buffer
1971  * must be properly allocated by the user. The address can be either literal or numeric depending
1972  * on the value of 'Flags'.
1973  *
1974  * \param addrlen: the length of the 'address' buffer.
1975  *
1976  * \param port: it contains the port that will be returned by the function. This buffer
1977  * must be properly allocated by the user.
1978  *
1979  * \param portlen: the length of the 'port' buffer.
1980  *
1981  * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1982  * that determine if the resulting address must be in numeric / literal form, and so on.
1983  *
1984  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1985  * error message. This buffer has to be at least 'errbuflen' in length.
1986  * It can be NULL; in this case the error cannot be printed.
1987  *
1988  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1989  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1990  *
1991  * \return It returns '-1' if this function succeeds, '0' otherwise.
1992  * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1993  * and 'port'.
1994  * In any case, the returned strings are '0' terminated.
1995  */
1996 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, size_t errbuflen)
1997 {
1998 	socklen_t sockaddrlen;
1999 	int retval;					/* Variable that keeps the return value; */
2000 
2001 	retval = -1;
2002 
2003 #ifdef _WIN32
2004 	if (sockaddr->ss_family == AF_INET)
2005 		sockaddrlen = sizeof(struct sockaddr_in);
2006 	else
2007 		sockaddrlen = sizeof(struct sockaddr_in6);
2008 #else
2009 	sockaddrlen = sizeof(struct sockaddr_storage);
2010 #endif
2011 
2012 	if ((flags & NI_NUMERICHOST) == 0)	/* Check that we want literal names */
2013 	{
2014 		if ((sockaddr->ss_family == AF_INET6) &&
2015 			(memcmp(&((struct sockaddr_in6 *) sockaddr)->sin6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(struct in6_addr)) == 0))
2016 		{
2017 			if (address)
2018 				pcapint_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
2019 			return retval;
2020 		}
2021 	}
2022 
2023 	if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
2024 	{
2025 		/* If the user wants to receive an error message */
2026 		if (errbuf)
2027 		{
2028 			sock_geterrmsg(errbuf, errbuflen,
2029 			    "getnameinfo() failed");
2030 			errbuf[errbuflen - 1] = 0;
2031 		}
2032 
2033 		if (address)
2034 		{
2035 			pcapint_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
2036 			address[addrlen - 1] = 0;
2037 		}
2038 
2039 		if (port)
2040 		{
2041 			pcapint_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
2042 			port[portlen - 1] = 0;
2043 		}
2044 
2045 		retval = 0;
2046 	}
2047 
2048 	return retval;
2049 }
2050 
2051 /*
2052  * \brief It translates an address from the 'presentation' form into the 'network' form.
2053  *
2054  * This function basically replaces inet_pton(), which does not exist in Winsock because
2055  * the same result can be obtained by using the getaddrinfo().
2056  * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
2057  * like in inet_pton() ) and a literal name (e.g. 'localhost').
2058  *
2059  * This function does the reverse job of sock_getascii_addrport().
2060  *
2061  * \param address: a zero-terminated string which contains the name you have to
2062  * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
2063  *
2064  * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
2065  * 'network' form of the requested address.
2066  *
2067  * \param addr_family: a constant which can assume the following values:
2068  * - 'AF_INET' if we want to ping an IPv4 host
2069  * - 'AF_INET6' if we want to ping an IPv6 host
2070  * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
2071  *
2072  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
2073  * error message. This buffer has to be at least 'errbuflen' in length.
2074  * It can be NULL; in this case the error cannot be printed.
2075  *
2076  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
2077  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
2078  *
2079  * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
2080  * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
2081  * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
2082  * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
2083  * the content of the SockAddr parameter will be the address corresponding to the first mapping.
2084  *
2085  * \warning The sockaddr_storage structure MUST be allocated by the user.
2086  */
2087 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
2088 {
2089 	struct addrinfo *addrinfo;
2090 	struct addrinfo hints;
2091 
2092 	memset(&hints, 0, sizeof(hints));
2093 
2094 	hints.ai_family = addr_family;
2095 
2096 	addrinfo = sock_initaddress(address, "22222" /* fake port */, &hints,
2097 	    errbuf, errbuflen);
2098 	if (addrinfo == NULL)
2099 		return 0;
2100 
2101 	if (addrinfo->ai_family == PF_INET)
2102 		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
2103 	else
2104 		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
2105 
2106 	if (addrinfo->ai_next != NULL)
2107 	{
2108 		freeaddrinfo(addrinfo);
2109 
2110 		if (errbuf)
2111 			snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
2112 		return -2;
2113 	}
2114 
2115 	freeaddrinfo(addrinfo);
2116 	return -1;
2117 }
2118