194960e5delphij/*
294960e5delphij * Copyright (c) 2002 - 2003
394960e5delphij * NetGroup, Politecnico di Torino (Italy)
494960e5delphij * All rights reserved.
594960e5delphij *
694960e5delphij * Redistribution and use in source and binary forms, with or without
794960e5delphij * modification, are permitted provided that the following conditions
894960e5delphij * are met:
994960e5delphij *
1094960e5delphij * 1. Redistributions of source code must retain the above copyright
1194960e5delphij * notice, this list of conditions and the following disclaimer.
1294960e5delphij * 2. Redistributions in binary form must reproduce the above copyright
1394960e5delphij * notice, this list of conditions and the following disclaimer in the
1494960e5delphij * documentation and/or other materials provided with the distribution.
1594960e5delphij * 3. Neither the name of the Politecnico di Torino nor the names of its
1694960e5delphij * contributors may be used to endorse or promote products derived from
1794960e5delphij * this software without specific prior written permission.
1894960e5delphij *
1994960e5delphij * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2094960e5delphij * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2194960e5delphij * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2294960e5delphij * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2394960e5delphij * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2494960e5delphij * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2594960e5delphij * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2694960e5delphij * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2794960e5delphij * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2894960e5delphij * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2994960e5delphij * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3094960e5delphij *
3194960e5delphij */
3294960e5delphij
3394960e5delphij#ifdef HAVE_CONFIG_H
3419bb0b8hselasky#include <config.h>
3594960e5delphij#endif
3694960e5delphij
3794960e5delphij/*
3894960e5delphij * \file sockutils.c
3994960e5delphij *
4094960e5delphij * The goal of this file is to provide a common set of primitives for socket
4194960e5delphij * manipulation.
4294960e5delphij *
4394960e5delphij * Although the socket interface defined in the RFC 2553 (and its updates)
4494960e5delphij * is excellent, there are still differences between the behavior of those
4594960e5delphij * routines on UN*X and Windows, and between UN*Xes.
4694960e5delphij *
4794960e5delphij * These calls provide an interface similar to the socket interface, but
4894960e5delphij * that hides the differences between operating systems.  It does not
4994960e5delphij * attempt to significantly improve on the socket interface in other
5094960e5delphij * ways.
5194960e5delphij */
5294960e5delphij
5319bb0b8hselasky#include "ftmacros.h"
5419bb0b8hselasky
5519bb0b8hselasky#include <string.h>
5694960e5delphij#include <errno.h>	/* for the errno variable */
5794960e5delphij#include <stdio.h>	/* for the stderr file */
5894960e5delphij#include <stdlib.h>	/* for malloc() and free() */
5994960e5delphij#ifdef HAVE_LIMITS_H
6094960e5delphij#include <limits.h>
6194960e5delphij#else
6294960e5delphij#define INT_MAX		2147483647
6394960e5delphij#endif
6494960e5delphij
6519bb0b8hselasky#include "pcap-int.h"
6619bb0b8hselasky
6794960e5delphij#include "sockutils.h"
6819bb0b8hselasky#include "portability.h"
6994960e5delphij
7094960e5delphij#ifdef _WIN32
7194960e5delphij  /*
7294960e5delphij   * Winsock initialization.
7394960e5delphij   *
7494960e5delphij   * Ask for WinSock 2.2.
7594960e5delphij   */
7694960e5delphij  #define WINSOCK_MAJOR_VERSION 2
7794960e5delphij  #define WINSOCK_MINOR_VERSION 2
7894960e5delphij
7994960e5delphij  static int sockcount = 0;	/*!< Variable that allows calling the WSAStartup() only one time */
8094960e5delphij#endif
8194960e5delphij
8294960e5delphij/* Some minor differences between UNIX and Win32 */
8394960e5delphij#ifdef _WIN32
8494960e5delphij  #define SHUT_WR SD_SEND	/* The control code for shutdown() is different in Win32 */
8594960e5delphij#endif
8694960e5delphij
8794960e5delphij/* Size of the buffer that has to keep error messages */
8894960e5delphij#define SOCK_ERRBUF_SIZE 1024
8994960e5delphij
9094960e5delphij/* Constants; used in order to keep strings here */
9194960e5delphij#define SOCKET_NO_NAME_AVAILABLE "No name available"
9294960e5delphij#define SOCKET_NO_PORT_AVAILABLE "No port available"
9394960e5delphij#define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
9494960e5delphij
9519bb0b8hselasky/*
9619bb0b8hselasky * On UN*X, send() and recv() return ssize_t.
9719bb0b8hselasky *
9819bb0b8hselasky * On Windows, send() and recv() return an int.
9919bb0b8hselasky *
10019bb0b8hselasky *   Wth MSVC, there *is* no ssize_t.
10119bb0b8hselasky *
10219bb0b8hselasky *   With MinGW, there is an ssize_t type; it is either an int (32 bit)
103c2630c9philip *   or a long long (64 bit).
10419bb0b8hselasky *
10519bb0b8hselasky * So, on Windows, if we don't have ssize_t defined, define it as an
10619bb0b8hselasky * int, so we can use it, on all platforms, as the type of variables
10719bb0b8hselasky * that hold the return values from send() and recv().
10819bb0b8hselasky */
10919bb0b8hselasky#if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
11019bb0b8hselaskytypedef int ssize_t;
11119bb0b8hselasky#endif
11219bb0b8hselasky
11394960e5delphij/****************************************************
11494960e5delphij *                                                  *
11594960e5delphij * Locally defined functions                        *
11694960e5delphij *                                                  *
11794960e5delphij ****************************************************/
11894960e5delphij
11994960e5delphijstatic int sock_ismcastaddr(const struct sockaddr *saddr);
12094960e5delphij
12194960e5delphij/****************************************************
12294960e5delphij *                                                  *
12394960e5delphij * Function bodies                                  *
12494960e5delphij *                                                  *
12594960e5delphij ****************************************************/
12694960e5delphij
12794960e5delphij/*
12819bb0b8hselasky * Format an error message given an errno value (UN*X) or a WinSock error
12919bb0b8hselasky * (Windows).
13094960e5delphij */
13119bb0b8hselaskyvoid sock_fmterror(const char *caller, int errcode, char *errbuf, int errbuflen)
13294960e5delphij{
13394960e5delphij	if (errbuf == NULL)
13494960e5delphij		return;
13594960e5delphij
136c2630c9philip#ifdef _WIN32
137c2630c9philip	pcap_fmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
138c2630c9philip	    "%s", caller);
13994960e5delphij#else
140c2630c9philip	pcap_fmt_errmsg_for_errno(errbuf, errbuflen, errcode,
141c2630c9philip	    "%s", caller);
14219bb0b8hselasky#endif
14319bb0b8hselasky}
14419bb0b8hselasky
14519bb0b8hselasky/*
14619bb0b8hselasky * \brief It retrieves the error message after an error occurred in the socket interface.
14719bb0b8hselasky *
14819bb0b8hselasky * This function is defined because of the different way errors are returned in UNIX
14919bb0b8hselasky * and Win32. This function provides a consistent way to retrieve the error message
15019bb0b8hselasky * (after a socket error occurred) on all the platforms.
15119bb0b8hselasky *
15219bb0b8hselasky * \param caller: a pointer to a user-allocated string which contains a message that has
15319bb0b8hselasky * to be printed *before* the true error message. It could be, for example, 'this error
154c2630c9philip * comes from the recv() call at line 31'.
15519bb0b8hselasky *
15619bb0b8hselasky * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
15719bb0b8hselasky * error message. This buffer has to be at least 'errbuflen' in length.
15819bb0b8hselasky * It can be NULL; in this case the error cannot be printed.
15919bb0b8hselasky *
16019bb0b8hselasky * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
16119bb0b8hselasky * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
16219bb0b8hselasky *
16319bb0b8hselasky * \return No return values. The error message is returned in the 'string' parameter.
16419bb0b8hselasky */
16519bb0b8hselaskyvoid sock_geterror(const char *caller, char *errbuf, int errbuflen)
16619bb0b8hselasky{
16719bb0b8hselasky#ifdef _WIN32
16819bb0b8hselasky	sock_fmterror(caller, GetLastError(), errbuf, errbuflen);
16919bb0b8hselasky#else
17019bb0b8hselasky	sock_fmterror(caller, errno, errbuf, errbuflen);
17194960e5delphij#endif
17294960e5delphij}
17394960e5delphij
17494960e5delphij/*
175c2630c9philip * \brief This function initializes the socket mechanism if it hasn't
176c2630c9philip * already been initialized or reinitializes it after it has been
177c2630c9philip * cleaned up.
17894960e5delphij *
179c2630c9philip * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
180c2630c9philip * initialize Winsock.
18194960e5delphij *
182c2630c9philip * \param errbuf: a pointer to an user-allocated buffer that will contain
183c2630c9philip * the complete error message. This buffer has to be at least 'errbuflen'
184c2630c9philip * in length. It can be NULL; in this case no error message is supplied.
18594960e5delphij *
186c2630c9philip * \param errbuflen: length of the buffer that will contains the error.
187c2630c9philip * The error message cannot be larger than 'errbuflen - 1' because the
188c2630c9philip * last char is reserved for the string terminator.
18994960e5delphij *
190c2630c9philip * \return '0' if everything is fine, '-1' if some errors occurred. The
191c2630c9philip * error message is returned in the buffer pointed to by 'errbuf' variable.
19294960e5delphij */
19319bb0b8hselasky#ifdef _WIN32
19494960e5delphijint sock_init(char *errbuf, int errbuflen)
19594960e5delphij{
19694960e5delphij	if (sockcount == 0)
19794960e5delphij	{
19894960e5delphij		WSADATA wsaData;			/* helper variable needed to initialize Winsock */
19994960e5delphij
20094960e5delphij		if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
20194960e5delphij		    WINSOCK_MINOR_VERSION), &wsaData) != 0)
20294960e5delphij		{
20394960e5delphij			if (errbuf)
20494960e5delphij				pcap_snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
20594960e5delphij
20694960e5delphij			WSACleanup();
20794960e5delphij
20894960e5delphij			return -1;
20994960e5delphij		}
21094960e5delphij	}
21194960e5delphij
21294960e5delphij	sockcount++;
213c2630c9philip	return 0;
214c2630c9philip}
21519bb0b8hselasky#else
21619bb0b8hselaskyint sock_init(char *errbuf _U_, int errbuflen _U_)
21719bb0b8hselasky{
218c2630c9philip	/*
219c2630c9philip	 * Nothing to do on UN*Xes.
220c2630c9philip	 */
22194960e5delphij	return 0;
22294960e5delphij}
223c2630c9philip#endif
22494960e5delphij
22594960e5delphij/*
226c2630c9philip * \brief This function cleans up the socket mechanism if we have no
227c2630c9philip * sockets left open.
22894960e5delphij *
229c2630c9philip * On UN*Xes, it doesn't need to do anything; on Windows, it needs
230c2630c9philip * to clean up Winsock.
23194960e5delphij *
23294960e5delphij * \return No error values.
23394960e5delphij */
23494960e5delphijvoid sock_cleanup(void)
23594960e5delphij{
23694960e5delphij#ifdef _WIN32
23794960e5delphij	sockcount--;
23894960e5delphij
23994960e5delphij	if (sockcount == 0)
24094960e5delphij		WSACleanup();
24194960e5delphij#endif
24294960e5delphij}
24394960e5delphij
24494960e5delphij/*
24594960e5delphij * \brief It checks if the sockaddr variable contains a multicast address.
24694960e5delphij *
24794960e5delphij * \return '0' if the address is multicast, '-1' if it is not.
24894960e5delphij */
24994960e5delphijstatic int sock_ismcastaddr(const struct sockaddr *saddr)
25094960e5delphij{
25194960e5delphij	if (saddr->sa_family == PF_INET)
25294960e5delphij	{
25394960e5delphij		struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
25494960e5delphij		if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
25594960e5delphij		else return -1;
25694960e5delphij	}
25794960e5delphij	else
25894960e5delphij	{
25994960e5delphij		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
26094960e5delphij		if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
26194960e5delphij		else return -1;
26294960e5delphij	}
26394960e5delphij}
26494960e5delphij
26594960e5delphij/*
26694960e5delphij * \brief It initializes a network connection both from the client and the server side.
26794960e5delphij *
26894960e5delphij * In case of a client socket, this function calls socket() and connect().
26994960e5delphij * In the meanwhile, it checks for any socket error.
27094960e5delphij * If an error occurs, it writes the error message into 'errbuf'.
27194960e5delphij *
27294960e5delphij * In case of a server socket, the function calls socket(), bind() and listen().
27394960e5delphij *
27494960e5delphij * This function is usually preceeded by the sock_initaddress().
27594960e5delphij *
27694960e5delphij * \param addrinfo: pointer to an addrinfo variable which will be used to
27794960e5delphij * open the socket and such. This variable is the one returned by the previous call to
27894960e5delphij * sock_initaddress().
27994960e5delphij *
28094960e5delphij * \param server: '1' if this is a server socket, '0' otherwise.
28194960e5delphij *
28294960e5delphij * \param nconn: number of the connections that are allowed to wait into the listen() call.
28394960e5delphij * This value has no meanings in case of a client socket.
28494960e5delphij *
28594960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
28694960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
28794960e5delphij * It can be NULL; in this case the error cannot be printed.
28894960e5delphij *
28994960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
29094960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
29194960e5delphij *
29294960e5delphij * \return the socket that has been opened (that has to be used in the following sockets calls)
29319bb0b8hselasky * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
29494960e5delphij * in the 'errbuf' variable.
29594960e5delphij */
29694960e5delphijSOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
29794960e5delphij{
29894960e5delphij	SOCKET sock;
29919bb0b8hselasky#if defined(SO_NOSIGPIPE) || defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
30019bb0b8hselasky	int on = 1;
30119bb0b8hselasky#endif
30294960e5delphij
30394960e5delphij	sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
30419bb0b8hselasky	if (sock == INVALID_SOCKET)
30594960e5delphij	{
306c2630c9philip		sock_geterror("socket()", errbuf, errbuflen);
30719bb0b8hselasky		return INVALID_SOCKET;
30894960e5delphij	}
30994960e5delphij
31019bb0b8hselasky	/*
31119bb0b8hselasky	 * Disable SIGPIPE, if we have SO_NOSIGPIPE.  We don't want to
31219bb0b8hselasky	 * have to deal with signals if the peer closes the connection,
31319bb0b8hselasky	 * especially in client programs, which may not even be aware that
31419bb0b8hselasky	 * they're sending to sockets.
31519bb0b8hselasky	 */
31619bb0b8hselasky#ifdef SO_NOSIGPIPE
31719bb0b8hselasky	if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
31819bb0b8hselasky	    sizeof (int)) == -1)
31919bb0b8hselasky	{
32019bb0b8hselasky		sock_geterror("setsockopt(SO_NOSIGPIPE)", errbuf, errbuflen);
32119bb0b8hselasky		closesocket(sock);
32219bb0b8hselasky		return INVALID_SOCKET;
32319bb0b8hselasky	}
32419bb0b8hselasky#endif
32594960e5delphij
32694960e5delphij	/* This is a server socket */
32794960e5delphij	if (server)
32894960e5delphij	{
329c2630c9philip		/*
330c2630c9philip		 * Allow a new server to bind the socket after the old one
331c2630c9philip		 * exited, even if lingering sockets are still present.
332c2630c9philip		 *
333c2630c9philip		 * Don't treat an error as a failure.
334c2630c9philip		 */
335c2630c9philip		int optval = 1;
336c2630c9philip		(void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
337c2630c9philip		    (char *)&optval, sizeof (optval));
338c2630c9philip
33919bb0b8hselasky#if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
34094960e5delphij		/*
34119bb0b8hselasky		 * Force the use of IPv6-only addresses.
34219bb0b8hselasky		 *
34319bb0b8hselasky		 * RFC 3493 indicates that you can support IPv4 on an
34419bb0b8hselasky		 * IPv6 socket:
34519bb0b8hselasky		 *
34619bb0b8hselasky		 *    https://tools.ietf.org/html/rfc3493#section-3.7
34719bb0b8hselasky		 *
34819bb0b8hselasky		 * and that this is the default behavior.  This means
34919bb0b8hselasky		 * that if we first create an IPv6 socket bound to the
35019bb0b8hselasky		 * "any" address, it is, in effect, also bound to the
35119bb0b8hselasky		 * IPv4 "any" address, so when we create an IPv4 socket
35219bb0b8hselasky		 * and try to bind it to the IPv4 "any" address, it gets
35319bb0b8hselasky		 * EADDRINUSE.
35419bb0b8hselasky		 *
35519bb0b8hselasky		 * Not all network stacks support IPv4 on IPv6 sockets;
35619bb0b8hselasky		 * pre-NT 6 Windows stacks don't support it, and the
35719bb0b8hselasky		 * OpenBSD stack doesn't support it for security reasons
35819bb0b8hselasky		 * (see the OpenBSD inet6(4) man page).  Therefore, we
35919bb0b8hselasky		 * don't want to rely on this behavior.
36019bb0b8hselasky		 *
36119bb0b8hselasky		 * So we try to disable it, using either the IPV6_V6ONLY
36219bb0b8hselasky		 * option from RFC 3493:
36319bb0b8hselasky		 *
36419bb0b8hselasky		 *    https://tools.ietf.org/html/rfc3493#section-5.3
36519bb0b8hselasky		 *
36619bb0b8hselasky		 * or the IPV6_BINDV6ONLY option from older UN*Xes.
36794960e5delphij		 */
36819bb0b8hselasky#ifndef IPV6_V6ONLY
36919bb0b8hselasky  /* For older systems */
37019bb0b8hselasky  #define IPV6_V6ONLY IPV6_BINDV6ONLY
37119bb0b8hselasky#endif /* IPV6_V6ONLY */
37294960e5delphij		if (addrinfo->ai_family == PF_INET6)
37394960e5delphij		{
37419bb0b8hselasky			if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
37519bb0b8hselasky			    (char *)&on, sizeof (int)) == -1)
37694960e5delphij			{
37794960e5delphij				if (errbuf)
37819bb0b8hselasky					pcap_snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
37919bb0b8hselasky				closesocket(sock);
38019bb0b8hselasky				return INVALID_SOCKET;
38194960e5delphij			}
38294960e5delphij		}
38319bb0b8hselasky#endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
38494960e5delphij
38594960e5delphij		/* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
38694960e5delphij		if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
38794960e5delphij		{
388c2630c9philip			sock_geterror("bind()", errbuf, errbuflen);
38919bb0b8hselasky			closesocket(sock);
39019bb0b8hselasky			return INVALID_SOCKET;
39194960e5delphij		}
39294960e5delphij
39394960e5delphij		if (addrinfo->ai_socktype == SOCK_STREAM)
39494960e5delphij			if (listen(sock, nconn) == -1)
39594960e5delphij			{
396c2630c9philip				sock_geterror("listen()", errbuf, errbuflen);
39719bb0b8hselasky				closesocket(sock);
39819bb0b8hselasky				return INVALID_SOCKET;
39994960e5delphij			}
40094960e5delphij
40194960e5delphij		/* server side ended */
40294960e5delphij		return sock;
40394960e5delphij	}
40494960e5delphij	else	/* we're the client */
40594960e5delphij	{
40694960e5delphij		struct addrinfo *tempaddrinfo;
40794960e5delphij		char *errbufptr;
40894960e5delphij		size_t bufspaceleft;
40994960e5delphij
41094960e5delphij		tempaddrinfo = addrinfo;
41194960e5delphij		errbufptr = errbuf;
41294960e5delphij		bufspaceleft = errbuflen;
41394960e5delphij		*errbufptr = 0;
41494960e5delphij
41594960e5delphij		/*
41694960e5delphij		 * We have to loop though all the addinfo returned.
41794960e5delphij		 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
41894960e5delphij		 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
41994960e5delphij		 */
42094960e5delphij		while (tempaddrinfo)
42194960e5delphij		{
42294960e5delphij
42394960e5delphij			if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
42494960e5delphij			{
42594960e5delphij				size_t msglen;
42694960e5delphij				char TmpBuffer[100];
42794960e5delphij				char SocketErrorMessage[SOCK_ERRBUF_SIZE];
42894960e5delphij
42994960e5delphij				/*
43094960e5delphij				 * We have to retrieve the error message before any other socket call completes, otherwise
43194960e5delphij				 * the error message is lost
43294960e5delphij				 */
433c2630c9philip				sock_geterror("Connect to socket failed",
434c2630c9philip				    SocketErrorMessage, sizeof(SocketErrorMessage));
43594960e5delphij
43694960e5delphij				/* Returns the numeric address of the host that triggered the error */
43794960e5delphij				sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
43894960e5delphij
43994960e5delphij				pcap_snprintf(errbufptr, bufspaceleft,
440c2630c9philip				    "Is the server properly installed on %s?  %s", TmpBuffer, SocketErrorMessage);
44194960e5delphij
44294960e5delphij				/* In case more then one 'connect' fails, we manage to keep all the error messages */
44394960e5delphij				msglen = strlen(errbufptr);
44494960e5delphij
44594960e5delphij				errbufptr[msglen] = ' ';
44694960e5delphij				errbufptr[msglen + 1] = 0;
44794960e5delphij
44894960e5delphij				bufspaceleft = bufspaceleft - (msglen + 1);
44994960e5delphij				errbufptr += (msglen + 1);
45094960e5delphij
45194960e5delphij				tempaddrinfo = tempaddrinfo->ai_next;
45294960e5delphij			}
45394960e5delphij			else
45494960e5delphij				break;
45594960e5delphij		}
45694960e5delphij
45794960e5delphij		/*
45894960e5delphij		 * Check how we exit from the previous loop
45994960e5delphij		 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
46094960e5delphij		 */
46194960e5delphij		if (tempaddrinfo == NULL)
46294960e5delphij		{
46394960e5delphij			closesocket(sock);
46419bb0b8hselasky			return INVALID_SOCKET;
46594960e5delphij		}
46694960e5delphij		else
46794960e5delphij			return sock;
46894960e5delphij	}
46994960e5delphij}
47094960e5delphij
47194960e5delphij/*
47294960e5delphij * \brief Closes the present (TCP and UDP) socket connection.
47394960e5delphij *
47494960e5delphij * This function sends a shutdown() on the socket in order to disable send() calls
47594960e5delphij * (while recv() ones are still allowed). Then, it closes the socket.
47694960e5delphij *
47794960e5delphij * \param sock: the socket identifier of the connection that has to be closed.
47894960e5delphij *
47994960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
48094960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
48194960e5delphij * It can be NULL; in this case the error cannot be printed.
48294960e5delphij *
48394960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
48494960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
48594960e5delphij *
48694960e5delphij * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
48794960e5delphij * in the 'errbuf' variable.
48894960e5delphij */
48994960e5delphijint sock_close(SOCKET sock, char *errbuf, int errbuflen)
49094960e5delphij{
49194960e5delphij	/*
49294960e5delphij	 * SHUT_WR: subsequent calls to the send function are disallowed.
49394960e5delphij	 * For TCP sockets, a FIN will be sent after all data is sent and
49494960e5delphij	 * acknowledged by the Server.
49594960e5delphij	 */
49694960e5delphij	if (shutdown(sock, SHUT_WR))
49794960e5delphij	{
498c2630c9philip		sock_geterror("shutdown()", errbuf, errbuflen);
49994960e5delphij		/* close the socket anyway */
50094960e5delphij		closesocket(sock);
50194960e5delphij		return -1;
50294960e5delphij	}
50394960e5delphij
50494960e5delphij	closesocket(sock);
50594960e5delphij	return 0;
50694960e5delphij}
50794960e5delphij
50894960e5delphij/*
509c2630c9philip * gai_errstring() has some problems:
510c2630c9philip *
511c2630c9philip * 1) on Windows, Microsoft explicitly says it's not thread-safe;
512c2630c9philip * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
513c2630c9philip *    thread-safe, so an implementation might use a static buffer
514c2630c9philip *    for unknown error codes;
515c2630c9philip * 3) the error message for the most likely error, EAI_NONAME, is
516c2630c9philip *    truly horrible on several platforms ("nodename nor servname
517c2630c9philip *    provided, or not known"?  It's typically going to be "not
518c2630c9philip *    known", not "oopsie, I passed null pointers for the host name
519c2630c9philip *    and service name", not to mention they forgot the "neither");
520c2630c9philip *
521c2630c9philip * so we roll our own.
522c2630c9philip */
523c2630c9philipstatic void
524c2630c9philipget_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
525c2630c9philip    const char *hostname, const char *portname)
526c2630c9philip{
527c2630c9philip	char hostport[PCAP_ERRBUF_SIZE];
528c2630c9philip
529c2630c9philip	if (hostname != NULL && portname != NULL)
530c2630c9philip		pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s:%s",
531c2630c9philip		    hostname, portname);
532c2630c9philip	else if (hostname != NULL)
533c2630c9philip		pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s",
534c2630c9philip		    hostname);
535c2630c9philip	else if (portname != NULL)
536c2630c9philip		pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, ":%s",
537c2630c9philip		    portname);
538c2630c9philip	else
539c2630c9philip		pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
540c2630c9philip	switch (err)
541c2630c9philip	{
542c2630c9philip#ifdef EAI_ADDRFAMILY
543c2630c9philip		case EAI_ADDRFAMILY:
544c2630c9philip			pcap_snprintf(errbuf, errbuflen,
545c2630c9philip			    "%sAddress family for %s not supported",
546c2630c9philip			    prefix, hostport);
547c2630c9philip			break;
548c2630c9philip#endif
549c2630c9philip
550c2630c9philip		case EAI_AGAIN:
551c2630c9philip			pcap_snprintf(errbuf, errbuflen,
552c2630c9philip			    "%s%s could not be resolved at this time",
553c2630c9philip			    prefix, hostport);
554c2630c9philip			break;
555c2630c9philip
556c2630c9philip		case EAI_BADFLAGS:
557c2630c9philip			pcap_snprintf(errbuf, errbuflen,
558c2630c9philip			    "%sThe ai_flags parameter for looking up %s had an invalid value",
559c2630c9philip			    prefix, hostport);
560c2630c9philip			break;
561c2630c9philip
562c2630c9philip		case EAI_FAIL:
563c2630c9philip			pcap_snprintf(errbuf, errbuflen,
564c2630c9philip			    "%sA non-recoverable error occurred when attempting to resolve %s",
565c2630c9philip			    prefix, hostport);
566c2630c9philip			break;
567c2630c9philip
568c2630c9philip		case EAI_FAMILY:
569c2630c9philip			pcap_snprintf(errbuf, errbuflen,
570c2630c9philip			    "%sThe address family for looking up %s was not recognized",
571c2630c9philip			    prefix, hostport);
572c2630c9philip			break;
573c2630c9philip
574c2630c9philip		case EAI_MEMORY:
575c2630c9philip			pcap_snprintf(errbuf, errbuflen,
576c2630c9philip			    "%sOut of memory trying to allocate storage when looking up %s",
577c2630c9philip			    prefix, hostport);
578c2630c9philip			break;
579c2630c9philip
580c2630c9philip		/*
581c2630c9philip		 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
582c2630c9philip		 *
583c2630c9philip		 * RFC 3493 has only EAI_NONAME.
584c2630c9philip		 *
585c2630c9philip		 * Some implementations define EAI_NODATA and EAI_NONAME
586c2630c9philip		 * to the same value, others don't.  If EAI_NODATA is
587c2630c9philip		 * defined and isn't the same as EAI_NONAME, we handle
588c2630c9philip		 * EAI_NODATA.
589c2630c9philip		 */
590c2630c9philip#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
591c2630c9philip		case EAI_NODATA:
592c2630c9philip			pcap_snprintf(errbuf, errbuflen,
593c2630c9philip			    "%sNo address associated with %s",
594c2630c9philip			    prefix, hostport);
595c2630c9philip			break;
596c2630c9philip#endif
597c2630c9philip
598c2630c9philip		case EAI_NONAME:
599c2630c9philip			pcap_snprintf(errbuf, errbuflen,
600c2630c9philip			    "%sThe host name %s couldn't be resolved",
601c2630c9philip			    prefix, hostport);
602c2630c9philip			break;
603c2630c9philip
604c2630c9philip		case EAI_SERVICE:
605c2630c9philip			pcap_snprintf(errbuf, errbuflen,
606c2630c9philip			    "%sThe service value specified when looking up %s as not recognized for the socket type",
607c2630c9philip			    prefix, hostport);
608c2630c9philip			break;
609c2630c9philip
610c2630c9philip		case EAI_SOCKTYPE:
611c2630c9philip			pcap_snprintf(errbuf, errbuflen,
612c2630c9philip			    "%sThe socket type specified when looking up %s as not recognized",
613c2630c9philip			    prefix, hostport);
614c2630c9philip			break;
615c2630c9philip
616c2630c9philip#ifdef EAI_SYSTEM
617c2630c9philip		case EAI_SYSTEM:
618c2630c9philip			/*
619c2630c9philip			 * Assumed to be UN*X.
620c2630c9philip			 */
621c2630c9philip			pcap_snprintf(errbuf, errbuflen,
622c2630c9philip			    "%sAn error occurred when looking up %s: %s",
623c2630c9philip			    prefix, hostport, pcap_strerror(errno));
624c2630c9philip			break;
625c2630c9philip#endif
626c2630c9philip
627c2630c9philip#ifdef EAI_BADHINTS
628c2630c9philip		case EAI_BADHINTS:
629c2630c9philip			pcap_snprintf(errbuf, errbuflen,
630c2630c9philip			    "%sInvalid value for hints when looking up %s",
631c2630c9philip			    prefix, hostport);
632c2630c9philip			break;
633c2630c9philip#endif
634c2630c9philip
635c2630c9philip#ifdef EAI_PROTOCOL
636c2630c9philip		case EAI_PROTOCOL:
637c2630c9philip			pcap_snprintf(errbuf, errbuflen,
638c2630c9philip			    "%sResolved protocol when looking up %s is unknown",
639c2630c9philip			    prefix, hostport);
640c2630c9philip			break;
641c2630c9philip#endif
642c2630c9philip
643c2630c9philip#ifdef EAI_OVERFLOW
644c2630c9philip		case EAI_OVERFLOW:
645c2630c9philip			pcap_snprintf(errbuf, errbuflen,
646c2630c9philip			    "%sArgument buffer overflow when looking up %s",
647c2630c9philip			    prefix, hostport);
648c2630c9philip			break;
649c2630c9philip#endif
650c2630c9philip
651c2630c9philip		default:
652c2630c9philip			pcap_snprintf(errbuf, errbuflen,
653c2630c9philip			    "%sgetaddrinfo() error %d when looking up %s",
654c2630c9philip			    prefix, err, hostport);
655c2630c9philip			break;
656c2630c9philip	}
657c2630c9philip}
658c2630c9philip
659c2630c9philip/*
66094960e5delphij * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
66194960e5delphij *
66294960e5delphij * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
66394960e5delphij * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
66494960e5delphij * If an error occurs, it writes the error message into 'errbuf'.
66594960e5delphij *
66694960e5delphij * \param host: a pointer to a string identifying the host. It can be
66794960e5delphij * a host name, a numeric literal address, or NULL or "" (useful
66894960e5delphij * in case of a server socket which has to bind to all addresses).
66994960e5delphij *
67094960e5delphij * \param port: a pointer to a user-allocated buffer containing the network port to use.
67194960e5delphij *
67294960e5delphij * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
67394960e5delphij * addrinfo structure appropriately.
67494960e5delphij *
67594960e5delphij * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
67694960e5delphij * (passed by reference), which will be allocated by this function and returned back to the caller.
67794960e5delphij * This variable will be used in the next sockets calls.
67894960e5delphij *
67994960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
68094960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
68194960e5delphij * It can be NULL; in this case the error cannot be printed.
68294960e5delphij *
68394960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
68494960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
68594960e5delphij *
68694960e5delphij * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
68794960e5delphij * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
68894960e5delphij * returned into the addrinfo parameter.
68994960e5delphij *
69094960e5delphij * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
69194960e5delphij * it is no longer needed.
69294960e5delphij *
69394960e5delphij * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
69494960e5delphij * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
69594960e5delphij * the programmer to look at that function in order to set the 'hints' variable appropriately.
69694960e5delphij */
69794960e5delphijint sock_initaddress(const char *host, const char *port,
69894960e5delphij    struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
69994960e5delphij{
70094960e5delphij	int retval;
70194960e5delphij
70294960e5delphij	retval = getaddrinfo(host, port, hints, addrinfo);
70394960e5delphij	if (retval != 0)
70494960e5delphij	{
70594960e5delphij		if (errbuf)
70694960e5delphij		{
707c2630c9philip			get_gai_errstring(errbuf, errbuflen, "", retval,
708c2630c9philip			    host, port);
70994960e5delphij		}
71094960e5delphij		return -1;
71194960e5delphij	}
71294960e5delphij	/*
71394960e5delphij	 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
71494960e5delphij	 * addrinfo has more han one pointers
71594960e5delphij	 */
71694960e5delphij
71794960e5delphij	/*
71894960e5delphij	 * This software only supports PF_INET and PF_INET6.
71994960e5delphij	 *
72094960e5delphij	 * XXX - should we just check that at least *one* address is
72194960e5delphij	 * either PF_INET or PF_INET6, and, when using the list,
72294960e5delphij	 * ignore all addresses that are neither?  (What, no IPX
72394960e5delphij	 * support? :-))
72494960e5delphij	 */
72594960e5delphij	if (((*addrinfo)->ai_family != PF_INET) &&
72694960e5delphij	    ((*addrinfo)->ai_family != PF_INET6))
72794960e5delphij	{
72894960e5delphij		if (errbuf)
72994960e5delphij			pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
73019bb0b8hselasky		freeaddrinfo(*addrinfo);
73119bb0b8hselasky		*addrinfo = NULL;
73294960e5delphij		return -1;
73394960e5delphij	}
73494960e5delphij
73594960e5delphij	/*
73694960e5delphij	 * You can't do multicast (or broadcast) TCP.
73794960e5delphij	 */
73894960e5delphij	if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
73994960e5delphij	    (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
74094960e5delphij	{
74194960e5delphij		if (errbuf)
74294960e5delphij			pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
74319bb0b8hselasky		freeaddrinfo(*addrinfo);
74419bb0b8hselasky		*addrinfo = NULL;
74594960e5delphij		return -1;
74694960e5delphij	}
74794960e5delphij
74894960e5delphij	return 0;
74994960e5delphij}
75094960e5delphij
75194960e5delphij/*
75294960e5delphij * \brief It sends the amount of data contained into 'buffer' on the given socket.
75394960e5delphij *
75494960e5delphij * This function basically calls the send() socket function and it checks that all
75594960e5delphij * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
75694960e5delphij * it writes the error message into 'errbuf'.
75794960e5delphij * In case the socket buffer does not have enough space, it loops until all data
75894960e5delphij * has been sent.
75994960e5delphij *
76094960e5delphij * \param socket: the connected socket currently opened.
76194960e5delphij *
76294960e5delphij * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
76394960e5delphij *
76494960e5delphij * \param size: number of bytes that have to be sent.
76594960e5delphij *
76694960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
76794960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
76894960e5delphij * It can be NULL; in this case the error cannot be printed.
76994960e5delphij *
77094960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
77194960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
77294960e5delphij *
77319bb0b8hselasky * \return '0' if everything is fine, '-1' if an error other than
77419bb0b8hselasky * "connection reset" or "peer has closed the receive side" occurred,
77519bb0b8hselasky * '-2' if we got one of those errors.
77619bb0b8hselasky * For errors, an error message is returned in the 'errbuf' variable.
77794960e5delphij */
77819bb0b8hselaskyint sock_send(SOCKET sock, const char *buffer, size_t size,
77919bb0b8hselasky    char *errbuf, int errbuflen)
78094960e5delphij{
78119bb0b8hselasky	int remaining;
78219bb0b8hselasky	ssize_t nsent;
78394960e5delphij
78419bb0b8hselasky	if (size > INT_MAX)
78594960e5delphij	{
78619bb0b8hselasky		if (errbuf)
78719bb0b8hselasky		{
78819bb0b8hselasky			pcap_snprintf(errbuf, errbuflen,
789c2630c9philip			    "Can't send more than %u bytes with sock_send",
79019bb0b8hselasky			    INT_MAX);
79119bb0b8hselasky		}
79294960e5delphij		return -1;
79394960e5delphij	}
79419bb0b8hselasky	remaining = (int)size;
79594960e5delphij
79619bb0b8hselasky	do {
79719bb0b8hselasky#ifdef MSG_NOSIGNAL
79819bb0b8hselasky		/*
79919bb0b8hselasky		 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
80019bb0b8hselasky		 * on errors on stream-oriented sockets when the other
80119bb0b8hselasky		 * end breaks the connection.
80219bb0b8hselasky		 * The EPIPE error is still returned.
80319bb0b8hselasky		 */
80419bb0b8hselasky		nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
80519bb0b8hselasky#else
80619bb0b8hselasky		nsent = send(sock, buffer, remaining, 0);
80719bb0b8hselasky#endif
80819bb0b8hselasky
80919bb0b8hselasky		if (nsent == -1)
81019bb0b8hselasky		{
81119bb0b8hselasky			/*
81219bb0b8hselasky			 * If the client closed the connection out from
81319bb0b8hselasky			 * under us, there's no need to log that as an
81419bb0b8hselasky			 * error.
81519bb0b8hselasky			 */
81619bb0b8hselasky			int errcode;
81719bb0b8hselasky
81819bb0b8hselasky#ifdef _WIN32
81919bb0b8hselasky			errcode = GetLastError();
82019bb0b8hselasky			if (errcode == WSAECONNRESET ||
82119bb0b8hselasky			    errcode == WSAECONNABORTED)
82219bb0b8hselasky			{
82319bb0b8hselasky				/*
82419bb0b8hselasky				 * WSAECONNABORTED appears to be the error
82519bb0b8hselasky				 * returned in Winsock when you try to send
82619bb0b8hselasky				 * on a connection where the peer has closed
82719bb0b8hselasky				 * the receive side.
82819bb0b8hselasky				 */
82919bb0b8hselasky				return -2;
83019bb0b8hselasky			}
831c2630c9philip			sock_fmterror("send()", errcode, errbuf, errbuflen);
83219bb0b8hselasky#else
83319bb0b8hselasky			errcode = errno;
83419bb0b8hselasky			if (errcode == ECONNRESET || errcode == EPIPE)
83519bb0b8hselasky			{
83619bb0b8hselasky				/*
83719bb0b8hselasky				 * EPIPE is what's returned on UN*X when
83819bb0b8hselasky				 * you try to send on a connection when
83919bb0b8hselasky				 * the peer has closed the receive side.
84019bb0b8hselasky				 */
84119bb0b8hselasky				return -2;
84219bb0b8hselasky			}
843c2630c9philip			sock_fmterror("send()", errcode, errbuf, errbuflen);
84419bb0b8hselasky#endif
84519bb0b8hselasky			return -1;
84619bb0b8hselasky		}
84719bb0b8hselasky
84819bb0b8hselasky		remaining -= nsent;
84994960e5delphij		buffer += nsent;
85019bb0b8hselasky	} while (remaining != 0);
85194960e5delphij
85294960e5delphij	return 0;
85394960e5delphij}
85494960e5delphij
85594960e5delphij/*
85694960e5delphij * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
85794960e5delphij * and it checks for buffer overflows.
85894960e5delphij *
85994960e5delphij * This function basically copies 'size' bytes of data contained into 'buffer'
86094960e5delphij * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
86194960e5delphij * resulting buffer will not be larger	than 'totsize'. Finally, it updates
86294960e5delphij * the 'offset' variable in order to point to the first empty location of the buffer.
86394960e5delphij *
86494960e5delphij * In case the function is called with 'checkonly' equal to 1, it does not copy
86594960e5delphij * the data into the buffer. It only checks for buffer overflows and it updates the
86694960e5delphij * 'offset' variable. This mode can be useful when the buffer already contains the
86794960e5delphij * data (maybe because the producer writes directly into the target buffer), so
86894960e5delphij * only the buffer overflow check has to be made.
86994960e5delphij * In this case, both 'buffer' and 'tempbuf' can be NULL values.
87094960e5delphij *
87194960e5delphij * This function is useful in case the userland application does not know immediately
87294960e5delphij * all the data it has to write into the socket. This function provides a way to create
87394960e5delphij * the "stream" step by step, appending the new data to the old one. Then, when all the
87494960e5delphij * data has been bufferized, the application can call the sock_send() function.
87594960e5delphij *
87694960e5delphij * \param buffer: a char pointer to a user-allocated buffer that keeps the data
87794960e5delphij * that has to be copied.
87894960e5delphij *
87994960e5delphij * \param size: number of bytes that have to be copied.
88094960e5delphij *
88194960e5delphij * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
88294960e5delphij * has to be copied.
88394960e5delphij *
88494960e5delphij * \param offset: an index into 'tempbuf' which keeps the location of its first
88594960e5delphij * empty location.
88694960e5delphij *
88794960e5delphij * \param totsize: total size of the buffer in which data is being copied.
88894960e5delphij *
88994960e5delphij * \param checkonly: '1' if we do not want to copy data into the buffer and we
89094960e5delphij * want just do a buffer ovreflow control, '0' if data has to be copied as well.
89194960e5delphij *
89294960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
89394960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
89494960e5delphij * It can be NULL; in this case the error cannot be printed.
89594960e5delphij *
89694960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
89794960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
89894960e5delphij *
89994960e5delphij * \return '0' if everything is fine, '-1' if some errors occurred. The error message
90094960e5delphij * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
90194960e5delphij * have the new string appended, and 'offset' will keep the length of that buffer.
90294960e5delphij * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
90394960e5delphij *
90494960e5delphij * \warning This function assumes that the buffer in which data has to be stored is
90594960e5delphij * large 'totbuf' bytes.
90694960e5delphij *
90794960e5delphij * \warning In case of 'checkonly', be carefully to call this function *before* copying
90894960e5delphij * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
90994960e5delphij */
91094960e5delphijint sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
91194960e5delphij{
91294960e5delphij	if ((*offset + size) > totsize)
91394960e5delphij	{
91494960e5delphij		if (errbuf)
91594960e5delphij			pcap_snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
91694960e5delphij		return -1;
91794960e5delphij	}
91894960e5delphij
91994960e5delphij	if (!checkonly)
92094960e5delphij		memcpy(tempbuf + (*offset), buffer, size);
92194960e5delphij
92294960e5delphij	(*offset) += size;
92394960e5delphij
92494960e5delphij	return 0;
92594960e5delphij}
92694960e5delphij
92794960e5delphij/*
92894960e5delphij * \brief It waits on a connected socket and it manages to receive data.
92994960e5delphij *
93094960e5delphij * This function basically calls the recv() socket function and it checks that no
93194960e5delphij * error occurred. If that happens, it writes the error message into 'errbuf'.
93294960e5delphij *
93394960e5delphij * This function changes its behavior according to the 'receiveall' flag: if we
93494960e5delphij * want to receive exactly 'size' byte, it loops on the recv()	until all the requested
93594960e5delphij * data is arrived. Otherwise, it returns the data currently available.
93694960e5delphij *
93794960e5delphij * In case the socket does not have enough data available, it cycles on the recv()
93894960e5delphij * until the requested data (of size 'size') is arrived.
93994960e5delphij * In this case, it blocks until the number of bytes read is equal to 'size'.
94094960e5delphij *
94194960e5delphij * \param sock: the connected socket currently opened.
94294960e5delphij *
94394960e5delphij * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
94494960e5delphij *
94594960e5delphij * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
94694960e5delphij * that we are expecting to be read.
94794960e5delphij *
94819bb0b8hselasky * \param flags:
94919bb0b8hselasky *
95019bb0b8hselasky *   SOCK_RECEIVALL_XXX:
95119bb0b8hselasky *
95219bb0b8hselasky * 	if SOCK_RECEIVEALL_NO, return as soon as some data is ready
95319bb0b8hselasky *	if SOCK_RECEIVALL_YES, wait until 'size' data has been
95419bb0b8hselasky *	    received (in case the socket does not have enough data available).
95519bb0b8hselasky *
95619bb0b8hselasky *   SOCK_EOF_XXX:
95719bb0b8hselasky *
95819bb0b8hselasky *	if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
95919bb0b8hselasky *	    and return an error on any subsequent read that returns 0;
96019bb0b8hselasky *	if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
96194960e5delphij *
96294960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
96394960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
96494960e5delphij * It can be NULL; in this case the error cannot be printed.
96594960e5delphij *
96694960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
96794960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
96894960e5delphij *
96994960e5delphij * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
97094960e5delphij * The error message is returned in the 'errbuf' variable.
97194960e5delphij */
97294960e5delphij
97319bb0b8hselaskyint sock_recv(SOCKET sock, void *buffer, size_t size, int flags,
97494960e5delphij    char *errbuf, int errbuflen)
97594960e5delphij{
97694960e5delphij	char *bufp = buffer;
97794960e5delphij	int remaining;
97894960e5delphij	ssize_t nread;
97994960e5delphij
98094960e5delphij	if (size == 0)
98194960e5delphij	{
98294960e5delphij		return 0;
98394960e5delphij	}
98494960e5delphij	if (size > INT_MAX)
98594960e5delphij	{
98619bb0b8hselasky		if (errbuf)
98719bb0b8hselasky		{
98819bb0b8hselasky			pcap_snprintf(errbuf, errbuflen,
98919bb0b8hselasky			    "Can't read more than %u bytes with sock_recv",
99019bb0b8hselasky			    INT_MAX);
99119bb0b8hselasky		}
99294960e5delphij		return -1;
99394960e5delphij	}
99494960e5delphij
99594960e5delphij	bufp = (char *) buffer;
99694960e5delphij	remaining = (int) size;
99794960e5delphij
99894960e5delphij	/*
99994960e5delphij	 * We don't use MSG_WAITALL because it's not supported in
100094960e5delphij	 * Win32.
100194960e5delphij	 */
100294960e5delphij	for (;;) {
100394960e5delphij		nread = recv(sock, bufp, remaining, 0);
100494960e5delphij
100594960e5delphij		if (nread == -1)
100694960e5delphij		{
100794960e5delphij#ifndef _WIN32
100894960e5delphij			if (errno == EINTR)
100994960e5delphij				return -3;
101094960e5delphij#endif
1011c2630c9philip			sock_geterror("recv()", errbuf, errbuflen);
101294960e5delphij			return -1;
101394960e5delphij		}
101494960e5delphij
101594960e5delphij		if (nread == 0)
101694960e5delphij		{
101719bb0b8hselasky			if ((flags & SOCK_EOF_IS_ERROR) ||
101819bb0b8hselasky			    (remaining != (int) size))
101994960e5delphij			{
102019bb0b8hselasky				/*
102119bb0b8hselasky				 * Either we've already read some data,
102219bb0b8hselasky				 * or we're always supposed to return
102319bb0b8hselasky				 * an error on EOF.
102419bb0b8hselasky				 */
102519bb0b8hselasky				if (errbuf)
102619bb0b8hselasky				{
102719bb0b8hselasky					pcap_snprintf(errbuf, errbuflen,
102819bb0b8hselasky					    "The other host terminated the connection.");
102919bb0b8hselasky				}
103019bb0b8hselasky				return -1;
103194960e5delphij			}
103219bb0b8hselasky			else
103319bb0b8hselasky				return 0;
103494960e5delphij		}
103594960e5delphij
103694960e5delphij		/*
103794960e5delphij		 * Do we want to read the amount requested, or just return
103894960e5delphij		 * what we got?
103994960e5delphij		 */
104019bb0b8hselasky		if (!(flags & SOCK_RECEIVEALL_YES))
104194960e5delphij		{
104294960e5delphij			/*
104394960e5delphij			 * Just return what we got.
104494960e5delphij			 */
104594960e5delphij			return (int) nread;
104694960e5delphij		}
104794960e5delphij
104894960e5delphij		bufp += nread;
104994960e5delphij		remaining -= nread;
105094960e5delphij
105194960e5delphij		if (remaining == 0)
105294960e5delphij			return (int) size;
105394960e5delphij	}
105494960e5delphij}
105594960e5delphij
105694960e5delphij/*
105719bb0b8hselasky * Receives a datagram from a socket.
105819bb0b8hselasky *
105919bb0b8hselasky * Returns the size of the datagram on success or -1 on error.
106019bb0b8hselasky */
106119bb0b8hselaskyint sock_recv_dgram(SOCKET sock, void *buffer, size_t size,
106219bb0b8hselasky    char *errbuf, int errbuflen)
106319bb0b8hselasky{
106419bb0b8hselasky	ssize_t nread;
106519bb0b8hselasky#ifndef _WIN32
106619bb0b8hselasky	struct msghdr message;
106719bb0b8hselasky	struct iovec iov;
106819bb0b8hselasky#endif
106919bb0b8hselasky
107019bb0b8hselasky	if (size == 0)
107119bb0b8hselasky	{
107219bb0b8hselasky		return 0;
107319bb0b8hselasky	}
107419bb0b8hselasky	if (size > INT_MAX)
107519bb0b8hselasky	{
107619bb0b8hselasky		if (errbuf)
107719bb0b8hselasky		{
107819bb0b8hselasky			pcap_snprintf(errbuf, errbuflen,
107919bb0b8hselasky			    "Can't read more than %u bytes with sock_recv_dgram",
108019bb0b8hselasky			    INT_MAX);
108119bb0b8hselasky		}
108219bb0b8hselasky		return -1;
108319bb0b8hselasky	}
108419bb0b8hselasky
108519bb0b8hselasky	/*
108619bb0b8hselasky	 * This should be a datagram socket, so we should get the
108719bb0b8hselasky	 * entire datagram in one recv() or recvmsg() call, and
108819bb0b8hselasky	 * don't need to loop.
108919bb0b8hselasky	 */
109019bb0b8hselasky#ifdef _WIN32
109119bb0b8hselasky	nread = recv(sock, buffer, size, 0);
109219bb0b8hselasky	if (nread == SOCKET_ERROR)
109319bb0b8hselasky	{
109419bb0b8hselasky		/*
109519bb0b8hselasky		 * To quote the MSDN documentation for recv(),
109619bb0b8hselasky		 * "If the datagram or message is larger than
109719bb0b8hselasky		 * the buffer specified, the buffer is filled
109819bb0b8hselasky		 * with the first part of the datagram, and recv
109919bb0b8hselasky		 * generates the error WSAEMSGSIZE. For unreliable
110019bb0b8hselasky		 * protocols (for example, UDP) the excess data is
110119bb0b8hselasky		 * lost..."
110219bb0b8hselasky		 *
110319bb0b8hselasky		 * So if the message is bigger than the buffer
110419bb0b8hselasky		 * supplied to us, the excess data is discarded,
110519bb0b8hselasky		 * and we'll report an error.
110619bb0b8hselasky		 */
1107c2630c9philip		sock_geterror("recv()", errbuf, errbuflen);
110819bb0b8hselasky		return -1;
110919bb0b8hselasky	}
111019bb0b8hselasky#else /* _WIN32 */
111119bb0b8hselasky	/*
111219bb0b8hselasky	 * The Single UNIX Specification says that a recv() on
111319bb0b8hselasky	 * a socket for a message-oriented protocol will discard
111419bb0b8hselasky	 * the excess data.  It does *not* indicate that the
111519bb0b8hselasky	 * receive will fail with, for example, EMSGSIZE.
111619bb0b8hselasky	 *
111719bb0b8hselasky	 * Therefore, we use recvmsg(), which appears to be
111819bb0b8hselasky	 * the only way to get a "message truncated" indication
111919bb0b8hselasky	 * when receiving a message for a message-oriented
112019bb0b8hselasky	 * protocol.
112119bb0b8hselasky	 */
112219bb0b8hselasky	message.msg_name = NULL;	/* we don't care who it's from */
112319bb0b8hselasky	message.msg_namelen = 0;
112419bb0b8hselasky	iov.iov_base = buffer;
112519bb0b8hselasky	iov.iov_len = size;
112619bb0b8hselasky	message.msg_iov = &iov;
112719bb0b8hselasky	message.msg_iovlen = 1;
112819bb0b8hselasky#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
112919bb0b8hselasky	message.msg_control = NULL;	/* we don't care about control information */
113019bb0b8hselasky	message.msg_controllen = 0;
113119bb0b8hselasky#endif
113219bb0b8hselasky#ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
113319bb0b8hselasky	message.msg_flags = 0;
113419bb0b8hselasky#endif
113519bb0b8hselasky	nread = recvmsg(sock, &message, 0);
113619bb0b8hselasky	if (nread == -1)
113719bb0b8hselasky	{
113819bb0b8hselasky		if (errno == EINTR)
113919bb0b8hselasky			return -3;
1140c2630c9philip		sock_geterror("recv()", errbuf, errbuflen);
114119bb0b8hselasky		return -1;
114219bb0b8hselasky	}
114319bb0b8hselasky#ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
114419bb0b8hselasky	/*
114519bb0b8hselasky	 * XXX - Solaris supports this, but only if you ask for the
114619bb0b8hselasky	 * X/Open version of recvmsg(); should we use that, or will
114719bb0b8hselasky	 * that cause other problems?
114819bb0b8hselasky	 */
114919bb0b8hselasky	if (message.msg_flags & MSG_TRUNC)
115019bb0b8hselasky	{
115119bb0b8hselasky		/*
115219bb0b8hselasky		 * Message was bigger than the specified buffer size.
115319bb0b8hselasky		 *
115419bb0b8hselasky		 * Report this as an error, as the Microsoft documentation
115519bb0b8hselasky		 * implies we'd do in a similar case on Windows.
115619bb0b8hselasky		 */
115719bb0b8hselasky		pcap_snprintf(errbuf, errbuflen, "recv(): Message too long");
115819bb0b8hselasky		return -1;
115919bb0b8hselasky	}
116019bb0b8hselasky#endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
116119bb0b8hselasky#endif /* _WIN32 */
116219bb0b8hselasky
116319bb0b8hselasky	/*
116419bb0b8hselasky	 * The size we're reading fits in an int, so the return value
116519bb0b8hselasky	 * will fit in an int.
116619bb0b8hselasky	 */
116719bb0b8hselasky	return (int)nread;
116819bb0b8hselasky}
116919bb0b8hselasky
117019bb0b8hselasky/*
117194960e5delphij * \brief It discards N bytes that are currently waiting to be read on the current socket.
117294960e5delphij *
117394960e5delphij * This function is useful in case we receive a message we cannot understand (e.g.
117494960e5delphij * wrong version number when receiving a network packet), so that we have to discard all
117594960e5delphij * data before reading a new message.
117694960e5delphij *
117794960e5delphij * This function will read 'size' bytes from the socket and discard them.
117894960e5delphij * It defines an internal buffer in which data will be copied; however, in case
117994960e5delphij * this buffer is not large enough, it will cycle in order to read everything as well.
118094960e5delphij *
118194960e5delphij * \param sock: the connected socket currently opened.
118294960e5delphij *
118394960e5delphij * \param size: number of bytes that have to be discarded.
118494960e5delphij *
118594960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
118694960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
118794960e5delphij * It can be NULL; in this case the error cannot be printed.
118894960e5delphij *
118994960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
119094960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
119194960e5delphij *
119294960e5delphij * \return '0' if everything is fine, '-1' if some errors occurred.
119394960e5delphij * The error message is returned in the 'errbuf' variable.
119494960e5delphij */
119594960e5delphijint sock_discard(SOCKET sock, int size, char *errbuf, int errbuflen)
119694960e5delphij{
119794960e5delphij#define TEMP_BUF_SIZE 32768
119894960e5delphij
119994960e5delphij	char buffer[TEMP_BUF_SIZE];		/* network buffer, to be used when the message is discarded */
120094960e5delphij
120194960e5delphij	/*
120294960e5delphij	 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
120394960e5delphij	 * Our feeling is that a buffer if 32KB is enough for most of the application;
120494960e5delphij	 * in case this is not enough, the "while" loop discards the message by calling the
120594960e5delphij	 * sockrecv() several times.
120694960e5delphij	 * We do not want to create a bigger variable because this causes the program to exit on
120794960e5delphij	 * some platforms (e.g. BSD)
120894960e5delphij	 */
120994960e5delphij	while (size > TEMP_BUF_SIZE)
121094960e5delphij	{
121194960e5delphij		if (sock_recv(sock, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
121294960e5delphij			return -1;
121394960e5delphij
121494960e5delphij		size -= TEMP_BUF_SIZE;
121594960e5delphij	}
121694960e5delphij
121794960e5delphij	/*
121894960e5delphij	 * If there is still data to be discarded
121994960e5delphij	 * In this case, the data can fit into the temporary buffer
122094960e5delphij	 */
122194960e5delphij	if (size)
122294960e5delphij	{
122394960e5delphij		if (sock_recv(sock, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
122494960e5delphij			return -1;
122594960e5delphij	}
122694960e5delphij
122794960e5delphij	return 0;
122894960e5delphij}
122994960e5delphij
123094960e5delphij/*
123194960e5delphij * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
123294960e5delphij *
123394960e5delphij * This function is useful after an accept() call in order to check if the connecting
123494960e5delphij * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
123594960e5delphij * allowed host; this function checks the sockaddr_storage structure of the connecting host
123694960e5delphij * against this host list, and it returns '0' is the host is included in this list.
123794960e5delphij *
123894960e5delphij * \param hostlist: pointer to a string that contains the list of the allowed host.
123994960e5delphij *
124094960e5delphij * \param sep: a string that keeps the separators used between the hosts (for example the
124194960e5delphij * space character) in the host list.
124294960e5delphij *
124394960e5delphij * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
124494960e5delphij *
124594960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
124694960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
124794960e5delphij * It can be NULL; in this case the error cannot be printed.
124894960e5delphij *
124994960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
125094960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
125194960e5delphij *
125294960e5delphij * \return It returns:
125394960e5delphij * - '1' if the host list is empty
125494960e5delphij * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
125594960e5delphij * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
125694960e5delphij * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
125794960e5delphij */
125894960e5delphijint sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
125994960e5delphij{
126094960e5delphij	/* checks if the connecting host is among the ones allowed */
126194960e5delphij	if ((hostlist) && (hostlist[0]))
126294960e5delphij	{
126394960e5delphij		char *token;					/* temp, needed to separate items into the hostlist */
126494960e5delphij		struct addrinfo *addrinfo, *ai_next;
126594960e5delphij		char *temphostlist;
126694960e5delphij		char *lasts;
1267c2630c9philip		int getaddrinfo_failed = 0;
126894960e5delphij
126994960e5delphij		/*
127094960e5delphij		 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
127194960e5delphij		 * So, we have to create a new temporary string in which the original content is kept
127294960e5delphij		 */
127394960e5delphij		temphostlist = strdup(hostlist);
127494960e5delphij		if (temphostlist == NULL)
127594960e5delphij		{
127694960e5delphij			sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
127794960e5delphij			return -2;
127894960e5delphij		}
127994960e5delphij
128094960e5delphij		token = pcap_strtok_r(temphostlist, sep, &lasts);
128194960e5delphij
128294960e5delphij		/* it avoids a warning in the compilation ('addrinfo used but not initialized') */
128394960e5delphij		addrinfo = NULL;
128494960e5delphij
128594960e5delphij		while (token != NULL)
128694960e5delphij		{
128794960e5delphij			struct addrinfo hints;
128894960e5delphij			int retval;
128994960e5delphij
129094960e5delphij			addrinfo = NULL;
129194960e5delphij			memset(&hints, 0, sizeof(struct addrinfo));
129294960e5delphij			hints.ai_family = PF_UNSPEC;
129394960e5delphij			hints.ai_socktype = SOCK_STREAM;
129494960e5delphij
1295c2630c9philip			retval = getaddrinfo(token, NULL, &hints, &addrinfo);
129694960e5delphij			if (retval != 0)
129794960e5delphij			{
129894960e5delphij				if (errbuf)
1299c2630c9philip					get_gai_errstring(errbuf, errbuflen,
1300c2630c9philip					    "Allowed host list error: ",
1301c2630c9philip					    retval, token, NULL);
130294960e5delphij
1303c2630c9philip				/*
1304c2630c9philip				 * Note that at least one call to getaddrinfo()
1305c2630c9philip				 * failed.
1306c2630c9philip				 */
1307c2630c9philip				getaddrinfo_failed = 1;
130894960e5delphij
130994960e5delphij				/* Get next token */
131094960e5delphij				token = pcap_strtok_r(NULL, sep, &lasts);
131194960e5delphij				continue;
131294960e5delphij			}
131394960e5delphij
131494960e5delphij			/* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
131594960e5delphij			ai_next = addrinfo;
131694960e5delphij			while (ai_next)
131794960e5delphij			{
131894960e5delphij				if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
131994960e5delphij				{
132094960e5delphij					free(temphostlist);
132119bb0b8hselasky					freeaddrinfo(addrinfo);
132294960e5delphij					return 0;
132394960e5delphij				}
132494960e5delphij
132594960e5delphij				/*
132694960e5delphij				 * If we are here, it means that the current address does not matches
132794960e5delphij				 * Let's try with the next one in the header chain
132894960e5delphij				 */
132994960e5delphij				ai_next = ai_next->ai_next;
133094960e5delphij			}
133194960e5delphij
133294960e5delphij			freeaddrinfo(addrinfo);
133394960e5delphij			addrinfo = NULL;
133494960e5delphij
133594960e5delphij			/* Get next token */
133694960e5delphij			token = pcap_strtok_r(NULL, sep, &lasts);
133794960e5delphij		}
133894960e5delphij
133994960e5delphij		if (addrinfo)
134094960e5delphij		{
134194960e5delphij			freeaddrinfo(addrinfo);
134294960e5delphij			addrinfo = NULL;
134394960e5delphij		}
134494960e5delphij
134594960e5delphij		free(temphostlist);
1346c2630c9philip
1347c2630c9philip		if (getaddrinfo_failed) {
1348c2630c9philip			/*
1349c2630c9philip			 * At least one getaddrinfo() call failed;
1350c2630c9philip			 * treat that as an error, so rpcapd knows
1351c2630c9philip			 * that it should log it locally as well
1352c2630c9philip			 * as telling the client about it.
1353c2630c9philip			 */
1354c2630c9philip			return -2;
1355c2630c9philip		} else {
1356c2630c9philip			/*
1357c2630c9philip			 * All getaddrinfo() calls succeeded, but
1358c2630c9philip			 * the host wasn't in the list.
1359c2630c9philip			 */
1360c2630c9philip			if (errbuf)
1361c2630c9philip				pcap_snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1362c2630c9philip			return -1;
1363c2630c9philip		}
136494960e5delphij	}
136594960e5delphij
136694960e5delphij	/* No hostlist, so we have to return 'empty list' */
136794960e5delphij	return 1;
136894960e5delphij}
136994960e5delphij
137094960e5delphij/*
137194960e5delphij * \brief Compares two addresses contained into two sockaddr_storage structures.
137294960e5delphij *
137394960e5delphij * This function is useful to compare two addresses, given their internal representation,
137494960e5delphij * i.e. an sockaddr_storage structure.
137594960e5delphij *
137694960e5delphij * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
137794960e5delphij * sockaddr_in6, properly acsted in order to be compliant to the function interface.
137894960e5delphij *
137994960e5delphij * This function will return '0' if the two addresses matches, '-1' if not.
138094960e5delphij *
138194960e5delphij * \param first: a sockaddr_storage structure, (for example the one that is returned by an
138294960e5delphij * accept() call), containing the first address to compare.
138394960e5delphij *
138494960e5delphij * \param second: a sockaddr_storage structure containing the second address to compare.
138594960e5delphij *
138694960e5delphij * \return '0' if the addresses are equal, '-1' if they are different.
138794960e5delphij */
138894960e5delphijint sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
138994960e5delphij{
139094960e5delphij	if (first->ss_family == second->ss_family)
139194960e5delphij	{
139294960e5delphij		if (first->ss_family == AF_INET)
139394960e5delphij		{
139494960e5delphij			if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
139594960e5delphij				&(((struct sockaddr_in *) second)->sin_addr),
139694960e5delphij				sizeof(struct in_addr)) == 0)
139794960e5delphij				return 0;
139894960e5delphij		}
139994960e5delphij		else /* address family is AF_INET6 */
140094960e5delphij		{
140194960e5delphij			if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
140294960e5delphij				&(((struct sockaddr_in6 *) second)->sin6_addr),
140394960e5delphij				sizeof(struct in6_addr)) == 0)
140494960e5delphij				return 0;
140594960e5delphij		}
140694960e5delphij	}
140794960e5delphij
140894960e5delphij	return -1;
140994960e5delphij}
141094960e5delphij
141194960e5delphij/*
141294960e5delphij * \brief It gets the address/port the system picked for this socket (on connected sockets).
141394960e5delphij *
141494960e5delphij * It is used to return the address and port the server picked for our socket on the local machine.
141594960e5delphij * It works only on:
141694960e5delphij * - connected sockets
141794960e5delphij * - server sockets
141894960e5delphij *
141994960e5delphij * On unconnected client sockets it does not work because the system dynamically chooses a port
142094960e5delphij * only when the socket calls a send() call.
142194960e5delphij *
142294960e5delphij * \param sock: the connected socket currently opened.
142394960e5delphij *
142494960e5delphij * \param address: it contains the address that will be returned by the function. This buffer
142594960e5delphij * must be properly allocated by the user. The address can be either literal or numeric depending
142694960e5delphij * on the value of 'Flags'.
142794960e5delphij *
142894960e5delphij * \param addrlen: the length of the 'address' buffer.
142994960e5delphij *
143094960e5delphij * \param port: it contains the port that will be returned by the function. This buffer
143194960e5delphij * must be properly allocated by the user.
143294960e5delphij *
143394960e5delphij * \param portlen: the length of the 'port' buffer.
143494960e5delphij *
143594960e5delphij * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
143694960e5delphij * that determine if the resulting address must be in numeric / literal form, and so on.
143794960e5delphij *
143894960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
143994960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
144094960e5delphij * It can be NULL; in this case the error cannot be printed.
144194960e5delphij *
144294960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
144394960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
144494960e5delphij *
144594960e5delphij * \return It returns '-1' if this function succeeds, '0' otherwise.
144694960e5delphij * The address and port corresponding are returned back in the buffers 'address' and 'port'.
144794960e5delphij * In any case, the returned strings are '0' terminated.
144894960e5delphij *
144994960e5delphij * \warning If the socket is using a connectionless protocol, the address may not be available
145094960e5delphij * until I/O occurs on the socket.
145194960e5delphij */
145294960e5delphijint sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
145394960e5delphij{
145494960e5delphij	struct sockaddr_storage mysockaddr;
145594960e5delphij	socklen_t sockaddrlen;
145694960e5delphij
145794960e5delphij
145894960e5delphij	sockaddrlen = sizeof(struct sockaddr_storage);
145994960e5delphij
146094960e5delphij	if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
146194960e5delphij	{
1462c2630c9philip		sock_geterror("getsockname()", errbuf, errbuflen);
146394960e5delphij		return 0;
146494960e5delphij	}
146594960e5delphij
146619bb0b8hselasky	/* Returns the numeric address of the host that triggered the error */
146719bb0b8hselasky	return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
146894960e5delphij}
146994960e5delphij
147094960e5delphij/*
147194960e5delphij * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
147294960e5delphij *
147394960e5delphij * This function is basically an extended version of the inet_ntop(), which does not exist in
147494960e5delphij * Winsock because the same result can be obtained by using the getnameinfo().
147594960e5delphij * However, differently from inet_ntop(), this function is able to return also literal names
147694960e5delphij * (e.g. 'localhost') dependently from the 'Flags' parameter.
147794960e5delphij *
147894960e5delphij * The function accepts a sockaddr_storage variable (which can be returned by several functions
147994960e5delphij * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
148094960e5delphij * form. So, for instance, it is able to translate an hex address (stored in binary form) into
148194960e5delphij * a standard IPv6 address like "::1".
148294960e5delphij *
148394960e5delphij * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
148494960e5delphij * are the ones allowed in the standard getnameinfo() socket function.
148594960e5delphij *
148694960e5delphij * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
148794960e5delphij * need to be translated from network form into the presentation form. This structure must be
148894960e5delphij * zero-ed prior using it, and the address family field must be filled with the proper value.
148994960e5delphij * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
149094960e5delphij * calling this function.
149194960e5delphij *
149294960e5delphij * \param address: it contains the address that will be returned by the function. This buffer
149394960e5delphij * must be properly allocated by the user. The address can be either literal or numeric depending
149494960e5delphij * on the value of 'Flags'.
149594960e5delphij *
149694960e5delphij * \param addrlen: the length of the 'address' buffer.
149794960e5delphij *
149894960e5delphij * \param port: it contains the port that will be returned by the function. This buffer
149994960e5delphij * must be properly allocated by the user.
150094960e5delphij *
150194960e5delphij * \param portlen: the length of the 'port' buffer.
150294960e5delphij *
150394960e5delphij * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
150494960e5delphij * that determine if the resulting address must be in numeric / literal form, and so on.
150594960e5delphij *
150694960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
150794960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
150894960e5delphij * It can be NULL; in this case the error cannot be printed.
150994960e5delphij *
151094960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
151194960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
151294960e5delphij *
151394960e5delphij * \return It returns '-1' if this function succeeds, '0' otherwise.
151494960e5delphij * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
151594960e5delphij * and 'port'.
151694960e5delphij * In any case, the returned strings are '0' terminated.
151794960e5delphij */
151894960e5delphijint sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
151994960e5delphij{
152094960e5delphij	socklen_t sockaddrlen;
152194960e5delphij	int retval;					/* Variable that keeps the return value; */
152294960e5delphij
152394960e5delphij	retval = -1;
152494960e5delphij
152594960e5delphij#ifdef _WIN32
152694960e5delphij	if (sockaddr->ss_family == AF_INET)
152794960e5delphij		sockaddrlen = sizeof(struct sockaddr_in);
152894960e5delphij	else
152994960e5delphij		sockaddrlen = sizeof(struct sockaddr_in6);
153094960e5delphij#else
153194960e5delphij	sockaddrlen = sizeof(struct sockaddr_storage);
153294960e5delphij#endif
153394960e5delphij
153494960e5delphij	if ((flags & NI_NUMERICHOST) == 0)	/* Check that we want literal names */
153594960e5delphij	{
153694960e5delphij		if ((sockaddr->ss_family == AF_INET6) &&
153794960e5delphij			(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))
153894960e5delphij		{
153994960e5delphij			if (address)
1540c2630c9philip				pcap_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
154194960e5delphij			return retval;
154294960e5delphij		}
154394960e5delphij	}
154494960e5delphij
154594960e5delphij	if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
154694960e5delphij	{
154794960e5delphij		/* If the user wants to receive an error message */
154894960e5delphij		if (errbuf)
154994960e5delphij		{
1550c2630c9philip			sock_geterror("getnameinfo()", errbuf, errbuflen);
155194960e5delphij			errbuf[errbuflen - 1] = 0;
155294960e5delphij		}
155394960e5delphij
155494960e5delphij		if (address)
155594960e5delphij		{
1556c2630c9philip			pcap_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
155794960e5delphij			address[addrlen - 1] = 0;
155894960e5delphij		}
155994960e5delphij
156094960e5delphij		if (port)
156194960e5delphij		{
1562c2630c9philip			pcap_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
156394960e5delphij			port[portlen - 1] = 0;
156494960e5delphij		}
156594960e5delphij
156694960e5delphij		retval = 0;
156794960e5delphij	}
156894960e5delphij
156994960e5delphij	return retval;
157094960e5delphij}
157194960e5delphij
157294960e5delphij/*
157394960e5delphij * \brief It translates an address from the 'presentation' form into the 'network' form.
157494960e5delphij *
157594960e5delphij * This function basically replaces inet_pton(), which does not exist in Winsock because
157694960e5delphij * the same result can be obtained by using the getaddrinfo().
157794960e5delphij * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
157894960e5delphij * like in inet_pton() ) and a literal name (e.g. 'localhost').
157994960e5delphij *
158094960e5delphij * This function does the reverse job of sock_getascii_addrport().
158194960e5delphij *
158294960e5delphij * \param address: a zero-terminated string which contains the name you have to
158394960e5delphij * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
158494960e5delphij *
158594960e5delphij * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
158694960e5delphij * 'network' form of the requested address.
158794960e5delphij *
158894960e5delphij * \param addr_family: a constant which can assume the following values:
158994960e5delphij * - 'AF_INET' if we want to ping an IPv4 host
159094960e5delphij * - 'AF_INET6' if we want to ping an IPv6 host
159194960e5delphij * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
159294960e5delphij *
159394960e5delphij * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
159494960e5delphij * error message. This buffer has to be at least 'errbuflen' in length.
159594960e5delphij * It can be NULL; in this case the error cannot be printed.
159694960e5delphij *
159794960e5delphij * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
159894960e5delphij * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
159994960e5delphij *
160094960e5delphij * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
160194960e5delphij * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
160294960e5delphij * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
160394960e5delphij * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
160494960e5delphij * the content of the SockAddr parameter will be the address corresponding to the first mapping.
160594960e5delphij *
160694960e5delphij * \warning The sockaddr_storage structure MUST be allocated by the user.
160794960e5delphij */
160894960e5delphijint sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
160994960e5delphij{
161094960e5delphij	int retval;
161194960e5delphij	struct addrinfo *addrinfo;
161294960e5delphij	struct addrinfo hints;
161394960e5delphij
161494960e5delphij	memset(&hints, 0, sizeof(hints));
161594960e5delphij
161694960e5delphij	hints.ai_family = addr_family;
161794960e5delphij
161894960e5delphij	if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
161994960e5delphij		return 0;
162094960e5delphij
162194960e5delphij	if (addrinfo->ai_family == PF_INET)
162294960e5delphij		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
162394960e5delphij	else
162494960e5delphij		memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
162594960e5delphij
162694960e5delphij	if (addrinfo->ai_next != NULL)
162794960e5delphij	{
162894960e5delphij		freeaddrinfo(addrinfo);
162994960e5delphij
163094960e5delphij		if (errbuf)
163194960e5delphij			pcap_snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
163294960e5delphij		return -2;
163394960e5delphij	}
163494960e5delphij
163594960e5delphij	freeaddrinfo(addrinfo);
163694960e5delphij	return -1;
163794960e5delphij}
1638