2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
40 * The goal of this file is to provide a common set of primitives for socket
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.
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
56 #include <errno.h> /* for the errno variable */
57 #include <stdio.h> /* for the stderr file */
58 #include <stdlib.h> /* for malloc() and free() */
62 #define INT_MAX 2147483647
67 #include "sockutils.h"
68 #include "portability.h"
72 * Winsock initialization.
74 * Ask for WinSock 2.2.
76 #define WINSOCK_MAJOR_VERSION 2
77 #define WINSOCK_MINOR_VERSION 2
79 static int sockcount = 0; /*!< Variable that allows calling the WSAStartup() only one time */
82 /* Some minor differences between UNIX and Win32 */
84 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
87 /* Size of the buffer that has to keep error messages */
88 #define SOCK_ERRBUF_SIZE 1024
90 /* Constants; used in order to keep strings here */
91 #define SOCKET_NO_NAME_AVAILABLE "No name available"
92 #define SOCKET_NO_PORT_AVAILABLE "No port available"
93 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
96 * On UN*X, send() and recv() return ssize_t.
98 * On Windows, send() and recv() return an int.
100 * Wth MSVC, there *is* no ssize_t.
102 * With MinGW, there is an ssize_t type; it is either an int (32 bit)
103 * or a long long (64 bit).
105 * So, on Windows, if we don't have ssize_t defined, define it as an
106 * int, so we can use it, on all platforms, as the type of variables
107 * that hold the return values from send() and recv().
109 #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
113 /****************************************************
115 * Locally defined functions *
117 ****************************************************/
119 static int sock_ismcastaddr(const struct sockaddr *saddr);
121 /****************************************************
125 ****************************************************/
128 * Format an error message given an errno value (UN*X) or a WinSock error
131 void sock_fmterror(const char *caller, int errcode, char *errbuf, int errbuflen)
137 pcap_fmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
140 pcap_fmt_errmsg_for_errno(errbuf, errbuflen, errcode,
146 * \brief It retrieves the error message after an error occurred in the socket interface.
148 * This function is defined because of the different way errors are returned in UNIX
149 * and Win32. This function provides a consistent way to retrieve the error message
150 * (after a socket error occurred) on all the platforms.
152 * \param caller: a pointer to a user-allocated string which contains a message that has
153 * to be printed *before* the true error message. It could be, for example, 'this error
154 * comes from the recv() call at line 31'.
156 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
157 * error message. This buffer has to be at least 'errbuflen' in length.
158 * It can be NULL; in this case the error cannot be printed.
160 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
161 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
163 * \return No return values. The error message is returned in the 'string' parameter.
165 void sock_geterror(const char *caller, char *errbuf, int errbuflen)
168 sock_fmterror(caller, GetLastError(), errbuf, errbuflen);
170 sock_fmterror(caller, errno, errbuf, errbuflen);
175 * \brief This function initializes the socket mechanism if it hasn't
176 * already been initialized or reinitializes it after it has been
179 * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
180 * initialize Winsock.
182 * \param errbuf: a pointer to an user-allocated buffer that will contain
183 * the complete error message. This buffer has to be at least 'errbuflen'
184 * in length. It can be NULL; in this case no error message is supplied.
186 * \param errbuflen: length of the buffer that will contains the error.
187 * The error message cannot be larger than 'errbuflen - 1' because the
188 * last char is reserved for the string terminator.
190 * \return '0' if everything is fine, '-1' if some errors occurred. The
191 * error message is returned in the buffer pointed to by 'errbuf' variable.
194 int sock_init(char *errbuf, int errbuflen)
198 WSADATA wsaData; /* helper variable needed to initialize Winsock */
200 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
201 WINSOCK_MINOR_VERSION), &wsaData) != 0)
204 pcap_snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
216 int sock_init(char *errbuf _U_, int errbuflen _U_)
219 * Nothing to do on UN*Xes.
226 * \brief This function cleans up the socket mechanism if we have no
229 * On UN*Xes, it doesn't need to do anything; on Windows, it needs
230 * to clean up Winsock.
232 * \return No error values.
234 void sock_cleanup(void)
245 * \brief It checks if the sockaddr variable contains a multicast address.
247 * \return '0' if the address is multicast, '-1' if it is not.
249 static int sock_ismcastaddr(const struct sockaddr *saddr)
251 if (saddr->sa_family == PF_INET)
253 struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
254 if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
259 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
260 if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
266 * \brief It initializes a network connection both from the client and the server side.
268 * In case of a client socket, this function calls socket() and connect().
269 * In the meanwhile, it checks for any socket error.
270 * If an error occurs, it writes the error message into 'errbuf'.
272 * In case of a server socket, the function calls socket(), bind() and listen().
274 * This function is usually preceeded by the sock_initaddress().
276 * \param addrinfo: pointer to an addrinfo variable which will be used to
277 * open the socket and such. This variable is the one returned by the previous call to
278 * sock_initaddress().
280 * \param server: '1' if this is a server socket, '0' otherwise.
282 * \param nconn: number of the connections that are allowed to wait into the listen() call.
283 * This value has no meanings in case of a client socket.
285 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
286 * error message. This buffer has to be at least 'errbuflen' in length.
287 * It can be NULL; in this case the error cannot be printed.
289 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
290 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
292 * \return the socket that has been opened (that has to be used in the following sockets calls)
293 * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
294 * in the 'errbuf' variable.
296 SOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
299 #if defined(SO_NOSIGPIPE) || defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
303 sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
304 if (sock == INVALID_SOCKET)
306 sock_geterror("socket()", errbuf, errbuflen);
307 return INVALID_SOCKET;
311 * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
312 * have to deal with signals if the peer closes the connection,
313 * especially in client programs, which may not even be aware that
314 * they're sending to sockets.
317 if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
320 sock_geterror("setsockopt(SO_NOSIGPIPE)", errbuf, errbuflen);
322 return INVALID_SOCKET;
326 /* This is a server socket */
330 * Allow a new server to bind the socket after the old one
331 * exited, even if lingering sockets are still present.
333 * Don't treat an error as a failure.
336 (void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
337 (char *)&optval, sizeof (optval));
339 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
341 * Force the use of IPv6-only addresses.
343 * RFC 3493 indicates that you can support IPv4 on an
346 * https://tools.ietf.org/html/rfc3493#section-3.7
348 * and that this is the default behavior. This means
349 * that if we first create an IPv6 socket bound to the
350 * "any" address, it is, in effect, also bound to the
351 * IPv4 "any" address, so when we create an IPv4 socket
352 * and try to bind it to the IPv4 "any" address, it gets
355 * Not all network stacks support IPv4 on IPv6 sockets;
356 * pre-NT 6 Windows stacks don't support it, and the
357 * OpenBSD stack doesn't support it for security reasons
358 * (see the OpenBSD inet6(4) man page). Therefore, we
359 * don't want to rely on this behavior.
361 * So we try to disable it, using either the IPV6_V6ONLY
362 * option from RFC 3493:
364 * https://tools.ietf.org/html/rfc3493#section-5.3
366 * or the IPV6_BINDV6ONLY option from older UN*Xes.
369 /* For older systems */
370 #define IPV6_V6ONLY IPV6_BINDV6ONLY
371 #endif /* IPV6_V6ONLY */
372 if (addrinfo->ai_family == PF_INET6)
374 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
375 (char *)&on, sizeof (int)) == -1)
378 pcap_snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
380 return INVALID_SOCKET;
383 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
385 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
386 if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
388 sock_geterror("bind()", errbuf, errbuflen);
390 return INVALID_SOCKET;
393 if (addrinfo->ai_socktype == SOCK_STREAM)
394 if (listen(sock, nconn) == -1)
396 sock_geterror("listen()", errbuf, errbuflen);
398 return INVALID_SOCKET;
401 /* server side ended */
404 else /* we're the client */
406 struct addrinfo *tempaddrinfo;
410 tempaddrinfo = addrinfo;
412 bufspaceleft = errbuflen;
416 * We have to loop though all the addinfo returned.
417 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
418 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
423 if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
427 char SocketErrorMessage[SOCK_ERRBUF_SIZE];
430 * We have to retrieve the error message before any other socket call completes, otherwise
431 * the error message is lost
433 sock_geterror("Connect to socket failed",
434 SocketErrorMessage, sizeof(SocketErrorMessage));
436 /* Returns the numeric address of the host that triggered the error */
437 sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
439 pcap_snprintf(errbufptr, bufspaceleft,
440 "Is the server properly installed on %s? %s", TmpBuffer, SocketErrorMessage);
442 /* In case more then one 'connect' fails, we manage to keep all the error messages */
443 msglen = strlen(errbufptr);
445 errbufptr[msglen] = ' ';
446 errbufptr[msglen + 1] = 0;
448 bufspaceleft = bufspaceleft - (msglen + 1);
449 errbufptr += (msglen + 1);
451 tempaddrinfo = tempaddrinfo->ai_next;
458 * Check how we exit from the previous loop
459 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
461 if (tempaddrinfo == NULL)
464 return INVALID_SOCKET;
472 * \brief Closes the present (TCP and UDP) socket connection.
474 * This function sends a shutdown() on the socket in order to disable send() calls
475 * (while recv() ones are still allowed). Then, it closes the socket.
477 * \param sock: the socket identifier of the connection that has to be closed.
479 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
480 * error message. This buffer has to be at least 'errbuflen' in length.
481 * It can be NULL; in this case the error cannot be printed.
483 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
484 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
486 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
487 * in the 'errbuf' variable.
489 int sock_close(SOCKET sock, char *errbuf, int errbuflen)
492 * SHUT_WR: subsequent calls to the send function are disallowed.
493 * For TCP sockets, a FIN will be sent after all data is sent and
494 * acknowledged by the Server.
496 if (shutdown(sock, SHUT_WR))
498 sock_geterror("shutdown()", errbuf, errbuflen);
499 /* close the socket anyway */
509 * gai_errstring() has some problems:
511 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
512 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
513 * thread-safe, so an implementation might use a static buffer
514 * for unknown error codes;
515 * 3) the error message for the most likely error, EAI_NONAME, is
516 * truly horrible on several platforms ("nodename nor servname
517 * provided, or not known"? It's typically going to be "not
518 * known", not "oopsie, I passed null pointers for the host name
519 * and service name", not to mention they forgot the "neither");
521 * so we roll our own.
524 get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
525 const char *hostname, const char *portname)
527 char hostport[PCAP_ERRBUF_SIZE];
529 if (hostname != NULL && portname != NULL)
530 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s:%s",
532 else if (hostname != NULL)
533 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s",
535 else if (portname != NULL)
536 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, ":%s",
539 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
542 #ifdef EAI_ADDRFAMILY
544 pcap_snprintf(errbuf, errbuflen,
545 "%sAddress family for %s not supported",
551 pcap_snprintf(errbuf, errbuflen,
552 "%s%s could not be resolved at this time",
557 pcap_snprintf(errbuf, errbuflen,
558 "%sThe ai_flags parameter for looking up %s had an invalid value",
563 pcap_snprintf(errbuf, errbuflen,
564 "%sA non-recoverable error occurred when attempting to resolve %s",
569 pcap_snprintf(errbuf, errbuflen,
570 "%sThe address family for looking up %s was not recognized",
575 pcap_snprintf(errbuf, errbuflen,
576 "%sOut of memory trying to allocate storage when looking up %s",
581 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
583 * RFC 3493 has only EAI_NONAME.
585 * Some implementations define EAI_NODATA and EAI_NONAME
586 * to the same value, others don't. If EAI_NODATA is
587 * defined and isn't the same as EAI_NONAME, we handle
590 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
592 pcap_snprintf(errbuf, errbuflen,
593 "%sNo address associated with %s",
599 pcap_snprintf(errbuf, errbuflen,
600 "%sThe host name %s couldn't be resolved",
605 pcap_snprintf(errbuf, errbuflen,
606 "%sThe service value specified when looking up %s as not recognized for the socket type",
611 pcap_snprintf(errbuf, errbuflen,
612 "%sThe socket type specified when looking up %s as not recognized",
619 * Assumed to be UN*X.
621 pcap_snprintf(errbuf, errbuflen,
622 "%sAn error occurred when looking up %s: %s",
623 prefix, hostport, pcap_strerror(errno));
629 pcap_snprintf(errbuf, errbuflen,
630 "%sInvalid value for hints when looking up %s",
637 pcap_snprintf(errbuf, errbuflen,
638 "%sResolved protocol when looking up %s is unknown",
645 pcap_snprintf(errbuf, errbuflen,
646 "%sArgument buffer overflow when looking up %s",
652 pcap_snprintf(errbuf, errbuflen,
653 "%sgetaddrinfo() error %d when looking up %s",
654 prefix, err, hostport);
660 * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
662 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
663 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
664 * If an error occurs, it writes the error message into 'errbuf'.
666 * \param host: a pointer to a string identifying the host. It can be
667 * a host name, a numeric literal address, or NULL or "" (useful
668 * in case of a server socket which has to bind to all addresses).
670 * \param port: a pointer to a user-allocated buffer containing the network port to use.
672 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
673 * addrinfo structure appropriately.
675 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
676 * (passed by reference), which will be allocated by this function and returned back to the caller.
677 * This variable will be used in the next sockets calls.
679 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
680 * error message. This buffer has to be at least 'errbuflen' in length.
681 * It can be NULL; in this case the error cannot be printed.
683 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
684 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
686 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
687 * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
688 * returned into the addrinfo parameter.
690 * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
691 * it is no longer needed.
693 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
694 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
695 * the programmer to look at that function in order to set the 'hints' variable appropriately.
697 int sock_initaddress(const char *host, const char *port,
698 struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
702 retval = getaddrinfo(host, port, hints, addrinfo);
707 get_gai_errstring(errbuf, errbuflen, "", retval,
713 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
714 * addrinfo has more han one pointers
718 * This software only supports PF_INET and PF_INET6.
720 * XXX - should we just check that at least *one* address is
721 * either PF_INET or PF_INET6, and, when using the list,
722 * ignore all addresses that are neither? (What, no IPX
725 if (((*addrinfo)->ai_family != PF_INET) &&
726 ((*addrinfo)->ai_family != PF_INET6))
729 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
730 freeaddrinfo(*addrinfo);
736 * You can't do multicast (or broadcast) TCP.
738 if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
739 (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
742 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
743 freeaddrinfo(*addrinfo);
752 * \brief It sends the amount of data contained into 'buffer' on the given socket.
754 * This function basically calls the send() socket function and it checks that all
755 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
756 * it writes the error message into 'errbuf'.
757 * In case the socket buffer does not have enough space, it loops until all data
760 * \param socket: the connected socket currently opened.
762 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
764 * \param size: number of bytes that have to be sent.
766 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
767 * error message. This buffer has to be at least 'errbuflen' in length.
768 * It can be NULL; in this case the error cannot be printed.
770 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
771 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
773 * \return '0' if everything is fine, '-1' if an error other than
774 * "connection reset" or "peer has closed the receive side" occurred,
775 * '-2' if we got one of those errors.
776 * For errors, an error message is returned in the 'errbuf' variable.
778 int sock_send(SOCKET sock, const char *buffer, size_t size,
779 char *errbuf, int errbuflen)
788 pcap_snprintf(errbuf, errbuflen,
789 "Can't send more than %u bytes with sock_send",
794 remaining = (int)size;
799 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
800 * on errors on stream-oriented sockets when the other
801 * end breaks the connection.
802 * The EPIPE error is still returned.
804 nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
806 nsent = send(sock, buffer, remaining, 0);
812 * If the client closed the connection out from
813 * under us, there's no need to log that as an
819 errcode = GetLastError();
820 if (errcode == WSAECONNRESET ||
821 errcode == WSAECONNABORTED)
824 * WSAECONNABORTED appears to be the error
825 * returned in Winsock when you try to send
826 * on a connection where the peer has closed
831 sock_fmterror("send()", errcode, errbuf, errbuflen);
834 if (errcode == ECONNRESET || errcode == EPIPE)
837 * EPIPE is what's returned on UN*X when
838 * you try to send on a connection when
839 * the peer has closed the receive side.
843 sock_fmterror("send()", errcode, errbuf, errbuflen);
850 } while (remaining != 0);
856 * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
857 * and it checks for buffer overflows.
859 * This function basically copies 'size' bytes of data contained into 'buffer'
860 * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
861 * resulting buffer will not be larger than 'totsize'. Finally, it updates
862 * the 'offset' variable in order to point to the first empty location of the buffer.
864 * In case the function is called with 'checkonly' equal to 1, it does not copy
865 * the data into the buffer. It only checks for buffer overflows and it updates the
866 * 'offset' variable. This mode can be useful when the buffer already contains the
867 * data (maybe because the producer writes directly into the target buffer), so
868 * only the buffer overflow check has to be made.
869 * In this case, both 'buffer' and 'tempbuf' can be NULL values.
871 * This function is useful in case the userland application does not know immediately
872 * all the data it has to write into the socket. This function provides a way to create
873 * the "stream" step by step, appending the new data to the old one. Then, when all the
874 * data has been bufferized, the application can call the sock_send() function.
876 * \param buffer: a char pointer to a user-allocated buffer that keeps the data
877 * that has to be copied.
879 * \param size: number of bytes that have to be copied.
881 * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
884 * \param offset: an index into 'tempbuf' which keeps the location of its first
887 * \param totsize: total size of the buffer in which data is being copied.
889 * \param checkonly: '1' if we do not want to copy data into the buffer and we
890 * want just do a buffer ovreflow control, '0' if data has to be copied as well.
892 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
893 * error message. This buffer has to be at least 'errbuflen' in length.
894 * It can be NULL; in this case the error cannot be printed.
896 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
897 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
899 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
900 * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
901 * have the new string appended, and 'offset' will keep the length of that buffer.
902 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
904 * \warning This function assumes that the buffer in which data has to be stored is
905 * large 'totbuf' bytes.
907 * \warning In case of 'checkonly', be carefully to call this function *before* copying
908 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
910 int sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
912 if ((*offset + size) > totsize)
915 pcap_snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
920 memcpy(tempbuf + (*offset), buffer, size);
928 * \brief It waits on a connected socket and it manages to receive data.
930 * This function basically calls the recv() socket function and it checks that no
931 * error occurred. If that happens, it writes the error message into 'errbuf'.
933 * This function changes its behavior according to the 'receiveall' flag: if we
934 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
935 * data is arrived. Otherwise, it returns the data currently available.
937 * In case the socket does not have enough data available, it cycles on the recv()
938 * until the requested data (of size 'size') is arrived.
939 * In this case, it blocks until the number of bytes read is equal to 'size'.
941 * \param sock: the connected socket currently opened.
943 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
945 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
946 * that we are expecting to be read.
950 * SOCK_RECEIVALL_XXX:
952 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
953 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
954 * received (in case the socket does not have enough data available).
958 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
959 * and return an error on any subsequent read that returns 0;
960 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
962 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
963 * error message. This buffer has to be at least 'errbuflen' in length.
964 * It can be NULL; in this case the error cannot be printed.
966 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
967 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
969 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
970 * The error message is returned in the 'errbuf' variable.
973 int sock_recv(SOCKET sock, void *buffer, size_t size, int flags,
974 char *errbuf, int errbuflen)
988 pcap_snprintf(errbuf, errbuflen,
989 "Can't read more than %u bytes with sock_recv",
995 bufp = (char *) buffer;
996 remaining = (int) size;
999 * We don't use MSG_WAITALL because it's not supported in
1003 nread = recv(sock, bufp, remaining, 0);
1011 sock_geterror("recv()", errbuf, errbuflen);
1017 if ((flags & SOCK_EOF_IS_ERROR) ||
1018 (remaining != (int) size))
1021 * Either we've already read some data,
1022 * or we're always supposed to return
1027 pcap_snprintf(errbuf, errbuflen,
1028 "The other host terminated the connection.");
1037 * Do we want to read the amount requested, or just return
1040 if (!(flags & SOCK_RECEIVEALL_YES))
1043 * Just return what we got.
1057 * Receives a datagram from a socket.
1059 * Returns the size of the datagram on success or -1 on error.
1061 int sock_recv_dgram(SOCKET sock, void *buffer, size_t size,
1062 char *errbuf, int errbuflen)
1066 struct msghdr message;
1078 pcap_snprintf(errbuf, errbuflen,
1079 "Can't read more than %u bytes with sock_recv_dgram",
1086 * This should be a datagram socket, so we should get the
1087 * entire datagram in one recv() or recvmsg() call, and
1088 * don't need to loop.
1091 nread = recv(sock, buffer, size, 0);
1092 if (nread == SOCKET_ERROR)
1095 * To quote the MSDN documentation for recv(),
1096 * "If the datagram or message is larger than
1097 * the buffer specified, the buffer is filled
1098 * with the first part of the datagram, and recv
1099 * generates the error WSAEMSGSIZE. For unreliable
1100 * protocols (for example, UDP) the excess data is
1103 * So if the message is bigger than the buffer
1104 * supplied to us, the excess data is discarded,
1105 * and we'll report an error.
1107 sock_geterror("recv()", errbuf, errbuflen);
1112 * The Single UNIX Specification says that a recv() on
1113 * a socket for a message-oriented protocol will discard
1114 * the excess data. It does *not* indicate that the
1115 * receive will fail with, for example, EMSGSIZE.
1117 * Therefore, we use recvmsg(), which appears to be
1118 * the only way to get a "message truncated" indication
1119 * when receiving a message for a message-oriented
1122 message.msg_name = NULL; /* we don't care who it's from */
1123 message.msg_namelen = 0;
1124 iov.iov_base = buffer;
1126 message.msg_iov = &iov;
1127 message.msg_iovlen = 1;
1128 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1129 message.msg_control = NULL; /* we don't care about control information */
1130 message.msg_controllen = 0;
1132 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1133 message.msg_flags = 0;
1135 nread = recvmsg(sock, &message, 0);
1140 sock_geterror("recv()", errbuf, errbuflen);
1143 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1145 * XXX - Solaris supports this, but only if you ask for the
1146 * X/Open version of recvmsg(); should we use that, or will
1147 * that cause other problems?
1149 if (message.msg_flags & MSG_TRUNC)
1152 * Message was bigger than the specified buffer size.
1154 * Report this as an error, as the Microsoft documentation
1155 * implies we'd do in a similar case on Windows.
1157 pcap_snprintf(errbuf, errbuflen, "recv(): Message too long");
1160 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1164 * The size we're reading fits in an int, so the return value
1165 * will fit in an int.
1171 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1173 * This function is useful in case we receive a message we cannot understand (e.g.
1174 * wrong version number when receiving a network packet), so that we have to discard all
1175 * data before reading a new message.
1177 * This function will read 'size' bytes from the socket and discard them.
1178 * It defines an internal buffer in which data will be copied; however, in case
1179 * this buffer is not large enough, it will cycle in order to read everything as well.
1181 * \param sock: the connected socket currently opened.
1183 * \param size: number of bytes that have to be discarded.
1185 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1186 * error message. This buffer has to be at least 'errbuflen' in length.
1187 * It can be NULL; in this case the error cannot be printed.
1189 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1190 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1192 * \return '0' if everything is fine, '-1' if some errors occurred.
1193 * The error message is returned in the 'errbuf' variable.
1195 int sock_discard(SOCKET sock, int size, char *errbuf, int errbuflen)
1197 #define TEMP_BUF_SIZE 32768
1199 char buffer[TEMP_BUF_SIZE]; /* network buffer, to be used when the message is discarded */
1202 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1203 * Our feeling is that a buffer if 32KB is enough for most of the application;
1204 * in case this is not enough, the "while" loop discards the message by calling the
1205 * sockrecv() several times.
1206 * We do not want to create a bigger variable because this causes the program to exit on
1207 * some platforms (e.g. BSD)
1209 while (size > TEMP_BUF_SIZE)
1211 if (sock_recv(sock, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1214 size -= TEMP_BUF_SIZE;
1218 * If there is still data to be discarded
1219 * In this case, the data can fit into the temporary buffer
1223 if (sock_recv(sock, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1231 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1233 * This function is useful after an accept() call in order to check if the connecting
1234 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1235 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1236 * against this host list, and it returns '0' is the host is included in this list.
1238 * \param hostlist: pointer to a string that contains the list of the allowed host.
1240 * \param sep: a string that keeps the separators used between the hosts (for example the
1241 * space character) in the host list.
1243 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1245 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1246 * error message. This buffer has to be at least 'errbuflen' in length.
1247 * It can be NULL; in this case the error cannot be printed.
1249 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1250 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1252 * \return It returns:
1253 * - '1' if the host list is empty
1254 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1255 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1256 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1258 int sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
1260 /* checks if the connecting host is among the ones allowed */
1261 if ((hostlist) && (hostlist[0]))
1263 char *token; /* temp, needed to separate items into the hostlist */
1264 struct addrinfo *addrinfo, *ai_next;
1267 int getaddrinfo_failed = 0;
1270 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1271 * So, we have to create a new temporary string in which the original content is kept
1273 temphostlist = strdup(hostlist);
1274 if (temphostlist == NULL)
1276 sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
1280 token = pcap_strtok_r(temphostlist, sep, &lasts);
1282 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1285 while (token != NULL)
1287 struct addrinfo hints;
1291 memset(&hints, 0, sizeof(struct addrinfo));
1292 hints.ai_family = PF_UNSPEC;
1293 hints.ai_socktype = SOCK_STREAM;
1295 retval = getaddrinfo(token, NULL, &hints, &addrinfo);
1299 get_gai_errstring(errbuf, errbuflen,
1300 "Allowed host list error: ",
1301 retval, token, NULL);
1304 * Note that at least one call to getaddrinfo()
1307 getaddrinfo_failed = 1;
1309 /* Get next token */
1310 token = pcap_strtok_r(NULL, sep, &lasts);
1314 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1318 if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1321 freeaddrinfo(addrinfo);
1326 * If we are here, it means that the current address does not matches
1327 * Let's try with the next one in the header chain
1329 ai_next = ai_next->ai_next;
1332 freeaddrinfo(addrinfo);
1335 /* Get next token */
1336 token = pcap_strtok_r(NULL, sep, &lasts);
1341 freeaddrinfo(addrinfo);
1347 if (getaddrinfo_failed) {
1349 * At least one getaddrinfo() call failed;
1350 * treat that as an error, so rpcapd knows
1351 * that it should log it locally as well
1352 * as telling the client about it.
1357 * All getaddrinfo() calls succeeded, but
1358 * the host wasn't in the list.
1361 pcap_snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1366 /* No hostlist, so we have to return 'empty list' */
1371 * \brief Compares two addresses contained into two sockaddr_storage structures.
1373 * This function is useful to compare two addresses, given their internal representation,
1374 * i.e. an sockaddr_storage structure.
1376 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1377 * sockaddr_in6, properly acsted in order to be compliant to the function interface.
1379 * This function will return '0' if the two addresses matches, '-1' if not.
1381 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1382 * accept() call), containing the first address to compare.
1384 * \param second: a sockaddr_storage structure containing the second address to compare.
1386 * \return '0' if the addresses are equal, '-1' if they are different.
1388 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
1390 if (first->ss_family == second->ss_family)
1392 if (first->ss_family == AF_INET)
1394 if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
1395 &(((struct sockaddr_in *) second)->sin_addr),
1396 sizeof(struct in_addr)) == 0)
1399 else /* address family is AF_INET6 */
1401 if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
1402 &(((struct sockaddr_in6 *) second)->sin6_addr),
1403 sizeof(struct in6_addr)) == 0)
1412 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1414 * It is used to return the address and port the server picked for our socket on the local machine.
1416 * - connected sockets
1419 * On unconnected client sockets it does not work because the system dynamically chooses a port
1420 * only when the socket calls a send() call.
1422 * \param sock: the connected socket currently opened.
1424 * \param address: it contains the address that will be returned by the function. This buffer
1425 * must be properly allocated by the user. The address can be either literal or numeric depending
1426 * on the value of 'Flags'.
1428 * \param addrlen: the length of the 'address' buffer.
1430 * \param port: it contains the port that will be returned by the function. This buffer
1431 * must be properly allocated by the user.
1433 * \param portlen: the length of the 'port' buffer.
1435 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1436 * that determine if the resulting address must be in numeric / literal form, and so on.
1438 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1439 * error message. This buffer has to be at least 'errbuflen' in length.
1440 * It can be NULL; in this case the error cannot be printed.
1442 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1443 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1445 * \return It returns '-1' if this function succeeds, '0' otherwise.
1446 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1447 * In any case, the returned strings are '0' terminated.
1449 * \warning If the socket is using a connectionless protocol, the address may not be available
1450 * until I/O occurs on the socket.
1452 int sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1454 struct sockaddr_storage mysockaddr;
1455 socklen_t sockaddrlen;
1458 sockaddrlen = sizeof(struct sockaddr_storage);
1460 if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1462 sock_geterror("getsockname()", errbuf, errbuflen);
1466 /* Returns the numeric address of the host that triggered the error */
1467 return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1471 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1473 * This function is basically an extended version of the inet_ntop(), which does not exist in
1474 * Winsock because the same result can be obtained by using the getnameinfo().
1475 * However, differently from inet_ntop(), this function is able to return also literal names
1476 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1478 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1479 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1480 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1481 * a standard IPv6 address like "::1".
1483 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1484 * are the ones allowed in the standard getnameinfo() socket function.
1486 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1487 * need to be translated from network form into the presentation form. This structure must be
1488 * zero-ed prior using it, and the address family field must be filled with the proper value.
1489 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1490 * calling this function.
1492 * \param address: it contains the address that will be returned by the function. This buffer
1493 * must be properly allocated by the user. The address can be either literal or numeric depending
1494 * on the value of 'Flags'.
1496 * \param addrlen: the length of the 'address' buffer.
1498 * \param port: it contains the port that will be returned by the function. This buffer
1499 * must be properly allocated by the user.
1501 * \param portlen: the length of the 'port' buffer.
1503 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1504 * that determine if the resulting address must be in numeric / literal form, and so on.
1506 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1507 * error message. This buffer has to be at least 'errbuflen' in length.
1508 * It can be NULL; in this case the error cannot be printed.
1510 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1511 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1513 * \return It returns '-1' if this function succeeds, '0' otherwise.
1514 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1516 * In any case, the returned strings are '0' terminated.
1518 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1520 socklen_t sockaddrlen;
1521 int retval; /* Variable that keeps the return value; */
1526 if (sockaddr->ss_family == AF_INET)
1527 sockaddrlen = sizeof(struct sockaddr_in);
1529 sockaddrlen = sizeof(struct sockaddr_in6);
1531 sockaddrlen = sizeof(struct sockaddr_storage);
1534 if ((flags & NI_NUMERICHOST) == 0) /* Check that we want literal names */
1536 if ((sockaddr->ss_family == AF_INET6) &&
1537 (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))
1540 pcap_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
1545 if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
1547 /* If the user wants to receive an error message */
1550 sock_geterror("getnameinfo()", errbuf, errbuflen);
1551 errbuf[errbuflen - 1] = 0;
1556 pcap_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
1557 address[addrlen - 1] = 0;
1562 pcap_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
1563 port[portlen - 1] = 0;
1573 * \brief It translates an address from the 'presentation' form into the 'network' form.
1575 * This function basically replaces inet_pton(), which does not exist in Winsock because
1576 * the same result can be obtained by using the getaddrinfo().
1577 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
1578 * like in inet_pton() ) and a literal name (e.g. 'localhost').
1580 * This function does the reverse job of sock_getascii_addrport().
1582 * \param address: a zero-terminated string which contains the name you have to
1583 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
1585 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
1586 * 'network' form of the requested address.
1588 * \param addr_family: a constant which can assume the following values:
1589 * - 'AF_INET' if we want to ping an IPv4 host
1590 * - 'AF_INET6' if we want to ping an IPv6 host
1591 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
1593 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1594 * error message. This buffer has to be at least 'errbuflen' in length.
1595 * It can be NULL; in this case the error cannot be printed.
1597 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1598 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1600 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
1601 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
1602 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
1603 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
1604 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
1606 * \warning The sockaddr_storage structure MUST be allocated by the user.
1608 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
1611 struct addrinfo *addrinfo;
1612 struct addrinfo hints;
1614 memset(&hints, 0, sizeof(hints));
1616 hints.ai_family = addr_family;
1618 if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
1621 if (addrinfo->ai_family == PF_INET)
1622 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
1624 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
1626 if (addrinfo->ai_next != NULL)
1628 freeaddrinfo(addrinfo);
1631 pcap_snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
1635 freeaddrinfo(addrinfo);