• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  *   Wth 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 
146 /*
147  * Format an error message given an errno value (UN*X) or a Winsock error
148  * (Windows).
149  */
sock_fmterror(const char * caller,int errcode,char * errbuf,int errbuflen)150 void sock_fmterror(const char *caller, int errcode, char *errbuf, int errbuflen)
151 {
152 	if (errbuf == NULL)
153 		return;
154 
155 #ifdef _WIN32
156 	pcap_fmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
157 	    "%s", caller);
158 #else
159 	pcap_fmt_errmsg_for_errno(errbuf, errbuflen, errcode,
160 	    "%s", caller);
161 #endif
162 }
163 
164 /*
165  * \brief It retrieves the error message after an error occurred in the socket interface.
166  *
167  * This function is defined because of the different way errors are returned in UNIX
168  * and Win32. This function provides a consistent way to retrieve the error message
169  * (after a socket error occurred) on all the platforms.
170  *
171  * \param caller: a pointer to a user-allocated string which contains a message that has
172  * to be printed *before* the true error message. It could be, for example, 'this error
173  * comes from the recv() call at line 31'.
174  *
175  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
176  * error message. This buffer has to be at least 'errbuflen' in length.
177  * It can be NULL; in this case the error cannot be printed.
178  *
179  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
180  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
181  *
182  * \return No return values. The error message is returned in the 'string' parameter.
183  */
sock_geterror(const char * caller,char * errbuf,int errbuflen)184 void sock_geterror(const char *caller, char *errbuf, int errbuflen)
185 {
186 #ifdef _WIN32
187 	sock_fmterror(caller, GetLastError(), errbuf, errbuflen);
188 #else
189 	sock_fmterror(caller, errno, errbuf, errbuflen);
190 #endif
191 }
192 
193 /*
194  * \brief This function initializes the socket mechanism if it hasn't
195  * already been initialized or reinitializes it after it has been
196  * cleaned up.
197  *
198  * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
199  * initialize Winsock.
200  *
201  * \param errbuf: a pointer to an user-allocated buffer that will contain
202  * the complete error message. This buffer has to be at least 'errbuflen'
203  * in length. It can be NULL; in this case no error message is supplied.
204  *
205  * \param errbuflen: length of the buffer that will contains the error.
206  * The error message cannot be larger than 'errbuflen - 1' because the
207  * last char is reserved for the string terminator.
208  *
209  * \return '0' if everything is fine, '-1' if some errors occurred. The
210  * error message is returned in the buffer pointed to by 'errbuf' variable.
211  */
212 #ifdef _WIN32
sock_init(char * errbuf,int errbuflen)213 int sock_init(char *errbuf, int errbuflen)
214 {
215 	if (sockcount == 0)
216 	{
217 		WSADATA wsaData;			/* helper variable needed to initialize Winsock */
218 
219 		if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
220 		    WINSOCK_MINOR_VERSION), &wsaData) != 0)
221 		{
222 			if (errbuf)
223 				snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
224 
225 			WSACleanup();
226 
227 			return -1;
228 		}
229 	}
230 
231 	sockcount++;
232 	return 0;
233 }
234 #else
sock_init(char * errbuf _U_,int errbuflen _U_)235 int sock_init(char *errbuf _U_, int errbuflen _U_)
236 {
237 	/*
238 	 * Nothing to do on UN*Xes.
239 	 */
240 	return 0;
241 }
242 #endif
243 
244 /*
245  * \brief This function cleans up the socket mechanism if we have no
246  * sockets left open.
247  *
248  * On UN*Xes, it doesn't need to do anything; on Windows, it needs
249  * to clean up Winsock.
250  *
251  * \return No error values.
252  */
sock_cleanup(void)253 void sock_cleanup(void)
254 {
255 #ifdef _WIN32
256 	sockcount--;
257 
258 	if (sockcount == 0)
259 		WSACleanup();
260 #endif
261 }
262 
263 /*
264  * \brief It checks if the sockaddr variable contains a multicast address.
265  *
266  * \return '0' if the address is multicast, '-1' if it is not.
267  */
sock_ismcastaddr(const struct sockaddr * saddr)268 static int sock_ismcastaddr(const struct sockaddr *saddr)
269 {
270 	if (saddr->sa_family == PF_INET)
271 	{
272 		struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
273 		if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
274 		else return -1;
275 	}
276 	else
277 	{
278 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
279 		if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
280 		else return -1;
281 	}
282 }
283 
284 /*
285  * \brief It initializes a network connection both from the client and the server side.
286  *
287  * In case of a client socket, this function calls socket() and connect().
288  * In the meanwhile, it checks for any socket error.
289  * If an error occurs, it writes the error message into 'errbuf'.
290  *
291  * In case of a server socket, the function calls socket(), bind() and listen().
292  *
293  * This function is usually preceded by the sock_initaddress().
294  *
295  * \param addrinfo: pointer to an addrinfo variable which will be used to
296  * open the socket and such. This variable is the one returned by the previous call to
297  * sock_initaddress().
298  *
299  * \param server: '1' if this is a server socket, '0' otherwise.
300  *
301  * \param nconn: number of the connections that are allowed to wait into the listen() call.
302  * This value has no meanings in case of a client socket.
303  *
304  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
305  * error message. This buffer has to be at least 'errbuflen' in length.
306  * It can be NULL; in this case the error cannot be printed.
307  *
308  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
309  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
310  *
311  * \return the socket that has been opened (that has to be used in the following sockets calls)
312  * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
313  * in the 'errbuf' variable.
314  */
sock_open(struct addrinfo * addrinfo,int server,int nconn,char * errbuf,int errbuflen)315 SOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
316 {
317 	SOCKET sock;
318 #if defined(SO_NOSIGPIPE) || defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
319 	int on = 1;
320 #endif
321 
322 	sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
323 	if (sock == INVALID_SOCKET)
324 	{
325 		sock_geterror("socket()", errbuf, errbuflen);
326 		return INVALID_SOCKET;
327 	}
328 
329 	/*
330 	 * Disable SIGPIPE, if we have SO_NOSIGPIPE.  We don't want to
331 	 * have to deal with signals if the peer closes the connection,
332 	 * especially in client programs, which may not even be aware that
333 	 * they're sending to sockets.
334 	 */
335 #ifdef SO_NOSIGPIPE
336 	if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
337 	    sizeof (int)) == -1)
338 	{
339 		sock_geterror("setsockopt(SO_NOSIGPIPE)", errbuf, errbuflen);
340 		closesocket(sock);
341 		return INVALID_SOCKET;
342 	}
343 #endif
344 
345 	/* This is a server socket */
346 	if (server)
347 	{
348 		/*
349 		 * Allow a new server to bind the socket after the old one
350 		 * exited, even if lingering sockets are still present.
351 		 *
352 		 * Don't treat an error as a failure.
353 		 */
354 		int optval = 1;
355 		(void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
356 		    (char *)&optval, sizeof (optval));
357 
358 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
359 		/*
360 		 * Force the use of IPv6-only addresses.
361 		 *
362 		 * RFC 3493 indicates that you can support IPv4 on an
363 		 * IPv6 socket:
364 		 *
365 		 *    https://tools.ietf.org/html/rfc3493#section-3.7
366 		 *
367 		 * and that this is the default behavior.  This means
368 		 * that if we first create an IPv6 socket bound to the
369 		 * "any" address, it is, in effect, also bound to the
370 		 * IPv4 "any" address, so when we create an IPv4 socket
371 		 * and try to bind it to the IPv4 "any" address, it gets
372 		 * EADDRINUSE.
373 		 *
374 		 * Not all network stacks support IPv4 on IPv6 sockets;
375 		 * pre-NT 6 Windows stacks don't support it, and the
376 		 * OpenBSD stack doesn't support it for security reasons
377 		 * (see the OpenBSD inet6(4) man page).  Therefore, we
378 		 * don't want to rely on this behavior.
379 		 *
380 		 * So we try to disable it, using either the IPV6_V6ONLY
381 		 * option from RFC 3493:
382 		 *
383 		 *    https://tools.ietf.org/html/rfc3493#section-5.3
384 		 *
385 		 * or the IPV6_BINDV6ONLY option from older UN*Xes.
386 		 */
387 #ifndef IPV6_V6ONLY
388   /* For older systems */
389   #define IPV6_V6ONLY IPV6_BINDV6ONLY
390 #endif /* IPV6_V6ONLY */
391 		if (addrinfo->ai_family == PF_INET6)
392 		{
393 			if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
394 			    (char *)&on, sizeof (int)) == -1)
395 			{
396 				if (errbuf)
397 					snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
398 				closesocket(sock);
399 				return INVALID_SOCKET;
400 			}
401 		}
402 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
403 
404 		/* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
405 		if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
406 		{
407 			sock_geterror("bind()", errbuf, errbuflen);
408 			closesocket(sock);
409 			return INVALID_SOCKET;
410 		}
411 
412 		if (addrinfo->ai_socktype == SOCK_STREAM)
413 			if (listen(sock, nconn) == -1)
414 			{
415 				sock_geterror("listen()", errbuf, errbuflen);
416 				closesocket(sock);
417 				return INVALID_SOCKET;
418 			}
419 
420 		/* server side ended */
421 		return sock;
422 	}
423 	else	/* we're the client */
424 	{
425 		struct addrinfo *tempaddrinfo;
426 		char *errbufptr;
427 		size_t bufspaceleft;
428 
429 		tempaddrinfo = addrinfo;
430 		errbufptr = errbuf;
431 		bufspaceleft = errbuflen;
432 		*errbufptr = 0;
433 
434 		/*
435 		 * We have to loop though all the addinfo returned.
436 		 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
437 		 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
438 		 */
439 		while (tempaddrinfo)
440 		{
441 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
442 			break;
443 #endif
444 			if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
445 			{
446 				size_t msglen;
447 				char TmpBuffer[100];
448 				char SocketErrorMessage[SOCK_ERRBUF_SIZE];
449 
450 				/*
451 				 * We have to retrieve the error message before any other socket call completes, otherwise
452 				 * the error message is lost
453 				 */
454 				sock_geterror("Connect to socket failed",
455 				    SocketErrorMessage, sizeof(SocketErrorMessage));
456 
457 				/* Returns the numeric address of the host that triggered the error */
458 				sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
459 
460 				snprintf(errbufptr, bufspaceleft,
461 				    "Is the server properly installed on %s?  %s", TmpBuffer, SocketErrorMessage);
462 
463 				/* In case more then one 'connect' fails, we manage to keep all the error messages */
464 				msglen = strlen(errbufptr);
465 
466 				errbufptr[msglen] = ' ';
467 				errbufptr[msglen + 1] = 0;
468 
469 				bufspaceleft = bufspaceleft - (msglen + 1);
470 				errbufptr += (msglen + 1);
471 
472 				tempaddrinfo = tempaddrinfo->ai_next;
473 			}
474 			else
475 				break;
476 		}
477 
478 		/*
479 		 * Check how we exit from the previous loop
480 		 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
481 		 */
482 		if (tempaddrinfo == NULL)
483 		{
484 			closesocket(sock);
485 			return INVALID_SOCKET;
486 		}
487 		else
488 			return sock;
489 	}
490 }
491 
492 /*
493  * \brief Closes the present (TCP and UDP) socket connection.
494  *
495  * This function sends a shutdown() on the socket in order to disable send() calls
496  * (while recv() ones are still allowed). Then, it closes the socket.
497  *
498  * \param sock: the socket identifier of the connection that has to be closed.
499  *
500  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
501  * error message. This buffer has to be at least 'errbuflen' in length.
502  * It can be NULL; in this case the error cannot be printed.
503  *
504  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
505  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
506  *
507  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
508  * in the 'errbuf' variable.
509  */
sock_close(SOCKET sock,char * errbuf,int errbuflen)510 int sock_close(SOCKET sock, char *errbuf, int errbuflen)
511 {
512 	/*
513 	 * SHUT_WR: subsequent calls to the send function are disallowed.
514 	 * For TCP sockets, a FIN will be sent after all data is sent and
515 	 * acknowledged by the Server.
516 	 */
517 	if (shutdown(sock, SHUT_WR))
518 	{
519 		sock_geterror("shutdown()", errbuf, errbuflen);
520 		/* close the socket anyway */
521 		closesocket(sock);
522 		return -1;
523 	}
524 
525 	closesocket(sock);
526 	return 0;
527 }
528 
529 /*
530  * gai_errstring() has some problems:
531  *
532  * 1) on Windows, Microsoft explicitly says it's not thread-safe;
533  * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
534  *    thread-safe, so an implementation might use a static buffer
535  *    for unknown error codes;
536  * 3) the error message for the most likely error, EAI_NONAME, is
537  *    truly horrible on several platforms ("nodename nor servname
538  *    provided, or not known"?  It's typically going to be "not
539  *    known", not "oopsie, I passed null pointers for the host name
540  *    and service name", not to mention they forgot the "neither");
541  *
542  * so we roll our own.
543  */
544 static void
get_gai_errstring(char * errbuf,int errbuflen,const char * prefix,int err,const char * hostname,const char * portname)545 get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
546     const char *hostname, const char *portname)
547 {
548 	char hostport[PCAP_ERRBUF_SIZE];
549 
550 	if (hostname != NULL && portname != NULL)
551 		snprintf(hostport, PCAP_ERRBUF_SIZE, "%s:%s",
552 		    hostname, portname);
553 	else if (hostname != NULL)
554 		snprintf(hostport, PCAP_ERRBUF_SIZE, "%s",
555 		    hostname);
556 	else if (portname != NULL)
557 		snprintf(hostport, PCAP_ERRBUF_SIZE, ":%s",
558 		    portname);
559 	else
560 		snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
561 	switch (err)
562 	{
563 #ifdef EAI_ADDRFAMILY
564 		case EAI_ADDRFAMILY:
565 			snprintf(errbuf, errbuflen,
566 			    "%sAddress family for %s not supported",
567 			    prefix, hostport);
568 			break;
569 #endif
570 
571 		case EAI_AGAIN:
572 			snprintf(errbuf, errbuflen,
573 			    "%s%s could not be resolved at this time",
574 			    prefix, hostport);
575 			break;
576 
577 		case EAI_BADFLAGS:
578 			snprintf(errbuf, errbuflen,
579 			    "%sThe ai_flags parameter for looking up %s had an invalid value",
580 			    prefix, hostport);
581 			break;
582 
583 		case EAI_FAIL:
584 			snprintf(errbuf, errbuflen,
585 			    "%sA non-recoverable error occurred when attempting to resolve %s",
586 			    prefix, hostport);
587 			break;
588 
589 		case EAI_FAMILY:
590 			snprintf(errbuf, errbuflen,
591 			    "%sThe address family for looking up %s was not recognized",
592 			    prefix, hostport);
593 			break;
594 
595 		case EAI_MEMORY:
596 			snprintf(errbuf, errbuflen,
597 			    "%sOut of memory trying to allocate storage when looking up %s",
598 			    prefix, hostport);
599 			break;
600 
601 		/*
602 		 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
603 		 *
604 		 * RFC 3493 has only EAI_NONAME.
605 		 *
606 		 * Some implementations define EAI_NODATA and EAI_NONAME
607 		 * to the same value, others don't.  If EAI_NODATA is
608 		 * defined and isn't the same as EAI_NONAME, we handle
609 		 * EAI_NODATA.
610 		 */
611 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
612 		case EAI_NODATA:
613 			snprintf(errbuf, errbuflen,
614 			    "%sNo address associated with %s",
615 			    prefix, hostport);
616 			break;
617 #endif
618 
619 		case EAI_NONAME:
620 			snprintf(errbuf, errbuflen,
621 			    "%sThe host name %s couldn't be resolved",
622 			    prefix, hostport);
623 			break;
624 
625 		case EAI_SERVICE:
626 			snprintf(errbuf, errbuflen,
627 			    "%sThe service value specified when looking up %s as not recognized for the socket type",
628 			    prefix, hostport);
629 			break;
630 
631 		case EAI_SOCKTYPE:
632 			snprintf(errbuf, errbuflen,
633 			    "%sThe socket type specified when looking up %s as not recognized",
634 			    prefix, hostport);
635 			break;
636 
637 #ifdef EAI_SYSTEM
638 		case EAI_SYSTEM:
639 			/*
640 			 * Assumed to be UN*X.
641 			 */
642 			pcap_fmt_errmsg_for_errno(errbuf, errbuflen, errno,
643 			    "%sAn error occurred when looking up %s",
644 			    prefix, hostport);
645 			break;
646 #endif
647 
648 #ifdef EAI_BADHINTS
649 		case EAI_BADHINTS:
650 			snprintf(errbuf, errbuflen,
651 			    "%sInvalid value for hints when looking up %s",
652 			    prefix, hostport);
653 			break;
654 #endif
655 
656 #ifdef EAI_PROTOCOL
657 		case EAI_PROTOCOL:
658 			snprintf(errbuf, errbuflen,
659 			    "%sResolved protocol when looking up %s is unknown",
660 			    prefix, hostport);
661 			break;
662 #endif
663 
664 #ifdef EAI_OVERFLOW
665 		case EAI_OVERFLOW:
666 			snprintf(errbuf, errbuflen,
667 			    "%sArgument buffer overflow when looking up %s",
668 			    prefix, hostport);
669 			break;
670 #endif
671 
672 		default:
673 			snprintf(errbuf, errbuflen,
674 			    "%sgetaddrinfo() error %d when looking up %s",
675 			    prefix, err, hostport);
676 			break;
677 	}
678 }
679 
680 /*
681  * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
682  *
683  * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
684  * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
685  * If an error occurs, it writes the error message into 'errbuf'.
686  *
687  * \param host: a pointer to a string identifying the host. It can be
688  * a host name, a numeric literal address, or NULL or "" (useful
689  * in case of a server socket which has to bind to all addresses).
690  *
691  * \param port: a pointer to a user-allocated buffer containing the network port to use.
692  *
693  * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
694  * addrinfo structure appropriately.
695  *
696  * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
697  * (passed by reference), which will be allocated by this function and returned back to the caller.
698  * This variable will be used in the next sockets calls.
699  *
700  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
701  * error message. This buffer has to be at least 'errbuflen' in length.
702  * It can be NULL; in this case the error cannot be printed.
703  *
704  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
705  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
706  *
707  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
708  * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
709  * returned into the addrinfo parameter.
710  *
711  * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
712  * it is no longer needed.
713  *
714  * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
715  * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
716  * the programmer to look at that function in order to set the 'hints' variable appropriately.
717  */
sock_initaddress(const char * host,const char * port,struct addrinfo * hints,struct addrinfo ** addrinfo,char * errbuf,int errbuflen)718 int sock_initaddress(const char *host, const char *port,
719     struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
720 {
721 	int retval;
722 
723 	retval = getaddrinfo(host, port, hints, addrinfo);
724 	if (retval != 0)
725 	{
726 		if (errbuf)
727 		{
728 			get_gai_errstring(errbuf, errbuflen, "", retval,
729 			    host, port);
730 		}
731 		return -1;
732 	}
733 	/*
734 	 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
735 	 * addrinfo has more han one pointers
736 	 */
737 
738 	/*
739 	 * This software only supports PF_INET and PF_INET6.
740 	 *
741 	 * XXX - should we just check that at least *one* address is
742 	 * either PF_INET or PF_INET6, and, when using the list,
743 	 * ignore all addresses that are neither?  (What, no IPX
744 	 * support? :-))
745 	 */
746 	if (((*addrinfo)->ai_family != PF_INET) &&
747 	    ((*addrinfo)->ai_family != PF_INET6))
748 	{
749 		if (errbuf)
750 			snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
751 		freeaddrinfo(*addrinfo);
752 		*addrinfo = NULL;
753 		return -1;
754 	}
755 
756 	/*
757 	 * You can't do multicast (or broadcast) TCP.
758 	 */
759 	if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
760 	    (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
761 	{
762 		if (errbuf)
763 			snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
764 		freeaddrinfo(*addrinfo);
765 		*addrinfo = NULL;
766 		return -1;
767 	}
768 
769 	return 0;
770 }
771 
772 /*
773  * \brief It sends the amount of data contained into 'buffer' on the given socket.
774  *
775  * This function basically calls the send() socket function and it checks that all
776  * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
777  * it writes the error message into 'errbuf'.
778  * In case the socket buffer does not have enough space, it loops until all data
779  * has been sent.
780  *
781  * \param socket: the connected socket currently opened.
782  *
783  * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
784  *
785  * \param size: number of bytes that have to be sent.
786  *
787  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
788  * error message. This buffer has to be at least 'errbuflen' in length.
789  * It can be NULL; in this case the error cannot be printed.
790  *
791  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
792  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
793  *
794  * \return '0' if everything is fine, '-1' if an error other than
795  * "connection reset" or "peer has closed the receive side" occurred,
796  * '-2' if we got one of those errors.
797  * For errors, an error message is returned in the 'errbuf' variable.
798  */
sock_send(SOCKET sock,SSL * ssl _U_NOSSL_,const char * buffer,size_t size,char * errbuf,int errbuflen)799 int sock_send(SOCKET sock, SSL *ssl _U_NOSSL_, const char *buffer, size_t size,
800     char *errbuf, int errbuflen)
801 {
802 	int remaining;
803 	ssize_t nsent;
804 
805 	if (size > INT_MAX)
806 	{
807 		if (errbuf)
808 		{
809 			snprintf(errbuf, errbuflen,
810 			    "Can't send more than %u bytes with sock_send",
811 			    INT_MAX);
812 		}
813 		return -1;
814 	}
815 	remaining = (int)size;
816 
817 	do {
818 #ifdef HAVE_OPENSSL
819 		if (ssl) return ssl_send(ssl, buffer, remaining, errbuf, errbuflen);
820 #endif
821 
822 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
823 		nsent = remaining;
824 #else
825 #ifdef MSG_NOSIGNAL
826 		/*
827 		 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
828 		 * on errors on stream-oriented sockets when the other
829 		 * end breaks the connection.
830 		 * The EPIPE error is still returned.
831 		 */
832 		nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
833 #else
834 		nsent = send(sock, buffer, remaining, 0);
835 #endif
836 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
837 
838 		if (nsent == -1)
839 		{
840 			/*
841 			 * If the client closed the connection out from
842 			 * under us, there's no need to log that as an
843 			 * error.
844 			 */
845 			int errcode;
846 
847 #ifdef _WIN32
848 			errcode = GetLastError();
849 			if (errcode == WSAECONNRESET ||
850 			    errcode == WSAECONNABORTED)
851 			{
852 				/*
853 				 * WSAECONNABORTED appears to be the error
854 				 * returned in Winsock when you try to send
855 				 * on a connection where the peer has closed
856 				 * the receive side.
857 				 */
858 				return -2;
859 			}
860 			sock_fmterror("send()", errcode, errbuf, errbuflen);
861 #else
862 			errcode = errno;
863 			if (errcode == ECONNRESET || errcode == EPIPE)
864 			{
865 				/*
866 				 * EPIPE is what's returned on UN*X when
867 				 * you try to send on a connection when
868 				 * the peer has closed the receive side.
869 				 */
870 				return -2;
871 			}
872 			sock_fmterror("send()", errcode, errbuf, errbuflen);
873 #endif
874 			return -1;
875 		}
876 
877 		remaining -= nsent;
878 		buffer += nsent;
879 	} while (remaining != 0);
880 
881 	return 0;
882 }
883 
884 /*
885  * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
886  * and it checks for buffer overflows.
887  *
888  * This function basically copies 'size' bytes of data contained into 'buffer'
889  * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
890  * resulting buffer will not be larger	than 'totsize'. Finally, it updates
891  * the 'offset' variable in order to point to the first empty location of the buffer.
892  *
893  * In case the function is called with 'checkonly' equal to 1, it does not copy
894  * the data into the buffer. It only checks for buffer overflows and it updates the
895  * 'offset' variable. This mode can be useful when the buffer already contains the
896  * data (maybe because the producer writes directly into the target buffer), so
897  * only the buffer overflow check has to be made.
898  * In this case, both 'buffer' and 'tempbuf' can be NULL values.
899  *
900  * This function is useful in case the userland application does not know immediately
901  * all the data it has to write into the socket. This function provides a way to create
902  * the "stream" step by step, appending the new data to the old one. Then, when all the
903  * data has been bufferized, the application can call the sock_send() function.
904  *
905  * \param buffer: a char pointer to a user-allocated buffer that keeps the data
906  * that has to be copied.
907  *
908  * \param size: number of bytes that have to be copied.
909  *
910  * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
911  * has to be copied.
912  *
913  * \param offset: an index into 'tempbuf' which keeps the location of its first
914  * empty location.
915  *
916  * \param totsize: total size of the buffer in which data is being copied.
917  *
918  * \param checkonly: '1' if we do not want to copy data into the buffer and we
919  * want just do a buffer ovreflow control, '0' if data has to be copied as well.
920  *
921  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
922  * error message. This buffer has to be at least 'errbuflen' in length.
923  * It can be NULL; in this case the error cannot be printed.
924  *
925  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
926  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
927  *
928  * \return '0' if everything is fine, '-1' if some errors occurred. The error message
929  * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
930  * have the new string appended, and 'offset' will keep the length of that buffer.
931  * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
932  *
933  * \warning This function assumes that the buffer in which data has to be stored is
934  * large 'totbuf' bytes.
935  *
936  * \warning In case of 'checkonly', be carefully to call this function *before* copying
937  * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
938  */
sock_bufferize(const char * buffer,int size,char * tempbuf,int * offset,int totsize,int checkonly,char * errbuf,int errbuflen)939 int sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
940 {
941 	if ((*offset + size) > totsize)
942 	{
943 		if (errbuf)
944 			snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
945 		return -1;
946 	}
947 
948 	if (!checkonly)
949 		memcpy(tempbuf + (*offset), buffer, size);
950 
951 	(*offset) += size;
952 
953 	return 0;
954 }
955 
956 /*
957  * \brief It waits on a connected socket and it manages to receive data.
958  *
959  * This function basically calls the recv() socket function and it checks that no
960  * error occurred. If that happens, it writes the error message into 'errbuf'.
961  *
962  * This function changes its behavior according to the 'receiveall' flag: if we
963  * want to receive exactly 'size' byte, it loops on the recv()	until all the requested
964  * data is arrived. Otherwise, it returns the data currently available.
965  *
966  * In case the socket does not have enough data available, it cycles on the recv()
967  * until the requested data (of size 'size') is arrived.
968  * In this case, it blocks until the number of bytes read is equal to 'size'.
969  *
970  * \param sock: the connected socket currently opened.
971  *
972  * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
973  *
974  * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
975  * that we are expecting to be read.
976  *
977  * \param flags:
978  *
979  *   SOCK_RECEIVALL_XXX:
980  *
981  * 	if SOCK_RECEIVEALL_NO, return as soon as some data is ready
982  *	if SOCK_RECEIVALL_YES, wait until 'size' data has been
983  *	    received (in case the socket does not have enough data available).
984  *
985  *   SOCK_EOF_XXX:
986  *
987  *	if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
988  *	    and return an error on any subsequent read that returns 0;
989  *	if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
990  *
991  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
992  * error message. This buffer has to be at least 'errbuflen' in length.
993  * It can be NULL; in this case the error cannot be printed.
994  *
995  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
996  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
997  *
998  * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
999  * The error message is returned in the 'errbuf' variable.
1000  */
1001 
sock_recv(SOCKET sock,SSL * ssl _U_NOSSL_,void * buffer,size_t size,int flags,char * errbuf,int errbuflen)1002 int sock_recv(SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
1003     int flags, char *errbuf, int errbuflen)
1004 {
1005 	int recv_flags = 0;
1006 	char *bufp = buffer;
1007 	int remaining;
1008 	ssize_t nread;
1009 
1010 	if (size == 0)
1011 	{
1012 		return 0;
1013 	}
1014 	if (size > INT_MAX)
1015 	{
1016 		if (errbuf)
1017 		{
1018 			snprintf(errbuf, errbuflen,
1019 			    "Can't read more than %u bytes with sock_recv",
1020 			    INT_MAX);
1021 		}
1022 		return -1;
1023 	}
1024 
1025 	if (flags & SOCK_MSG_PEEK)
1026 		recv_flags |= MSG_PEEK;
1027 
1028 	bufp = (char *) buffer;
1029 	remaining = (int) size;
1030 
1031 	/*
1032 	 * We don't use MSG_WAITALL because it's not supported in
1033 	 * Win32.
1034 	 */
1035 	for (;;) {
1036 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1037 		nread = fuzz_recv(bufp, remaining);
1038 #elif defined(HAVE_OPENSSL)
1039 		if (ssl)
1040 		{
1041 			/*
1042 			 * XXX - what about MSG_PEEK?
1043 			 */
1044 			nread = ssl_recv(ssl, bufp, remaining, errbuf, errbuflen);
1045 			if (nread == -2) return -1;
1046 		}
1047 		else
1048 			nread = recv(sock, bufp, remaining, recv_flags);
1049 #else
1050 		nread = recv(sock, bufp, remaining, recv_flags);
1051 #endif
1052 
1053 		if (nread == -1)
1054 		{
1055 #ifndef _WIN32
1056 			if (errno == EINTR)
1057 				return -3;
1058 #endif
1059 			sock_geterror("recv()", errbuf, errbuflen);
1060 			return -1;
1061 		}
1062 
1063 		if (nread == 0)
1064 		{
1065 			if ((flags & SOCK_EOF_IS_ERROR) ||
1066 			    (remaining != (int) size))
1067 			{
1068 				/*
1069 				 * Either we've already read some data,
1070 				 * or we're always supposed to return
1071 				 * an error on EOF.
1072 				 */
1073 				if (errbuf)
1074 				{
1075 					snprintf(errbuf, errbuflen,
1076 					    "The other host terminated the connection.");
1077 				}
1078 				return -1;
1079 			}
1080 			else
1081 				return 0;
1082 		}
1083 
1084 		/*
1085 		 * Do we want to read the amount requested, or just return
1086 		 * what we got?
1087 		 */
1088 		if (!(flags & SOCK_RECEIVEALL_YES))
1089 		{
1090 			/*
1091 			 * Just return what we got.
1092 			 */
1093 			return (int) nread;
1094 		}
1095 
1096 		bufp += nread;
1097 		remaining -= nread;
1098 
1099 		if (remaining == 0)
1100 			return (int) size;
1101 	}
1102 }
1103 
1104 /*
1105  * Receives a datagram from a socket.
1106  *
1107  * Returns the size of the datagram on success or -1 on error.
1108  */
sock_recv_dgram(SOCKET sock,SSL * ssl _U_NOSSL_,void * buffer,size_t size,char * errbuf,int errbuflen)1109 int sock_recv_dgram(SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
1110     char *errbuf, int errbuflen)
1111 {
1112 	ssize_t nread;
1113 #ifndef _WIN32
1114 	struct msghdr message;
1115 	struct iovec iov;
1116 #endif
1117 
1118 	if (size == 0)
1119 	{
1120 		return 0;
1121 	}
1122 	if (size > INT_MAX)
1123 	{
1124 		if (errbuf)
1125 		{
1126 			snprintf(errbuf, errbuflen,
1127 			    "Can't read more than %u bytes with sock_recv_dgram",
1128 			    INT_MAX);
1129 		}
1130 		return -1;
1131 	}
1132 
1133 #ifdef HAVE_OPENSSL
1134 	// TODO: DTLS
1135 	if (ssl)
1136 	{
1137 		snprintf(errbuf, errbuflen, "DTLS not implemented yet");
1138 		return -1;
1139 	}
1140 #endif
1141 
1142 	/*
1143 	 * This should be a datagram socket, so we should get the
1144 	 * entire datagram in one recv() or recvmsg() call, and
1145 	 * don't need to loop.
1146 	 */
1147 #ifdef _WIN32
1148 	nread = recv(sock, buffer, (int)size, 0);
1149 	if (nread == SOCKET_ERROR)
1150 	{
1151 		/*
1152 		 * To quote the MSDN documentation for recv(),
1153 		 * "If the datagram or message is larger than
1154 		 * the buffer specified, the buffer is filled
1155 		 * with the first part of the datagram, and recv
1156 		 * generates the error WSAEMSGSIZE. For unreliable
1157 		 * protocols (for example, UDP) the excess data is
1158 		 * lost..."
1159 		 *
1160 		 * So if the message is bigger than the buffer
1161 		 * supplied to us, the excess data is discarded,
1162 		 * and we'll report an error.
1163 		 */
1164 		sock_geterror("recv()", errbuf, errbuflen);
1165 		return -1;
1166 	}
1167 #else /* _WIN32 */
1168 	/*
1169 	 * The Single UNIX Specification says that a recv() on
1170 	 * a socket for a message-oriented protocol will discard
1171 	 * the excess data.  It does *not* indicate that the
1172 	 * receive will fail with, for example, EMSGSIZE.
1173 	 *
1174 	 * Therefore, we use recvmsg(), which appears to be
1175 	 * the only way to get a "message truncated" indication
1176 	 * when receiving a message for a message-oriented
1177 	 * protocol.
1178 	 */
1179 	message.msg_name = NULL;	/* we don't care who it's from */
1180 	message.msg_namelen = 0;
1181 	iov.iov_base = buffer;
1182 	iov.iov_len = size;
1183 	message.msg_iov = &iov;
1184 	message.msg_iovlen = 1;
1185 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1186 	message.msg_control = NULL;	/* we don't care about control information */
1187 	message.msg_controllen = 0;
1188 #endif
1189 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1190 	message.msg_flags = 0;
1191 #endif
1192 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1193 	nread = fuzz_recv(buffer, size);
1194 #else
1195 	nread = recvmsg(sock, &message, 0);
1196 #endif
1197 	if (nread == -1)
1198 	{
1199 		if (errno == EINTR)
1200 			return -3;
1201 		sock_geterror("recv()", errbuf, errbuflen);
1202 		return -1;
1203 	}
1204 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1205 	/*
1206 	 * XXX - Solaris supports this, but only if you ask for the
1207 	 * X/Open version of recvmsg(); should we use that, or will
1208 	 * that cause other problems?
1209 	 */
1210 	if (message.msg_flags & MSG_TRUNC)
1211 	{
1212 		/*
1213 		 * Message was bigger than the specified buffer size.
1214 		 *
1215 		 * Report this as an error, as the Microsoft documentation
1216 		 * implies we'd do in a similar case on Windows.
1217 		 */
1218 		snprintf(errbuf, errbuflen, "recv(): Message too long");
1219 		return -1;
1220 	}
1221 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1222 #endif /* _WIN32 */
1223 
1224 	/*
1225 	 * The size we're reading fits in an int, so the return value
1226 	 * will fit in an int.
1227 	 */
1228 	return (int)nread;
1229 }
1230 
1231 /*
1232  * \brief It discards N bytes that are currently waiting to be read on the current socket.
1233  *
1234  * This function is useful in case we receive a message we cannot understand (e.g.
1235  * wrong version number when receiving a network packet), so that we have to discard all
1236  * data before reading a new message.
1237  *
1238  * This function will read 'size' bytes from the socket and discard them.
1239  * It defines an internal buffer in which data will be copied; however, in case
1240  * this buffer is not large enough, it will cycle in order to read everything as well.
1241  *
1242  * \param sock: the connected socket currently opened.
1243  *
1244  * \param size: number of bytes that have to be discarded.
1245  *
1246  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1247  * error message. This buffer has to be at least 'errbuflen' in length.
1248  * It can be NULL; in this case the error cannot be printed.
1249  *
1250  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1251  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1252  *
1253  * \return '0' if everything is fine, '-1' if some errors occurred.
1254  * The error message is returned in the 'errbuf' variable.
1255  */
sock_discard(SOCKET sock,SSL * ssl,int size,char * errbuf,int errbuflen)1256 int sock_discard(SOCKET sock, SSL *ssl, int size, char *errbuf, int errbuflen)
1257 {
1258 #define TEMP_BUF_SIZE 32768
1259 
1260 	char buffer[TEMP_BUF_SIZE];		/* network buffer, to be used when the message is discarded */
1261 
1262 	/*
1263 	 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1264 	 * Our feeling is that a buffer if 32KB is enough for most of the application;
1265 	 * in case this is not enough, the "while" loop discards the message by calling the
1266 	 * sockrecv() several times.
1267 	 * We do not want to create a bigger variable because this causes the program to exit on
1268 	 * some platforms (e.g. BSD)
1269 	 */
1270 	while (size > TEMP_BUF_SIZE)
1271 	{
1272 		if (sock_recv(sock, ssl, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1273 			return -1;
1274 
1275 		size -= TEMP_BUF_SIZE;
1276 	}
1277 
1278 	/*
1279 	 * If there is still data to be discarded
1280 	 * In this case, the data can fit into the temporary buffer
1281 	 */
1282 	if (size)
1283 	{
1284 		if (sock_recv(sock, ssl, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1285 			return -1;
1286 	}
1287 
1288 	return 0;
1289 }
1290 
1291 /*
1292  * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1293  *
1294  * This function is useful after an accept() call in order to check if the connecting
1295  * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1296  * allowed host; this function checks the sockaddr_storage structure of the connecting host
1297  * against this host list, and it returns '0' is the host is included in this list.
1298  *
1299  * \param hostlist: pointer to a string that contains the list of the allowed host.
1300  *
1301  * \param sep: a string that keeps the separators used between the hosts (for example the
1302  * space character) in the host list.
1303  *
1304  * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1305  *
1306  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1307  * error message. This buffer has to be at least 'errbuflen' in length.
1308  * It can be NULL; in this case the error cannot be printed.
1309  *
1310  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1311  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1312  *
1313  * \return It returns:
1314  * - '1' if the host list is empty
1315  * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1316  * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1317  * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1318  */
sock_check_hostlist(char * hostlist,const char * sep,struct sockaddr_storage * from,char * errbuf,int errbuflen)1319 int sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
1320 {
1321 	/* checks if the connecting host is among the ones allowed */
1322 	if ((hostlist) && (hostlist[0]))
1323 	{
1324 		char *token;					/* temp, needed to separate items into the hostlist */
1325 		struct addrinfo *addrinfo, *ai_next;
1326 		char *temphostlist;
1327 		char *lasts;
1328 		int getaddrinfo_failed = 0;
1329 
1330 		/*
1331 		 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1332 		 * So, we have to create a new temporary string in which the original content is kept
1333 		 */
1334 		temphostlist = strdup(hostlist);
1335 		if (temphostlist == NULL)
1336 		{
1337 			sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
1338 			return -2;
1339 		}
1340 
1341 		token = pcap_strtok_r(temphostlist, sep, &lasts);
1342 
1343 		/* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1344 		addrinfo = NULL;
1345 
1346 		while (token != NULL)
1347 		{
1348 			struct addrinfo hints;
1349 			int retval;
1350 
1351 			addrinfo = NULL;
1352 			memset(&hints, 0, sizeof(struct addrinfo));
1353 			hints.ai_family = PF_UNSPEC;
1354 			hints.ai_socktype = SOCK_STREAM;
1355 
1356 			retval = getaddrinfo(token, NULL, &hints, &addrinfo);
1357 			if (retval != 0)
1358 			{
1359 				if (errbuf)
1360 					get_gai_errstring(errbuf, errbuflen,
1361 					    "Allowed host list error: ",
1362 					    retval, token, NULL);
1363 
1364 				/*
1365 				 * Note that at least one call to getaddrinfo()
1366 				 * failed.
1367 				 */
1368 				getaddrinfo_failed = 1;
1369 
1370 				/* Get next token */
1371 				token = pcap_strtok_r(NULL, sep, &lasts);
1372 				continue;
1373 			}
1374 
1375 			/* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1376 			ai_next = addrinfo;
1377 			while (ai_next)
1378 			{
1379 				if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1380 				{
1381 					free(temphostlist);
1382 					freeaddrinfo(addrinfo);
1383 					return 0;
1384 				}
1385 
1386 				/*
1387 				 * If we are here, it means that the current address does not matches
1388 				 * Let's try with the next one in the header chain
1389 				 */
1390 				ai_next = ai_next->ai_next;
1391 			}
1392 
1393 			freeaddrinfo(addrinfo);
1394 			addrinfo = NULL;
1395 
1396 			/* Get next token */
1397 			token = pcap_strtok_r(NULL, sep, &lasts);
1398 		}
1399 
1400 		if (addrinfo)
1401 		{
1402 			freeaddrinfo(addrinfo);
1403 			addrinfo = NULL;
1404 		}
1405 
1406 		free(temphostlist);
1407 
1408 		if (getaddrinfo_failed) {
1409 			/*
1410 			 * At least one getaddrinfo() call failed;
1411 			 * treat that as an error, so rpcapd knows
1412 			 * that it should log it locally as well
1413 			 * as telling the client about it.
1414 			 */
1415 			return -2;
1416 		} else {
1417 			/*
1418 			 * All getaddrinfo() calls succeeded, but
1419 			 * the host wasn't in the list.
1420 			 */
1421 			if (errbuf)
1422 				snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1423 			return -1;
1424 		}
1425 	}
1426 
1427 	/* No hostlist, so we have to return 'empty list' */
1428 	return 1;
1429 }
1430 
1431 /*
1432  * \brief Compares two addresses contained into two sockaddr_storage structures.
1433  *
1434  * This function is useful to compare two addresses, given their internal representation,
1435  * i.e. an sockaddr_storage structure.
1436  *
1437  * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1438  * sockaddr_in6, properly acsted in order to be compliant to the function interface.
1439  *
1440  * This function will return '0' if the two addresses matches, '-1' if not.
1441  *
1442  * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1443  * accept() call), containing the first address to compare.
1444  *
1445  * \param second: a sockaddr_storage structure containing the second address to compare.
1446  *
1447  * \return '0' if the addresses are equal, '-1' if they are different.
1448  */
sock_cmpaddr(struct sockaddr_storage * first,struct sockaddr_storage * second)1449 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
1450 {
1451 	if (first->ss_family == second->ss_family)
1452 	{
1453 		if (first->ss_family == AF_INET)
1454 		{
1455 			if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
1456 				&(((struct sockaddr_in *) second)->sin_addr),
1457 				sizeof(struct in_addr)) == 0)
1458 				return 0;
1459 		}
1460 		else /* address family is AF_INET6 */
1461 		{
1462 			if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
1463 				&(((struct sockaddr_in6 *) second)->sin6_addr),
1464 				sizeof(struct in6_addr)) == 0)
1465 				return 0;
1466 		}
1467 	}
1468 
1469 	return -1;
1470 }
1471 
1472 /*
1473  * \brief It gets the address/port the system picked for this socket (on connected sockets).
1474  *
1475  * It is used to return the address and port the server picked for our socket on the local machine.
1476  * It works only on:
1477  * - connected sockets
1478  * - server sockets
1479  *
1480  * On unconnected client sockets it does not work because the system dynamically chooses a port
1481  * only when the socket calls a send() call.
1482  *
1483  * \param sock: the connected socket currently opened.
1484  *
1485  * \param address: it contains the address that will be returned by the function. This buffer
1486  * must be properly allocated by the user. The address can be either literal or numeric depending
1487  * on the value of 'Flags'.
1488  *
1489  * \param addrlen: the length of the 'address' buffer.
1490  *
1491  * \param port: it contains the port that will be returned by the function. This buffer
1492  * must be properly allocated by the user.
1493  *
1494  * \param portlen: the length of the 'port' buffer.
1495  *
1496  * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1497  * that determine if the resulting address must be in numeric / literal form, and so on.
1498  *
1499  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1500  * error message. This buffer has to be at least 'errbuflen' in length.
1501  * It can be NULL; in this case the error cannot be printed.
1502  *
1503  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1504  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1505  *
1506  * \return It returns '-1' if this function succeeds, '0' otherwise.
1507  * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1508  * In any case, the returned strings are '0' terminated.
1509  *
1510  * \warning If the socket is using a connectionless protocol, the address may not be available
1511  * until I/O occurs on the socket.
1512  */
sock_getmyinfo(SOCKET sock,char * address,int addrlen,char * port,int portlen,int flags,char * errbuf,int errbuflen)1513 int sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1514 {
1515 	struct sockaddr_storage mysockaddr;
1516 	socklen_t sockaddrlen;
1517 
1518 
1519 	sockaddrlen = sizeof(struct sockaddr_storage);
1520 
1521 	if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1522 	{
1523 		sock_geterror("getsockname()", errbuf, errbuflen);
1524 		return 0;
1525 	}
1526 
1527 	/* Returns the numeric address of the host that triggered the error */
1528 	return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1529 }
1530 
1531 /*
1532  * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1533  *
1534  * This function is basically an extended version of the inet_ntop(), which does not exist in
1535  * Winsock because the same result can be obtained by using the getnameinfo().
1536  * However, differently from inet_ntop(), this function is able to return also literal names
1537  * (e.g. 'localhost') dependently from the 'Flags' parameter.
1538  *
1539  * The function accepts a sockaddr_storage variable (which can be returned by several functions
1540  * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1541  * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1542  * a standard IPv6 address like "::1".
1543  *
1544  * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1545  * are the ones allowed in the standard getnameinfo() socket function.
1546  *
1547  * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1548  * need to be translated from network form into the presentation form. This structure must be
1549  * zero-ed prior using it, and the address family field must be filled with the proper value.
1550  * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1551  * calling this function.
1552  *
1553  * \param address: it contains the address that will be returned by the function. This buffer
1554  * must be properly allocated by the user. The address can be either literal or numeric depending
1555  * on the value of 'Flags'.
1556  *
1557  * \param addrlen: the length of the 'address' buffer.
1558  *
1559  * \param port: it contains the port that will be returned by the function. This buffer
1560  * must be properly allocated by the user.
1561  *
1562  * \param portlen: the length of the 'port' buffer.
1563  *
1564  * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1565  * that determine if the resulting address must be in numeric / literal form, and so on.
1566  *
1567  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1568  * error message. This buffer has to be at least 'errbuflen' in length.
1569  * It can be NULL; in this case the error cannot be printed.
1570  *
1571  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1572  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1573  *
1574  * \return It returns '-1' if this function succeeds, '0' otherwise.
1575  * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1576  * and 'port'.
1577  * In any case, the returned strings are '0' terminated.
1578  */
sock_getascii_addrport(const struct sockaddr_storage * sockaddr,char * address,int addrlen,char * port,int portlen,int flags,char * errbuf,int errbuflen)1579 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1580 {
1581 	socklen_t sockaddrlen;
1582 	int retval;					/* Variable that keeps the return value; */
1583 
1584 	retval = -1;
1585 
1586 #ifdef _WIN32
1587 	if (sockaddr->ss_family == AF_INET)
1588 		sockaddrlen = sizeof(struct sockaddr_in);
1589 	else
1590 		sockaddrlen = sizeof(struct sockaddr_in6);
1591 #else
1592 	sockaddrlen = sizeof(struct sockaddr_storage);
1593 #endif
1594 
1595 	if ((flags & NI_NUMERICHOST) == 0)	/* Check that we want literal names */
1596 	{
1597 		if ((sockaddr->ss_family == AF_INET6) &&
1598 			(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))
1599 		{
1600 			if (address)
1601 				pcap_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
1602 			return retval;
1603 		}
1604 	}
1605 
1606 	if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
1607 	{
1608 		/* If the user wants to receive an error message */
1609 		if (errbuf)
1610 		{
1611 			sock_geterror("getnameinfo()", errbuf, errbuflen);
1612 			errbuf[errbuflen - 1] = 0;
1613 		}
1614 
1615 		if (address)
1616 		{
1617 			pcap_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
1618 			address[addrlen - 1] = 0;
1619 		}
1620 
1621 		if (port)
1622 		{
1623 			pcap_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
1624 			port[portlen - 1] = 0;
1625 		}
1626 
1627 		retval = 0;
1628 	}
1629 
1630 	return retval;
1631 }
1632 
1633 /*
1634  * \brief It translates an address from the 'presentation' form into the 'network' form.
1635  *
1636  * This function basically replaces inet_pton(), which does not exist in Winsock because
1637  * the same result can be obtained by using the getaddrinfo().
1638  * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
1639  * like in inet_pton() ) and a literal name (e.g. 'localhost').
1640  *
1641  * This function does the reverse job of sock_getascii_addrport().
1642  *
1643  * \param address: a zero-terminated string which contains the name you have to
1644  * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
1645  *
1646  * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
1647  * 'network' form of the requested address.
1648  *
1649  * \param addr_family: a constant which can assume the following values:
1650  * - 'AF_INET' if we want to ping an IPv4 host
1651  * - 'AF_INET6' if we want to ping an IPv6 host
1652  * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
1653  *
1654  * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1655  * error message. This buffer has to be at least 'errbuflen' in length.
1656  * It can be NULL; in this case the error cannot be printed.
1657  *
1658  * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1659  * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1660  *
1661  * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
1662  * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
1663  * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
1664  * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
1665  * the content of the SockAddr parameter will be the address corresponding to the first mapping.
1666  *
1667  * \warning The sockaddr_storage structure MUST be allocated by the user.
1668  */
sock_present2network(const char * address,struct sockaddr_storage * sockaddr,int addr_family,char * errbuf,int errbuflen)1669 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
1670 {
1671 	int retval;
1672 	struct addrinfo *addrinfo;
1673 	struct addrinfo hints;
1674 
1675 	memset(&hints, 0, sizeof(hints));
1676 
1677 	hints.ai_family = addr_family;
1678 
1679 	if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
1680 		return 0;
1681 
1682 	if (addrinfo->ai_family == PF_INET)
1683 		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
1684 	else
1685 		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
1686 
1687 	if (addrinfo->ai_next != NULL)
1688 	{
1689 		freeaddrinfo(addrinfo);
1690 
1691 		if (errbuf)
1692 			snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
1693 		return -2;
1694 	}
1695 
1696 	freeaddrinfo(addrinfo);
1697 	return -1;
1698 }
1699