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