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() */
59 #include <limits.h> /* for INT_MAX */
63 #include "sockutils.h"
64 #include "portability.h"
68 * Winsock initialization.
70 * Ask for Winsock 2.2.
72 #define WINSOCK_MAJOR_VERSION 2
73 #define WINSOCK_MINOR_VERSION 2
75 static int sockcount
= 0; /*!< Variable that allows calling the WSAStartup() only one time */
78 /* Some minor differences between UNIX and Win32 */
80 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
83 /* Size of the buffer that has to keep error messages */
84 #define SOCK_ERRBUF_SIZE 1024
86 /* Constants; used in order to keep strings here */
87 #define SOCKET_NO_NAME_AVAILABLE "No name available"
88 #define SOCKET_NO_PORT_AVAILABLE "No port available"
89 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
92 * On UN*X, send() and recv() return ssize_t.
94 * On Windows, send() and recv() return an int.
96 * With MSVC, there *is* no ssize_t.
98 * With MinGW, there is an ssize_t type; it is either an int (32 bit)
99 * or a long long (64 bit).
101 * So, on Windows, if we don't have ssize_t defined, define it as an
102 * int, so we can use it, on all platforms, as the type of variables
103 * that hold the return values from send() and recv().
105 #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
109 /****************************************************
111 * Locally defined functions *
113 ****************************************************/
115 static int sock_ismcastaddr(const struct sockaddr
*saddr
);
117 /****************************************************
121 ****************************************************/
123 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
124 const uint8_t *fuzzBuffer
;
128 void sock_initfuzz(const uint8_t *Data
, size_t Size
) {
134 static int fuzz_recv(char *bufp
, int remaining
) {
135 if (remaining
> fuzzSize
- fuzzPos
) {
136 remaining
= fuzzSize
- fuzzPos
;
138 if (fuzzPos
< fuzzSize
) {
139 memcpy(bufp
, fuzzBuffer
+ fuzzPos
, remaining
);
141 fuzzPos
+= remaining
;
146 int sock_geterrcode(void)
149 return GetLastError();
156 * Format an error message given an errno value (UN*X) or a Winsock error
159 void sock_vfmterrmsg(char *errbuf
, size_t errbuflen
, int errcode
,
160 const char *fmt
, va_list ap
)
166 pcapint_vfmt_errmsg_for_win32_err(errbuf
, errbuflen
, errcode
,
169 pcapint_vfmt_errmsg_for_errno(errbuf
, errbuflen
, errcode
,
174 void sock_fmterrmsg(char *errbuf
, size_t errbuflen
, int errcode
,
175 const char *fmt
, ...)
180 sock_vfmterrmsg(errbuf
, errbuflen
, errcode
, fmt
, ap
);
185 * Format an error message for the last socket error.
187 void sock_geterrmsg(char *errbuf
, size_t errbuflen
, const char *fmt
, ...)
192 sock_vfmterrmsg(errbuf
, errbuflen
, sock_geterrcode(), fmt
, ap
);
199 * These are sorted by how likely they are to be the "underlying" problem,
200 * so that lower-rated errors for a given address in a given family
201 * should not overwrite higher-rated errors for another address in that
202 * family, and higher-rated errors should overwrite lower-rated errors.
205 SOCK_CONNERR
, /* connection error */
206 SOCK_HOSTERR
, /* host error */
207 SOCK_NETERR
, /* network error */
208 SOCK_AFNOTSUPERR
, /* address family not supported */
209 SOCK_UNKNOWNERR
, /* unknown error */
210 SOCK_NOERR
/* no error */
213 static sock_errtype
sock_geterrtype(int errcode
)
219 case WSAECONNABORTED
:
220 case WSAECONNREFUSED
:
227 * Connection error; this means the problem is probably
228 * that there's no server set up on the remote machine,
229 * or that it is set up, but it's IPv4-only or IPv6-only
230 * and we're trying the wrong address family.
232 * These overwrite all other errors, as they indicate
233 * that, even if something else went wrong in another
234 * attempt, this probably wouldn't work even if the
235 * other problems were fixed.
237 return (SOCK_CONNERR
);
243 case WSAEHOSTUNREACH
:
251 * Network errors that could be IPv4-specific, IPv6-
252 * specific, or present with both.
254 * Don't overwrite connection errors, but overwrite
257 return (SOCK_HOSTERR
);
267 * Network error; this means we don't know whether
268 * there's a server set up on the remote machine,
269 * and we don't have a reason to believe that IPv6
270 * any worse or better than IPv4.
272 * These probably indicate a local failure, e.g.
273 * an interface is down.
275 * Don't overwrite connection errors or host errors,
276 * but overwrite everything else.
278 return (SOCK_NETERR
);
281 case WSAEAFNOSUPPORT
:
286 * "Address family not supported" probably means
287 * "No soup^WIPv6 for you!".
289 * Don't overwrite connection errors, host errors, or
290 * network errors (none of which we should get for this
291 * address family if it's not supported), but overwrite
294 return (SOCK_AFNOTSUPERR
);
300 * Don't overwrite any errors.
302 return (SOCK_UNKNOWNERR
);
307 * \brief This function initializes the socket mechanism if it hasn't
308 * already been initialized or reinitializes it after it has been
311 * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
312 * initialize Winsock.
314 * \param errbuf: a pointer to an user-allocated buffer that will contain
315 * the complete error message. This buffer has to be at least 'errbuflen'
316 * in length. It can be NULL; in this case no error message is supplied.
318 * \param errbuflen: length of the buffer that will contains the error.
319 * The error message cannot be larger than 'errbuflen - 1' because the
320 * last char is reserved for the string terminator.
322 * \return '0' if everything is fine, '-1' if some errors occurred. The
323 * error message is returned in the buffer pointed to by 'errbuf' variable.
326 int sock_init(char *errbuf
, int errbuflen
)
330 WSADATA wsaData
; /* helper variable needed to initialize Winsock */
332 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION
,
333 WINSOCK_MINOR_VERSION
), &wsaData
) != 0)
336 snprintf(errbuf
, errbuflen
, "Failed to initialize Winsock\n");
348 int sock_init(char *errbuf _U_
, int errbuflen _U_
)
351 * Nothing to do on UN*Xes.
358 * \brief This function cleans up the socket mechanism if we have no
361 * On UN*Xes, it doesn't need to do anything; on Windows, it needs
362 * to clean up Winsock.
364 * \return No error values.
366 void sock_cleanup(void)
377 * \brief It checks if the sockaddr variable contains a multicast address.
379 * \return '0' if the address is multicast, '-1' if it is not.
381 static int sock_ismcastaddr(const struct sockaddr
*saddr
)
383 if (saddr
->sa_family
== PF_INET
)
385 struct sockaddr_in
*saddr4
= (struct sockaddr_in
*) saddr
;
386 if (IN_MULTICAST(ntohl(saddr4
->sin_addr
.s_addr
))) return 0;
391 struct sockaddr_in6
*saddr6
= (struct sockaddr_in6
*) saddr
;
392 if (IN6_IS_ADDR_MULTICAST(&saddr6
->sin6_addr
)) return 0;
398 struct addrinfo
*info
;
400 sock_errtype errtype
;
404 * Sort by IPv4 address vs. IPv6 address.
406 static int compare_addrs_to_try_by_address_family(const void *a
, const void *b
)
408 const struct addr_status
*addr_a
= (const struct addr_status
*)a
;
409 const struct addr_status
*addr_b
= (const struct addr_status
*)b
;
411 return addr_a
->info
->ai_family
- addr_b
->info
->ai_family
;
415 * Sort by error type and, within a given error type, by error code and,
416 * within a given error code, by IPv4 address vs. IPv6 address.
418 static int compare_addrs_to_try_by_status(const void *a
, const void *b
)
420 const struct addr_status
*addr_a
= (const struct addr_status
*)a
;
421 const struct addr_status
*addr_b
= (const struct addr_status
*)b
;
423 if (addr_a
->errtype
== addr_b
->errtype
)
425 if (addr_a
->errcode
== addr_b
->errcode
)
427 return addr_a
->info
->ai_family
- addr_b
->info
->ai_family
;
429 return addr_a
->errcode
- addr_b
->errcode
;
432 return addr_a
->errtype
- addr_b
->errtype
;
435 static PCAP_SOCKET
sock_create_socket(struct addrinfo
*addrinfo
, char *errbuf
,
443 sock
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
,
444 addrinfo
->ai_protocol
);
445 if (sock
== INVALID_SOCKET
)
447 sock_geterrmsg(errbuf
, errbuflen
, "socket() failed");
448 return INVALID_SOCKET
;
452 * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
453 * have to deal with signals if the peer closes the connection,
454 * especially in client programs, which may not even be aware that
455 * they're sending to sockets.
458 if (setsockopt(sock
, SOL_SOCKET
, SO_NOSIGPIPE
, (char *)&on
,
461 sock_geterrmsg(errbuf
, errbuflen
,
462 "setsockopt(SO_NOSIGPIPE) failed");
464 return INVALID_SOCKET
;
471 * \brief It initializes a network connection both from the client and the server side.
473 * In case of a client socket, this function calls socket() and connect().
474 * In the meanwhile, it checks for any socket error.
475 * If an error occurs, it writes the error message into 'errbuf'.
477 * In case of a server socket, the function calls socket(), bind() and listen().
479 * This function is usually preceded by the sock_initaddress().
481 * \param host: for client sockets, the host name to which we're trying
484 * \param addrinfo: pointer to an addrinfo variable which will be used to
485 * open the socket and such. This variable is the one returned by the previous call to
486 * sock_initaddress().
488 * \param server: '1' if this is a server socket, '0' otherwise.
490 * \param nconn: number of the connections that are allowed to wait into the listen() call.
491 * This value has no meanings in case of a client socket.
493 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
494 * error message. This buffer has to be at least 'errbuflen' in length.
495 * It can be NULL; in this case the error cannot be printed.
497 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
498 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
500 * \return the socket that has been opened (that has to be used in the following sockets calls)
501 * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
502 * in the 'errbuf' variable.
504 PCAP_SOCKET
sock_open(const char *host
, struct addrinfo
*addrinfo
,
505 int server
, int nconn
, char *errbuf
, int errbuflen
)
509 /* This is a server socket */
515 * Attempt to create the socket.
517 sock
= sock_create_socket(addrinfo
, errbuf
, errbuflen
);
518 if (sock
== INVALID_SOCKET
)
520 return INVALID_SOCKET
;
524 * Allow a new server to bind the socket after the old one
525 * exited, even if lingering sockets are still present.
527 * Don't treat an error as a failure.
530 (void)setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
,
531 (char *)&on
, sizeof (on
));
533 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
535 * Force the use of IPv6-only addresses.
537 * RFC 3493 indicates that you can support IPv4 on an
540 * https://tools.ietf.org/html/rfc3493#section-3.7
542 * and that this is the default behavior. This means
543 * that if we first create an IPv6 socket bound to the
544 * "any" address, it is, in effect, also bound to the
545 * IPv4 "any" address, so when we create an IPv4 socket
546 * and try to bind it to the IPv4 "any" address, it gets
549 * Not all network stacks support IPv4 on IPv6 sockets;
550 * pre-NT 6 Windows stacks don't support it, and the
551 * OpenBSD stack doesn't support it for security reasons
552 * (see the OpenBSD inet6(4) man page). Therefore, we
553 * don't want to rely on this behavior.
555 * So we try to disable it, using either the IPV6_V6ONLY
556 * option from RFC 3493:
558 * https://tools.ietf.org/html/rfc3493#section-5.3
560 * or the IPV6_BINDV6ONLY option from older UN*Xes.
563 /* For older systems */
564 #define IPV6_V6ONLY IPV6_BINDV6ONLY
565 #endif /* IPV6_V6ONLY */
566 if (addrinfo
->ai_family
== PF_INET6
)
569 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
,
570 (char *)&on
, sizeof (int)) == -1)
573 snprintf(errbuf
, errbuflen
, "setsockopt(IPV6_V6ONLY)");
575 return INVALID_SOCKET
;
578 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
580 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
581 if (bind(sock
, addrinfo
->ai_addr
, (int) addrinfo
->ai_addrlen
) != 0)
583 sock_geterrmsg(errbuf
, errbuflen
, "bind() failed");
585 return INVALID_SOCKET
;
588 if (addrinfo
->ai_socktype
== SOCK_STREAM
)
589 if (listen(sock
, nconn
) == -1)
591 sock_geterrmsg(errbuf
, errbuflen
,
594 return INVALID_SOCKET
;
597 /* server side ended */
600 else /* we're the client */
602 struct addr_status
*addrs_to_try
;
603 struct addrinfo
*tempaddrinfo
;
606 int current_af
= AF_UNSPEC
;
609 * We have to loop though all the addrinfos returned.
610 * For instance, we can have both IPv6 and IPv4 addresses,
611 * but the service we're trying to connect to is unavailable
612 * in IPv6, so we have to try in IPv4 as well.
614 * How many addrinfos do we have?
617 for (tempaddrinfo
= addrinfo
; tempaddrinfo
!= NULL
;
618 tempaddrinfo
= tempaddrinfo
->ai_next
)
623 if (numaddrinfos
== 0)
625 snprintf(errbuf
, errbuflen
,
626 "There are no addresses in the address list");
627 return INVALID_SOCKET
;
631 * Allocate an array of struct addr_status and fill it in.
633 addrs_to_try
= calloc(numaddrinfos
, sizeof *addrs_to_try
);
634 if (addrs_to_try
== NULL
)
636 snprintf(errbuf
, errbuflen
,
637 "Out of memory connecting to %s", host
);
638 return INVALID_SOCKET
;
641 for (tempaddrinfo
= addrinfo
, i
= 0; tempaddrinfo
!= NULL
;
642 tempaddrinfo
= tempaddrinfo
->ai_next
, i
++)
644 addrs_to_try
[i
].info
= tempaddrinfo
;
645 addrs_to_try
[i
].errcode
= 0;
646 addrs_to_try
[i
].errtype
= SOCK_NOERR
;
650 * Sort the structures to put the IPv4 addresses before the
651 * IPv6 addresses; we will have to create an IPv4 socket
652 * for the IPv4 addresses and an IPv6 socket for the IPv6
653 * addresses (one of the arguments to socket() is the
654 * address/protocol family to use, and IPv4 and IPv6 are
655 * separate address/protocol families).
657 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
658 compare_addrs_to_try_by_address_family
);
660 /* Start out with no socket. */
661 sock
= INVALID_SOCKET
;
666 for (i
= 0; i
< numaddrinfos
; i
++)
668 tempaddrinfo
= addrs_to_try
[i
].info
;
669 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
673 * If we have a socket, but it's for a
674 * different address family, close it.
676 if (sock
!= INVALID_SOCKET
&&
677 current_af
!= tempaddrinfo
->ai_family
)
680 sock
= INVALID_SOCKET
;
684 * If we don't have a socket, open one
685 * for *this* address's address family.
687 if (sock
== INVALID_SOCKET
)
689 sock
= sock_create_socket(tempaddrinfo
,
691 if (sock
== INVALID_SOCKET
)
694 return INVALID_SOCKET
;
697 if (connect(sock
, tempaddrinfo
->ai_addr
, (int) tempaddrinfo
->ai_addrlen
) == -1)
699 addrs_to_try
[i
].errcode
= sock_geterrcode();
700 addrs_to_try
[i
].errtype
=
701 sock_geterrtype(addrs_to_try
[i
].errcode
);
708 * Check how we exited from the previous loop.
709 * If tempaddrinfo is equal to NULL, it means that all
710 * the connect() attempts failed. Construct an
713 if (i
== numaddrinfos
)
715 int same_error_for_all
;
721 * Sort the statuses to group together categories
722 * of errors, errors within categories, and
723 * address families within error sets.
725 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
726 compare_addrs_to_try_by_status
);
729 * Are all the errors the same?
731 same_error_for_all
= 1;
732 first_error
= addrs_to_try
[0].errcode
;
733 for (i
= 1; i
< numaddrinfos
; i
++)
735 if (addrs_to_try
[i
].errcode
!= first_error
)
737 same_error_for_all
= 0;
742 if (same_error_for_all
) {
744 * Yes. No need to show the IP
747 if (addrs_to_try
[0].errtype
== SOCK_CONNERR
) {
749 * Connection error; note that
750 * the daemon might not be set
751 * up correctly, or set up at all.
753 sock_fmterrmsg(errbuf
, errbuflen
,
754 addrs_to_try
[0].errcode
,
755 "Is the server properly installed? Cannot connect to %s",
758 sock_fmterrmsg(errbuf
, errbuflen
,
759 addrs_to_try
[0].errcode
,
760 "Cannot connect to %s", host
);
764 * Show all the errors and the IP addresses
765 * to which they apply.
771 snprintf(errbuf
, errbuflen
,
772 "Connect to %s failed: ", host
);
774 msglen
= strlen(errbuf
);
775 errbufptr
= errbuf
+ msglen
;
776 bufspaceleft
= errbuflen
- msglen
;
778 for (i
= 0; i
< numaddrinfos
&&
779 addrs_to_try
[i
].errcode
!= SOCK_NOERR
;
783 * Get the string for the address
784 * and port that got this error.
786 sock_getascii_addrport((struct sockaddr_storage
*) addrs_to_try
[i
].info
->ai_addr
,
787 errbufptr
, (int)bufspaceleft
,
788 NULL
, 0, NI_NUMERICHOST
, NULL
, 0);
789 msglen
= strlen(errbuf
);
790 errbufptr
= errbuf
+ msglen
;
791 bufspaceleft
= errbuflen
- msglen
;
793 if (i
+ 1 < numaddrinfos
&&
794 addrs_to_try
[i
+ 1].errcode
== addrs_to_try
[i
].errcode
)
797 * There's another error
798 * after this, and it has
799 * the same error code.
801 * Append a comma, as the
802 * list of addresses with
803 * this error has another
806 snprintf(errbufptr
, bufspaceleft
,
812 * Either there are no
813 * more errors after this,
814 * or the next error is
818 * the message for tis
819 * error, followed by a
823 sock_fmterrmsg(errbufptr
,
825 addrs_to_try
[i
].errcode
,
827 msglen
= strlen(errbuf
);
828 errbufptr
= errbuf
+ msglen
;
829 bufspaceleft
= errbuflen
- msglen
;
831 if (i
+ 1 < numaddrinfos
&&
832 addrs_to_try
[i
+ 1].errcode
!= SOCK_NOERR
)
842 msglen
= strlen(errbuf
);
843 errbufptr
= errbuf
+ msglen
;
844 bufspaceleft
= errbuflen
- msglen
;
848 return INVALID_SOCKET
;
859 * \brief Closes the present (TCP and UDP) socket connection.
861 * This function sends a shutdown() on the socket in order to disable send() calls
862 * (while recv() ones are still allowed). Then, it closes the socket.
864 * \param sock: the socket identifier of the connection that has to be closed.
866 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
867 * error message. This buffer has to be at least 'errbuflen' in length.
868 * It can be NULL; in this case the error cannot be printed.
870 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
871 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
873 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
874 * in the 'errbuf' variable.
876 int sock_close(PCAP_SOCKET sock
, char *errbuf
, int errbuflen
)
879 * SHUT_WR: subsequent calls to the send function are disallowed.
880 * For TCP sockets, a FIN will be sent after all data is sent and
881 * acknowledged by the Server.
883 if (shutdown(sock
, SHUT_WR
))
885 sock_geterrmsg(errbuf
, errbuflen
, "shutdown() failed");
886 /* close the socket anyway */
896 * gai_strerror() has some problems:
898 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
899 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
900 * thread-safe, so an implementation might use a static buffer
901 * for unknown error codes;
902 * 3) the error message for the most likely error, EAI_NONAME, is
903 * truly horrible on several platforms ("nodename nor servname
904 * provided, or not known"? It's typically going to be "not
905 * known", not "oopsie, I passed null pointers for the host name
906 * and service name", not to mention they forgot the "neither");
908 * so we roll our own.
911 get_gai_errstring(char *errbuf
, int errbuflen
, const char *prefix
, int err
,
912 const char *hostname
, const char *portname
)
914 char hostport
[PCAP_ERRBUF_SIZE
];
916 if (hostname
!= NULL
&& portname
!= NULL
)
917 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host and port %s:%s",
919 else if (hostname
!= NULL
)
920 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host %s",
922 else if (portname
!= NULL
)
923 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "port %s",
926 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "<no host or port!>");
929 #ifdef EAI_ADDRFAMILY
931 snprintf(errbuf
, errbuflen
,
932 "%sAddress family for %s not supported",
938 snprintf(errbuf
, errbuflen
,
939 "%s%s could not be resolved at this time",
944 snprintf(errbuf
, errbuflen
,
945 "%sThe ai_flags parameter for looking up %s had an invalid value",
950 snprintf(errbuf
, errbuflen
,
951 "%sA non-recoverable error occurred when attempting to resolve %s",
956 snprintf(errbuf
, errbuflen
,
957 "%sThe address family for looking up %s was not recognized",
962 snprintf(errbuf
, errbuflen
,
963 "%sOut of memory trying to allocate storage when looking up %s",
968 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
970 * RFC 3493 has only EAI_NONAME.
972 * Some implementations define EAI_NODATA and EAI_NONAME
973 * to the same value, others don't. If EAI_NODATA is
974 * defined and isn't the same as EAI_NONAME, we handle
977 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
979 snprintf(errbuf
, errbuflen
,
980 "%sNo address associated with %s",
986 snprintf(errbuf
, errbuflen
,
987 "%sThe %s couldn't be resolved",
992 snprintf(errbuf
, errbuflen
,
993 "%sThe service value specified when looking up %s as not recognized for the socket type",
998 snprintf(errbuf
, errbuflen
,
999 "%sThe socket type specified when looking up %s as not recognized",
1006 * Assumed to be UN*X.
1008 pcapint_fmt_errmsg_for_errno(errbuf
, errbuflen
, errno
,
1009 "%sAn error occurred when looking up %s",
1016 snprintf(errbuf
, errbuflen
,
1017 "%sInvalid value for hints when looking up %s",
1024 snprintf(errbuf
, errbuflen
,
1025 "%sResolved protocol when looking up %s is unknown",
1032 snprintf(errbuf
, errbuflen
,
1033 "%sArgument buffer overflow when looking up %s",
1039 snprintf(errbuf
, errbuflen
,
1040 "%sgetaddrinfo() error %d when looking up %s",
1041 prefix
, err
, hostport
);
1047 * \brief Checks that the address, port and flags given are valid and it returns an 'addrinfo' structure.
1049 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
1050 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
1051 * If an error occurs, it writes the error message into 'errbuf'.
1053 * \param host: a pointer to a string identifying the host. It can be
1054 * a host name, a numeric literal address, or NULL or "" (useful
1055 * in case of a server socket which has to bind to all addresses).
1057 * \param port: a pointer to a user-allocated buffer containing the network port to use.
1059 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
1060 * addrinfo structure appropriately.
1062 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
1063 * (passed by reference), which will be allocated by this function and returned back to the caller.
1064 * This variable will be used in the next sockets calls.
1066 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1067 * error message. This buffer has to be at least 'errbuflen' in length.
1068 * It can be NULL; in this case the error cannot be printed.
1070 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1071 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1073 * \return a pointer to the first element in a list of addrinfo structures
1074 * if everything is fine, NULL if some errors occurred. The error message
1075 * is returned in the 'errbuf' variable.
1077 * \warning The list of addrinfo structures returned has to be deleted by
1078 * the programmer by calling freeaddrinfo() when it is no longer needed.
1080 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
1081 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
1082 * the programmer to look at that function in order to set the 'hints' variable appropriately.
1084 struct addrinfo
*sock_initaddress(const char *host
, const char *port
,
1085 struct addrinfo
*hints
, char *errbuf
, int errbuflen
)
1087 struct addrinfo
*addrinfo
;
1091 * We allow both the host and port to be null, but getaddrinfo()
1092 * is not guaranteed to do so; to handle that, if port is null,
1093 * we provide "0" as the port number.
1095 * This results in better error messages from get_gai_errstring(),
1096 * as those messages won't talk about a problem with the port if
1097 * no port was specified.
1099 retval
= getaddrinfo(host
, port
== NULL
? "0" : port
, hints
, &addrinfo
);
1104 * Determine whether the problem is that the host is bad.
1108 if (host
!= NULL
&& port
!= NULL
) {
1110 * Try with just a host, to distinguish
1111 * between "host is bad" and "port is
1116 try_retval
= getaddrinfo(host
, NULL
, hints
,
1118 if (try_retval
== 0) {
1120 * Worked with just the host,
1121 * so assume the problem is
1124 * Free up the address info first.
1126 freeaddrinfo(addrinfo
);
1127 get_gai_errstring(errbuf
, errbuflen
,
1128 "", retval
, NULL
, port
);
1131 * Didn't work with just the host,
1132 * so assume the problem is
1133 * with the host; we assume
1134 * the original error indicates
1135 * the underlying problem.
1137 get_gai_errstring(errbuf
, errbuflen
,
1138 "", retval
, host
, NULL
);
1142 * Either the host or port was null, so
1143 * there's nothing to determine; report
1144 * the error from the original call.
1146 get_gai_errstring(errbuf
, errbuflen
, "",
1147 retval
, host
, port
);
1153 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
1154 * addrinfo has more han one pointers
1158 * This software only supports PF_INET and PF_INET6.
1160 * XXX - should we just check that at least *one* address is
1161 * either PF_INET or PF_INET6, and, when using the list,
1162 * ignore all addresses that are neither? (What, no IPX
1165 if ((addrinfo
->ai_family
!= PF_INET
) &&
1166 (addrinfo
->ai_family
!= PF_INET6
))
1169 snprintf(errbuf
, errbuflen
, "getaddrinfo(): socket type not supported");
1170 freeaddrinfo(addrinfo
);
1175 * You can't do multicast (or broadcast) TCP.
1177 if ((addrinfo
->ai_socktype
== SOCK_STREAM
) &&
1178 (sock_ismcastaddr(addrinfo
->ai_addr
) == 0))
1181 snprintf(errbuf
, errbuflen
, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
1182 freeaddrinfo(addrinfo
);
1190 * \brief It sends the amount of data contained into 'buffer' on the given socket.
1192 * This function basically calls the send() socket function and it checks that all
1193 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
1194 * it writes the error message into 'errbuf'.
1195 * In case the socket buffer does not have enough space, it loops until all data
1198 * \param socket: the connected socket currently opened.
1200 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
1202 * \param size: number of bytes that have to be sent.
1204 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1205 * error message. This buffer has to be at least 'errbuflen' in length.
1206 * It can be NULL; in this case the error cannot be printed.
1208 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1209 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1211 * \return '0' if everything is fine, '-1' if an error other than
1212 * "connection reset" or "peer has closed the receive side" occurred,
1213 * '-2' if we got one of those errors.
1214 * For errors, an error message is returned in the 'errbuf' variable.
1216 int sock_send(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, const char *buffer
,
1217 size_t size
, char *errbuf
, int errbuflen
)
1226 snprintf(errbuf
, errbuflen
,
1227 "Can't send more than %u bytes with sock_send",
1232 remaining
= (int)size
;
1236 if (ssl
) return ssl_send(ssl
, buffer
, remaining
, errbuf
, errbuflen
);
1239 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1244 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
1245 * on errors on stream-oriented sockets when the other
1246 * end breaks the connection.
1247 * The EPIPE error is still returned.
1249 nsent
= send(sock
, buffer
, remaining
, MSG_NOSIGNAL
);
1251 nsent
= send(sock
, buffer
, remaining
, 0);
1253 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1258 * If the client closed the connection out from
1259 * under us, there's no need to log that as an
1265 errcode
= GetLastError();
1266 if (errcode
== WSAECONNRESET
||
1267 errcode
== WSAECONNABORTED
)
1270 * WSAECONNABORTED appears to be the error
1271 * returned in Winsock when you try to send
1272 * on a connection where the peer has closed
1277 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1281 if (errcode
== ECONNRESET
|| errcode
== EPIPE
)
1284 * EPIPE is what's returned on UN*X when
1285 * you try to send on a connection when
1286 * the peer has closed the receive side.
1290 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1298 } while (remaining
!= 0);
1304 * \brief It copies the amount of data contained in 'data' into 'outbuf'.
1305 * and it checks for buffer overflows.
1307 * This function basically copies 'size' bytes of data contained in 'data'
1308 * into 'outbuf', starting at offset 'offset'. Before that, it checks that the
1309 * resulting buffer will not be larger than 'totsize'. Finally, it updates
1310 * the 'offset' variable in order to point to the first empty location of the buffer.
1312 * In case the function is called with 'checkonly' equal to 1, it does not copy
1313 * the data into the buffer. It only checks for buffer overflows and it updates the
1314 * 'offset' variable. This mode can be useful when the buffer already contains the
1315 * data (maybe because the producer writes directly into the target buffer), so
1316 * only the buffer overflow check has to be made.
1317 * In this case, both 'data' and 'outbuf' can be NULL values.
1319 * This function is useful in case the userland application does not know immediately
1320 * all the data it has to write into the socket. This function provides a way to create
1321 * the "stream" step by step, appending the new data to the old one. Then, when all the
1322 * data has been bufferized, the application can call the sock_send() function.
1324 * \param data: a void pointer to the data that has to be copied.
1326 * \param size: number of bytes that have to be copied.
1328 * \param outbuf: user-allocated buffer (of size 'totsize') into which data
1331 * \param offset: an index into 'outbuf' which keeps the location of its first
1334 * \param totsize: total size of the buffer into which data is being copied.
1336 * \param checkonly: '1' if we do not want to copy data into the buffer and we
1337 * want just do a buffer overflow control, '0' if data has to be copied as well.
1339 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1340 * error message. This buffer has to be at least 'errbuflen' in length.
1341 * It can be NULL; in this case the error cannot be printed.
1343 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1344 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1346 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
1347 * is returned in the 'errbuf' variable. When the function returns, 'outbuf' will
1348 * have the new string appended, and 'offset' will keep the length of that buffer.
1349 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
1351 * \warning This function assumes that the buffer in which data has to be stored is
1352 * large 'totbuf' bytes.
1354 * \warning In case of 'checkonly', be carefully to call this function *before* copying
1355 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
1357 int sock_bufferize(const void *data
, int size
, char *outbuf
, int *offset
, int totsize
, int checkonly
, char *errbuf
, int errbuflen
)
1359 if ((*offset
+ size
) > totsize
)
1362 snprintf(errbuf
, errbuflen
, "Not enough space in the temporary send buffer.");
1367 memcpy(outbuf
+ (*offset
), data
, size
);
1375 * \brief It waits on a connected socket and it manages to receive data.
1377 * This function basically calls the recv() socket function and it checks that no
1378 * error occurred. If that happens, it writes the error message into 'errbuf'.
1380 * This function changes its behavior according to the 'receiveall' flag: if we
1381 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
1382 * data is arrived. Otherwise, it returns the data currently available.
1384 * In case the socket does not have enough data available, it cycles on the recv()
1385 * until the requested data (of size 'size') is arrived.
1386 * In this case, it blocks until the number of bytes read is equal to 'size'.
1388 * \param sock: the connected socket currently opened.
1390 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
1392 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
1393 * that we are expecting to be read.
1397 * SOCK_RECEIVALL_XXX:
1399 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
1400 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
1401 * received (in case the socket does not have enough data available).
1405 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
1406 * and return an error on any subsequent read that returns 0;
1407 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
1409 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1410 * error message. This buffer has to be at least 'errbuflen' in length.
1411 * It can be NULL; in this case the error cannot be printed.
1413 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1414 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1416 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
1417 * The error message is returned in the 'errbuf' variable.
1420 int sock_recv(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
, size_t size
,
1421 int flags
, char *errbuf
, int errbuflen
)
1424 char *bufp
= buffer
;
1436 snprintf(errbuf
, errbuflen
,
1437 "Can't read more than %u bytes with sock_recv",
1443 if (flags
& SOCK_MSG_PEEK
)
1444 recv_flags
|= MSG_PEEK
;
1446 bufp
= (char *) buffer
;
1447 remaining
= (int) size
;
1450 * We don't use MSG_WAITALL because it's not supported in
1454 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1455 nread
= fuzz_recv(bufp
, remaining
);
1456 #elif defined(HAVE_OPENSSL)
1460 * XXX - what about MSG_PEEK?
1462 nread
= ssl_recv(ssl
, bufp
, remaining
, errbuf
, errbuflen
);
1463 if (nread
== -2) return -1;
1466 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1468 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1477 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1483 if ((flags
& SOCK_EOF_IS_ERROR
) ||
1484 (remaining
!= (int) size
))
1487 * Either we've already read some data,
1488 * or we're always supposed to return
1493 snprintf(errbuf
, errbuflen
,
1494 "The other host terminated the connection.");
1503 * Do we want to read the amount requested, or just return
1506 if (!(flags
& SOCK_RECEIVEALL_YES
))
1509 * Just return what we got.
1523 * Receives a datagram from a socket.
1525 * Returns the size of the datagram on success or -1 on error.
1527 int sock_recv_dgram(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
,
1528 size_t size
, char *errbuf
, int errbuflen
)
1532 struct msghdr message
;
1544 snprintf(errbuf
, errbuflen
,
1545 "Can't read more than %u bytes with sock_recv_dgram",
1555 snprintf(errbuf
, errbuflen
, "DTLS not implemented yet");
1561 * This should be a datagram socket, so we should get the
1562 * entire datagram in one recv() or recvmsg() call, and
1563 * don't need to loop.
1566 nread
= recv(sock
, buffer
, (int)size
, 0);
1567 if (nread
== SOCKET_ERROR
)
1570 * To quote the MSDN documentation for recv(),
1571 * "If the datagram or message is larger than
1572 * the buffer specified, the buffer is filled
1573 * with the first part of the datagram, and recv
1574 * generates the error WSAEMSGSIZE. For unreliable
1575 * protocols (for example, UDP) the excess data is
1578 * So if the message is bigger than the buffer
1579 * supplied to us, the excess data is discarded,
1580 * and we'll report an error.
1582 sock_fmterrmsg(errbuf
, errbuflen
, sock_geterrcode(),
1588 * The Single UNIX Specification says that a recv() on
1589 * a socket for a message-oriented protocol will discard
1590 * the excess data. It does *not* indicate that the
1591 * receive will fail with, for example, EMSGSIZE.
1593 * Therefore, we use recvmsg(), which appears to be
1594 * the only way to get a "message truncated" indication
1595 * when receiving a message for a message-oriented
1598 message
.msg_name
= NULL
; /* we don't care who it's from */
1599 message
.msg_namelen
= 0;
1600 iov
.iov_base
= buffer
;
1602 message
.msg_iov
= &iov
;
1603 message
.msg_iovlen
= 1;
1604 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1605 message
.msg_control
= NULL
; /* we don't care about control information */
1606 message
.msg_controllen
= 0;
1608 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1609 message
.msg_flags
= 0;
1611 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1612 nread
= fuzz_recv(buffer
, size
);
1614 nread
= recvmsg(sock
, &message
, 0);
1620 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1623 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1625 * XXX - Solaris supports this, but only if you ask for the
1626 * X/Open version of recvmsg(); should we use that, or will
1627 * that cause other problems?
1629 if (message
.msg_flags
& MSG_TRUNC
)
1632 * Message was bigger than the specified buffer size.
1634 * Report this as an error, as the Microsoft documentation
1635 * implies we'd do in a similar case on Windows.
1637 snprintf(errbuf
, errbuflen
, "recv(): Message too long");
1640 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1644 * The size we're reading fits in an int, so the return value
1645 * will fit in an int.
1651 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1653 * This function is useful in case we receive a message we cannot understand (e.g.
1654 * wrong version number when receiving a network packet), so that we have to discard all
1655 * data before reading a new message.
1657 * This function will read 'size' bytes from the socket and discard them.
1658 * It defines an internal buffer in which data will be copied; however, in case
1659 * this buffer is not large enough, it will cycle in order to read everything as well.
1661 * \param sock: the connected socket currently opened.
1663 * \param size: number of bytes that have to be discarded.
1665 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1666 * error message. This buffer has to be at least 'errbuflen' in length.
1667 * It can be NULL; in this case the error cannot be printed.
1669 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1670 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1672 * \return '0' if everything is fine, '-1' if some errors occurred.
1673 * The error message is returned in the 'errbuf' variable.
1675 int sock_discard(PCAP_SOCKET sock
, SSL
*ssl
, int size
, char *errbuf
,
1678 #define TEMP_BUF_SIZE 32768
1680 char buffer
[TEMP_BUF_SIZE
]; /* network buffer, to be used when the message is discarded */
1683 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1684 * Our feeling is that a buffer if 32KB is enough for most of the application;
1685 * in case this is not enough, the "while" loop discards the message by calling the
1686 * sockrecv() several times.
1687 * We do not want to create a bigger variable because this causes the program to exit on
1688 * some platforms (e.g. BSD)
1690 while (size
> TEMP_BUF_SIZE
)
1692 if (sock_recv(sock
, ssl
, buffer
, TEMP_BUF_SIZE
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1695 size
-= TEMP_BUF_SIZE
;
1699 * If there is still data to be discarded
1700 * In this case, the data can fit into the temporary buffer
1704 if (sock_recv(sock
, ssl
, buffer
, size
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1712 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1714 * This function is useful after an accept() call in order to check if the connecting
1715 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1716 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1717 * against this host list, and it returns '0' is the host is included in this list.
1719 * \param hostlist: pointer to a string that contains the list of the allowed host.
1721 * \param sep: a string that keeps the separators used between the hosts (for example the
1722 * space character) in the host list.
1724 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1726 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1727 * error message. This buffer has to be at least 'errbuflen' in length.
1728 * It can be NULL; in this case the error cannot be printed.
1730 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1731 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1733 * \return It returns:
1734 * - '1' if the host list is empty
1735 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1736 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1737 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1739 int sock_check_hostlist(const char *hostlist
, const char *sep
, struct sockaddr_storage
*from
, char *errbuf
, int errbuflen
)
1741 /* checks if the connecting host is among the ones allowed */
1742 if ((hostlist
) && (hostlist
[0]))
1744 char *token
; /* temp, needed to separate items into the hostlist */
1745 struct addrinfo
*addrinfo
, *ai_next
;
1748 int getaddrinfo_failed
= 0;
1751 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1752 * So, we have to create a new temporary string in which the original content is kept
1754 temphostlist
= strdup(hostlist
);
1755 if (temphostlist
== NULL
)
1757 sock_geterrmsg(errbuf
, errbuflen
,
1758 "sock_check_hostlist(), malloc() failed");
1762 token
= pcapint_strtok_r(temphostlist
, sep
, &lasts
);
1764 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1767 while (token
!= NULL
)
1769 struct addrinfo hints
;
1773 memset(&hints
, 0, sizeof(struct addrinfo
));
1774 hints
.ai_family
= PF_UNSPEC
;
1775 hints
.ai_socktype
= SOCK_STREAM
;
1777 retval
= getaddrinfo(token
, NULL
, &hints
, &addrinfo
);
1781 get_gai_errstring(errbuf
, errbuflen
,
1782 "Allowed host list error: ",
1783 retval
, token
, NULL
);
1786 * Note that at least one call to getaddrinfo()
1789 getaddrinfo_failed
= 1;
1791 /* Get next token */
1792 token
= pcapint_strtok_r(NULL
, sep
, &lasts
);
1796 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1800 if (sock_cmpaddr(from
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
1803 freeaddrinfo(addrinfo
);
1808 * If we are here, it means that the current address does not matches
1809 * Let's try with the next one in the header chain
1811 ai_next
= ai_next
->ai_next
;
1814 freeaddrinfo(addrinfo
);
1817 /* Get next token */
1818 token
= pcapint_strtok_r(NULL
, sep
, &lasts
);
1823 freeaddrinfo(addrinfo
);
1829 if (getaddrinfo_failed
) {
1831 * At least one getaddrinfo() call failed;
1832 * treat that as an error, so rpcapd knows
1833 * that it should log it locally as well
1834 * as telling the client about it.
1839 * All getaddrinfo() calls succeeded, but
1840 * the host wasn't in the list.
1843 snprintf(errbuf
, errbuflen
, "The host is not in the allowed host list. Connection refused.");
1848 /* No hostlist, so we have to return 'empty list' */
1853 * \brief Compares two addresses contained into two sockaddr_storage structures.
1855 * This function is useful to compare two addresses, given their internal representation,
1856 * i.e. an sockaddr_storage structure.
1858 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1859 * sockaddr_in6, properly casted in order to be compliant to the function interface.
1861 * This function will return '0' if the two addresses matches, '-1' if not.
1863 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1864 * accept() call), containing the first address to compare.
1866 * \param second: a sockaddr_storage structure containing the second address to compare.
1868 * \return '0' if the addresses are equal, '-1' if they are different.
1870 int sock_cmpaddr(struct sockaddr_storage
*first
, struct sockaddr_storage
*second
)
1872 if (first
->ss_family
== second
->ss_family
)
1874 if (first
->ss_family
== AF_INET
)
1876 if (memcmp(&(((struct sockaddr_in
*) first
)->sin_addr
),
1877 &(((struct sockaddr_in
*) second
)->sin_addr
),
1878 sizeof(struct in_addr
)) == 0)
1881 else /* address family is AF_INET6 */
1883 if (memcmp(&(((struct sockaddr_in6
*) first
)->sin6_addr
),
1884 &(((struct sockaddr_in6
*) second
)->sin6_addr
),
1885 sizeof(struct in6_addr
)) == 0)
1894 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1896 * It is used to return the address and port the server picked for our socket on the local machine.
1898 * - connected sockets
1901 * On unconnected client sockets it does not work because the system dynamically chooses a port
1902 * only when the socket calls a send() call.
1904 * \param sock: the connected socket currently opened.
1906 * \param address: it contains the address that will be returned by the function. This buffer
1907 * must be properly allocated by the user. The address can be either literal or numeric depending
1908 * on the value of 'Flags'.
1910 * \param addrlen: the length of the 'address' buffer.
1912 * \param port: it contains the port that will be returned by the function. This buffer
1913 * must be properly allocated by the user.
1915 * \param portlen: the length of the 'port' buffer.
1917 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1918 * that determine if the resulting address must be in numeric / literal form, and so on.
1920 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1921 * error message. This buffer has to be at least 'errbuflen' in length.
1922 * It can be NULL; in this case the error cannot be printed.
1924 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1925 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1927 * \return It returns '-1' if this function succeeds, '0' otherwise.
1928 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1929 * In any case, the returned strings are '0' terminated.
1931 * \warning If the socket is using a connectionless protocol, the address may not be available
1932 * until I/O occurs on the socket.
1934 int sock_getmyinfo(PCAP_SOCKET sock
, char *address
, int addrlen
, char *port
,
1935 int portlen
, int flags
, char *errbuf
, int errbuflen
)
1937 struct sockaddr_storage mysockaddr
;
1938 socklen_t sockaddrlen
;
1941 sockaddrlen
= sizeof(struct sockaddr_storage
);
1943 if (getsockname(sock
, (struct sockaddr
*) &mysockaddr
, &sockaddrlen
) == -1)
1945 sock_geterrmsg(errbuf
, errbuflen
, "getsockname() failed");
1949 /* Returns the numeric address of the host that triggered the error */
1950 return sock_getascii_addrport(&mysockaddr
, address
, addrlen
, port
, portlen
, flags
, errbuf
, errbuflen
);
1954 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1956 * This function is basically an extended version of the inet_ntop(), which does not exist in
1957 * Winsock because the same result can be obtained by using the getnameinfo().
1958 * However, differently from inet_ntop(), this function is able to return also literal names
1959 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1961 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1962 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1963 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1964 * a standard IPv6 address like "::1".
1966 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1967 * are the ones allowed in the standard getnameinfo() socket function.
1969 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1970 * need to be translated from network form into the presentation form. This structure must be
1971 * zero-ed prior using it, and the address family field must be filled with the proper value.
1972 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1973 * calling this function.
1975 * \param address: it contains the address that will be returned by the function. This buffer
1976 * must be properly allocated by the user. The address can be either literal or numeric depending
1977 * on the value of 'Flags'.
1979 * \param addrlen: the length of the 'address' buffer.
1981 * \param port: it contains the port that will be returned by the function. This buffer
1982 * must be properly allocated by the user.
1984 * \param portlen: the length of the 'port' buffer.
1986 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1987 * that determine if the resulting address must be in numeric / literal form, and so on.
1989 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1990 * error message. This buffer has to be at least 'errbuflen' in length.
1991 * It can be NULL; in this case the error cannot be printed.
1993 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1994 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1996 * \return It returns '-1' if this function succeeds, '0' otherwise.
1997 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1999 * In any case, the returned strings are '0' terminated.
2001 int sock_getascii_addrport(const struct sockaddr_storage
*sockaddr
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, size_t errbuflen
)
2003 socklen_t sockaddrlen
;
2004 int retval
; /* Variable that keeps the return value; */
2009 if (sockaddr
->ss_family
== AF_INET
)
2010 sockaddrlen
= sizeof(struct sockaddr_in
);
2012 sockaddrlen
= sizeof(struct sockaddr_in6
);
2014 sockaddrlen
= sizeof(struct sockaddr_storage
);
2017 if ((flags
& NI_NUMERICHOST
) == 0) /* Check that we want literal names */
2019 if ((sockaddr
->ss_family
== AF_INET6
) &&
2020 (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))
2023 pcapint_strlcpy(address
, SOCKET_NAME_NULL_DAD
, addrlen
);
2028 if (getnameinfo((struct sockaddr
*) sockaddr
, sockaddrlen
, address
, addrlen
, port
, portlen
, flags
) != 0)
2030 /* If the user wants to receive an error message */
2033 sock_geterrmsg(errbuf
, errbuflen
,
2034 "getnameinfo() failed");
2035 errbuf
[errbuflen
- 1] = 0;
2040 pcapint_strlcpy(address
, SOCKET_NO_NAME_AVAILABLE
, addrlen
);
2041 address
[addrlen
- 1] = 0;
2046 pcapint_strlcpy(port
, SOCKET_NO_PORT_AVAILABLE
, portlen
);
2047 port
[portlen
- 1] = 0;
2057 * \brief It translates an address from the 'presentation' form into the 'network' form.
2059 * This function basically replaces inet_pton(), which does not exist in Winsock because
2060 * the same result can be obtained by using the getaddrinfo().
2061 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
2062 * like in inet_pton() ) and a literal name (e.g. 'localhost').
2064 * This function does the reverse job of sock_getascii_addrport().
2066 * \param address: a zero-terminated string which contains the name you have to
2067 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
2069 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
2070 * 'network' form of the requested address.
2072 * \param addr_family: a constant which can assume the following values:
2073 * - 'AF_INET' if we want to ping an IPv4 host
2074 * - 'AF_INET6' if we want to ping an IPv6 host
2075 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
2077 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
2078 * error message. This buffer has to be at least 'errbuflen' in length.
2079 * It can be NULL; in this case the error cannot be printed.
2081 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
2082 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
2084 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
2085 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
2086 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
2087 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
2088 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
2090 * \warning The sockaddr_storage structure MUST be allocated by the user.
2092 int sock_present2network(const char *address
, struct sockaddr_storage
*sockaddr
, int addr_family
, char *errbuf
, int errbuflen
)
2094 struct addrinfo
*addrinfo
;
2095 struct addrinfo hints
;
2097 memset(&hints
, 0, sizeof(hints
));
2099 hints
.ai_family
= addr_family
;
2101 addrinfo
= sock_initaddress(address
, "22222" /* fake port */, &hints
,
2103 if (addrinfo
== NULL
)
2106 if (addrinfo
->ai_family
== PF_INET
)
2107 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in
));
2109 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in6
));
2111 if (addrinfo
->ai_next
!= NULL
)
2113 freeaddrinfo(addrinfo
);
2116 snprintf(errbuf
, errbuflen
, "More than one socket requested; using the first one returned");
2120 freeaddrinfo(addrinfo
);