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 pcap_vfmt_errmsg_for_win32_err(errbuf
, errbuflen
, errcode
,
169 pcap_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 overwrit elower-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 somethng 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 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 SOCKET
sock_open(const char *host
, struct addrinfo
*addrinfo
, int server
, int nconn
, char *errbuf
, int errbuflen
)
508 /* This is a server socket */
514 * Attempt to create the socket.
516 sock
= sock_create_socket(addrinfo
, errbuf
, errbuflen
);
517 if (sock
== INVALID_SOCKET
)
519 return INVALID_SOCKET
;
523 * Allow a new server to bind the socket after the old one
524 * exited, even if lingering sockets are still present.
526 * Don't treat an error as a failure.
529 (void)setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
,
530 (char *)&on
, sizeof (on
));
532 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
534 * Force the use of IPv6-only addresses.
536 * RFC 3493 indicates that you can support IPv4 on an
539 * https://tools.ietf.org/html/rfc3493#section-3.7
541 * and that this is the default behavior. This means
542 * that if we first create an IPv6 socket bound to the
543 * "any" address, it is, in effect, also bound to the
544 * IPv4 "any" address, so when we create an IPv4 socket
545 * and try to bind it to the IPv4 "any" address, it gets
548 * Not all network stacks support IPv4 on IPv6 sockets;
549 * pre-NT 6 Windows stacks don't support it, and the
550 * OpenBSD stack doesn't support it for security reasons
551 * (see the OpenBSD inet6(4) man page). Therefore, we
552 * don't want to rely on this behavior.
554 * So we try to disable it, using either the IPV6_V6ONLY
555 * option from RFC 3493:
557 * https://tools.ietf.org/html/rfc3493#section-5.3
559 * or the IPV6_BINDV6ONLY option from older UN*Xes.
562 /* For older systems */
563 #define IPV6_V6ONLY IPV6_BINDV6ONLY
564 #endif /* IPV6_V6ONLY */
565 if (addrinfo
->ai_family
== PF_INET6
)
568 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
,
569 (char *)&on
, sizeof (int)) == -1)
572 snprintf(errbuf
, errbuflen
, "setsockopt(IPV6_V6ONLY)");
574 return INVALID_SOCKET
;
577 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
579 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
580 if (bind(sock
, addrinfo
->ai_addr
, (int) addrinfo
->ai_addrlen
) != 0)
582 sock_geterrmsg(errbuf
, errbuflen
, "bind() failed");
584 return INVALID_SOCKET
;
587 if (addrinfo
->ai_socktype
== SOCK_STREAM
)
588 if (listen(sock
, nconn
) == -1)
590 sock_geterrmsg(errbuf
, errbuflen
,
593 return INVALID_SOCKET
;
596 /* server side ended */
599 else /* we're the client */
601 struct addr_status
*addrs_to_try
;
602 struct addrinfo
*tempaddrinfo
;
605 int current_af
= AF_UNSPEC
;
608 * We have to loop though all the addrinfos returned.
609 * For instance, we can have both IPv6 and IPv4 addresses,
610 * but the service we're trying to connect to is unavailable
611 * in IPv6, so we have to try in IPv4 as well.
613 * How many addrinfos do we have?
616 for (tempaddrinfo
= addrinfo
; tempaddrinfo
!= NULL
;
617 tempaddrinfo
= tempaddrinfo
->ai_next
)
622 if (numaddrinfos
== 0)
624 snprintf(errbuf
, errbuflen
,
625 "There are no addresses in the address list");
626 return INVALID_SOCKET
;
630 * Allocate an array of struct addr_status and fill it in.
632 addrs_to_try
= calloc(numaddrinfos
, sizeof *addrs_to_try
);
633 if (addrs_to_try
== NULL
)
635 snprintf(errbuf
, errbuflen
,
636 "Out of memory connecting to %s", host
);
637 return INVALID_SOCKET
;
640 for (tempaddrinfo
= addrinfo
, i
= 0; tempaddrinfo
!= NULL
;
641 tempaddrinfo
= tempaddrinfo
->ai_next
, i
++)
643 addrs_to_try
[i
].info
= tempaddrinfo
;
644 addrs_to_try
[i
].errcode
= 0;
645 addrs_to_try
[i
].errtype
= SOCK_NOERR
;
649 * Sort the structures to put the IPv4 addresses before the
650 * IPv6 addresses; we will have to create an IPv4 socket
651 * for the IPv4 addresses and an IPv6 socket for the IPv6
652 * addresses (one of the arguments to socket() is the
653 * address/protocol family to use, and IPv4 and IPv6 are
654 * separate address/protocol families).
656 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
657 compare_addrs_to_try_by_address_family
);
659 /* Start out with no socket. */
660 sock
= INVALID_SOCKET
;
665 for (i
= 0; i
< numaddrinfos
; i
++)
667 tempaddrinfo
= addrs_to_try
[i
].info
;
668 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
672 * If we have a socket, but it's for a
673 * different address family, close it.
675 if (sock
!= INVALID_SOCKET
&&
676 current_af
!= tempaddrinfo
->ai_family
)
679 sock
= INVALID_SOCKET
;
683 * If we don't have a socket, open one
684 * for *this* address's address family.
686 if (sock
== INVALID_SOCKET
)
688 sock
= sock_create_socket(tempaddrinfo
,
690 if (sock
== INVALID_SOCKET
)
693 return INVALID_SOCKET
;
696 if (connect(sock
, tempaddrinfo
->ai_addr
, (int) tempaddrinfo
->ai_addrlen
) == -1)
698 addrs_to_try
[i
].errcode
= sock_geterrcode();
699 addrs_to_try
[i
].errtype
=
700 sock_geterrtype(addrs_to_try
[i
].errcode
);
707 * Check how we exited from the previous loop.
708 * If tempaddrinfo is equal to NULL, it means that all
709 * the connect() attempts failed. Construct an
712 if (i
== numaddrinfos
)
714 int same_error_for_all
;
720 * Sort the statuses to group together categories
721 * of errors, errors within categories, and
722 * address families within error sets.
724 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
725 compare_addrs_to_try_by_status
);
728 * Are all the errors the same?
730 same_error_for_all
= 1;
731 first_error
= addrs_to_try
[0].errcode
;
732 for (i
= 1; i
< numaddrinfos
; i
++)
734 if (addrs_to_try
[i
].errcode
!= first_error
)
736 same_error_for_all
= 0;
741 if (same_error_for_all
) {
743 * Yes. No need to show the IP
746 if (addrs_to_try
[0].errtype
== SOCK_CONNERR
) {
748 * Connection error; note that
749 * the daemon might not be set
750 * up correctly, or set up at all.
752 sock_fmterrmsg(errbuf
, errbuflen
,
753 addrs_to_try
[0].errcode
,
754 "Is the server properly installed? Cannot connect to %s",
757 sock_fmterrmsg(errbuf
, errbuflen
,
758 addrs_to_try
[0].errcode
,
759 "Cannot connect to %s", host
);
763 * Show all the errors and the IP addresses
764 * to which they apply.
770 snprintf(errbuf
, errbuflen
,
771 "Connect to %s failed: ", host
);
773 msglen
= strlen(errbuf
);
774 errbufptr
= errbuf
+ msglen
;
775 bufspaceleft
= errbuflen
- msglen
;
777 for (i
= 0; i
< numaddrinfos
&&
778 addrs_to_try
[i
].errcode
!= SOCK_NOERR
;
782 * Get the string for the address
783 * and port that got this error.
785 sock_getascii_addrport((struct sockaddr_storage
*) addrs_to_try
[i
].info
->ai_addr
,
786 errbufptr
, (int)bufspaceleft
,
787 NULL
, 0, NI_NUMERICHOST
, NULL
, 0);
788 msglen
= strlen(errbuf
);
789 errbufptr
= errbuf
+ msglen
;
790 bufspaceleft
= errbuflen
- msglen
;
792 if (i
+ 1 < numaddrinfos
&&
793 addrs_to_try
[i
+ 1].errcode
== addrs_to_try
[i
].errcode
)
796 * There's another error
797 * after this, and it has
798 * the same error code.
800 * Append a comma, as the
801 * list of addresses with
802 * this error has another
805 snprintf(errbufptr
, bufspaceleft
,
811 * Either there are no
812 * more errors after this,
813 * or the next error is
817 * the message for tis
818 * error, followed by a
822 sock_fmterrmsg(errbufptr
,
824 addrs_to_try
[i
].errcode
,
826 msglen
= strlen(errbuf
);
827 errbufptr
= errbuf
+ msglen
;
828 bufspaceleft
= errbuflen
- msglen
;
830 if (i
+ 1 < numaddrinfos
&&
831 addrs_to_try
[i
+ 1].errcode
!= SOCK_NOERR
)
841 msglen
= strlen(errbuf
);
842 errbufptr
= errbuf
+ msglen
;
843 bufspaceleft
= errbuflen
- msglen
;
847 return INVALID_SOCKET
;
858 * \brief Closes the present (TCP and UDP) socket connection.
860 * This function sends a shutdown() on the socket in order to disable send() calls
861 * (while recv() ones are still allowed). Then, it closes the socket.
863 * \param sock: the socket identifier of the connection that has to be closed.
865 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
866 * error message. This buffer has to be at least 'errbuflen' in length.
867 * It can be NULL; in this case the error cannot be printed.
869 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
870 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
872 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
873 * in the 'errbuf' variable.
875 int sock_close(SOCKET sock
, char *errbuf
, int errbuflen
)
878 * SHUT_WR: subsequent calls to the send function are disallowed.
879 * For TCP sockets, a FIN will be sent after all data is sent and
880 * acknowledged by the Server.
882 if (shutdown(sock
, SHUT_WR
))
884 sock_geterrmsg(errbuf
, errbuflen
, "shutdown() feiled");
885 /* close the socket anyway */
895 * gai_strerror() has some problems:
897 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
898 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
899 * thread-safe, so an implementation might use a static buffer
900 * for unknown error codes;
901 * 3) the error message for the most likely error, EAI_NONAME, is
902 * truly horrible on several platforms ("nodename nor servname
903 * provided, or not known"? It's typically going to be "not
904 * known", not "oopsie, I passed null pointers for the host name
905 * and service name", not to mention they forgot the "neither");
907 * so we roll our own.
910 get_gai_errstring(char *errbuf
, int errbuflen
, const char *prefix
, int err
,
911 const char *hostname
, const char *portname
)
913 char hostport
[PCAP_ERRBUF_SIZE
];
915 if (hostname
!= NULL
&& portname
!= NULL
)
916 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host and port %s:%s",
918 else if (hostname
!= NULL
)
919 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host %s",
921 else if (portname
!= NULL
)
922 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "port %s",
925 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "<no host or port!>");
928 #ifdef EAI_ADDRFAMILY
930 snprintf(errbuf
, errbuflen
,
931 "%sAddress family for %s not supported",
937 snprintf(errbuf
, errbuflen
,
938 "%s%s could not be resolved at this time",
943 snprintf(errbuf
, errbuflen
,
944 "%sThe ai_flags parameter for looking up %s had an invalid value",
949 snprintf(errbuf
, errbuflen
,
950 "%sA non-recoverable error occurred when attempting to resolve %s",
955 snprintf(errbuf
, errbuflen
,
956 "%sThe address family for looking up %s was not recognized",
961 snprintf(errbuf
, errbuflen
,
962 "%sOut of memory trying to allocate storage when looking up %s",
967 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
969 * RFC 3493 has only EAI_NONAME.
971 * Some implementations define EAI_NODATA and EAI_NONAME
972 * to the same value, others don't. If EAI_NODATA is
973 * defined and isn't the same as EAI_NONAME, we handle
976 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
978 snprintf(errbuf
, errbuflen
,
979 "%sNo address associated with %s",
985 snprintf(errbuf
, errbuflen
,
986 "%sThe %s couldn't be resolved",
991 snprintf(errbuf
, errbuflen
,
992 "%sThe service value specified when looking up %s as not recognized for the socket type",
997 snprintf(errbuf
, errbuflen
,
998 "%sThe socket type specified when looking up %s as not recognized",
1005 * Assumed to be UN*X.
1007 pcap_fmt_errmsg_for_errno(errbuf
, errbuflen
, errno
,
1008 "%sAn error occurred when looking up %s",
1015 snprintf(errbuf
, errbuflen
,
1016 "%sInvalid value for hints when looking up %s",
1023 snprintf(errbuf
, errbuflen
,
1024 "%sResolved protocol when looking up %s is unknown",
1031 snprintf(errbuf
, errbuflen
,
1032 "%sArgument buffer overflow when looking up %s",
1038 snprintf(errbuf
, errbuflen
,
1039 "%sgetaddrinfo() error %d when looking up %s",
1040 prefix
, err
, hostport
);
1046 * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
1048 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
1049 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
1050 * If an error occurs, it writes the error message into 'errbuf'.
1052 * \param host: a pointer to a string identifying the host. It can be
1053 * a host name, a numeric literal address, or NULL or "" (useful
1054 * in case of a server socket which has to bind to all addresses).
1056 * \param port: a pointer to a user-allocated buffer containing the network port to use.
1058 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
1059 * addrinfo structure appropriately.
1061 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
1062 * (passed by reference), which will be allocated by this function and returned back to the caller.
1063 * This variable will be used in the next sockets calls.
1065 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1066 * error message. This buffer has to be at least 'errbuflen' in length.
1067 * It can be NULL; in this case the error cannot be printed.
1069 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1070 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1072 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1073 * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
1074 * returned into the addrinfo parameter.
1076 * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
1077 * it is no longer needed.
1079 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
1080 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
1081 * the programmer to look at that function in order to set the 'hints' variable appropriately.
1083 int sock_initaddress(const char *host
, const char *port
,
1084 struct addrinfo
*hints
, struct addrinfo
**addrinfo
, char *errbuf
, int errbuflen
)
1089 * We allow both the host and port to be null, but getaddrinfo()
1090 * is not guaranteed to do so; to handle that, if port is null,
1091 * we provide "0" as the port number.
1093 * This results in better error messages from get_gai_errstring(),
1094 * as those messages won't talk about a problem with the port if
1095 * no port was specified.
1097 retval
= getaddrinfo(host
, port
== NULL
? "0" : port
, hints
, addrinfo
);
1102 if (host
!= NULL
&& port
!= NULL
) {
1104 * Try with just a host, to distinguish
1105 * between "host is bad" and "port is
1110 try_retval
= getaddrinfo(host
, NULL
, hints
,
1112 if (try_retval
== 0) {
1114 * Worked with just the host,
1115 * so assume the problem is
1118 * Free up the address info first.
1120 freeaddrinfo(*addrinfo
);
1121 get_gai_errstring(errbuf
, errbuflen
,
1122 "", retval
, NULL
, port
);
1125 * Didn't work with just the host,
1126 * so assume the problem is
1129 get_gai_errstring(errbuf
, errbuflen
,
1130 "", retval
, host
, NULL
);
1134 * Either the host or port was null, so
1135 * there's nothing to determine.
1137 get_gai_errstring(errbuf
, errbuflen
, "",
1138 retval
, host
, port
);
1144 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
1145 * addrinfo has more han one pointers
1149 * This software only supports PF_INET and PF_INET6.
1151 * XXX - should we just check that at least *one* address is
1152 * either PF_INET or PF_INET6, and, when using the list,
1153 * ignore all addresses that are neither? (What, no IPX
1156 if (((*addrinfo
)->ai_family
!= PF_INET
) &&
1157 ((*addrinfo
)->ai_family
!= PF_INET6
))
1160 snprintf(errbuf
, errbuflen
, "getaddrinfo(): socket type not supported");
1161 freeaddrinfo(*addrinfo
);
1167 * You can't do multicast (or broadcast) TCP.
1169 if (((*addrinfo
)->ai_socktype
== SOCK_STREAM
) &&
1170 (sock_ismcastaddr((*addrinfo
)->ai_addr
) == 0))
1173 snprintf(errbuf
, errbuflen
, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
1174 freeaddrinfo(*addrinfo
);
1183 * \brief It sends the amount of data contained into 'buffer' on the given socket.
1185 * This function basically calls the send() socket function and it checks that all
1186 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
1187 * it writes the error message into 'errbuf'.
1188 * In case the socket buffer does not have enough space, it loops until all data
1191 * \param socket: the connected socket currently opened.
1193 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
1195 * \param size: number of bytes that have to be sent.
1197 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1198 * error message. This buffer has to be at least 'errbuflen' in length.
1199 * It can be NULL; in this case the error cannot be printed.
1201 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1202 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1204 * \return '0' if everything is fine, '-1' if an error other than
1205 * "connection reset" or "peer has closed the receive side" occurred,
1206 * '-2' if we got one of those errors.
1207 * For errors, an error message is returned in the 'errbuf' variable.
1209 int sock_send(SOCKET sock
, SSL
*ssl _U_NOSSL_
, const char *buffer
, size_t size
,
1210 char *errbuf
, int errbuflen
)
1219 snprintf(errbuf
, errbuflen
,
1220 "Can't send more than %u bytes with sock_send",
1225 remaining
= (int)size
;
1229 if (ssl
) return ssl_send(ssl
, buffer
, remaining
, errbuf
, errbuflen
);
1232 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1237 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
1238 * on errors on stream-oriented sockets when the other
1239 * end breaks the connection.
1240 * The EPIPE error is still returned.
1242 nsent
= send(sock
, buffer
, remaining
, MSG_NOSIGNAL
);
1244 nsent
= send(sock
, buffer
, remaining
, 0);
1246 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1251 * If the client closed the connection out from
1252 * under us, there's no need to log that as an
1258 errcode
= GetLastError();
1259 if (errcode
== WSAECONNRESET
||
1260 errcode
== WSAECONNABORTED
)
1263 * WSAECONNABORTED appears to be the error
1264 * returned in Winsock when you try to send
1265 * on a connection where the peer has closed
1270 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1274 if (errcode
== ECONNRESET
|| errcode
== EPIPE
)
1277 * EPIPE is what's returned on UN*X when
1278 * you try to send on a connection when
1279 * the peer has closed the receive side.
1283 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1291 } while (remaining
!= 0);
1297 * \brief It copies the amount of data contained in 'data' into 'outbuf'.
1298 * and it checks for buffer overflows.
1300 * This function basically copies 'size' bytes of data contained in 'data'
1301 * into 'outbuf', starting at offset 'offset'. Before that, it checks that the
1302 * resulting buffer will not be larger than 'totsize'. Finally, it updates
1303 * the 'offset' variable in order to point to the first empty location of the buffer.
1305 * In case the function is called with 'checkonly' equal to 1, it does not copy
1306 * the data into the buffer. It only checks for buffer overflows and it updates the
1307 * 'offset' variable. This mode can be useful when the buffer already contains the
1308 * data (maybe because the producer writes directly into the target buffer), so
1309 * only the buffer overflow check has to be made.
1310 * In this case, both 'data' and 'outbuf' can be NULL values.
1312 * This function is useful in case the userland application does not know immediately
1313 * all the data it has to write into the socket. This function provides a way to create
1314 * the "stream" step by step, appending the new data to the old one. Then, when all the
1315 * data has been bufferized, the application can call the sock_send() function.
1317 * \param data: a void pointer to the data that has to be copied.
1319 * \param size: number of bytes that have to be copied.
1321 * \param outbuf: user-allocated buffer (of size 'totsize') into which data
1324 * \param offset: an index into 'outbuf' which keeps the location of its first
1327 * \param totsize: total size of the buffer into which data is being copied.
1329 * \param checkonly: '1' if we do not want to copy data into the buffer and we
1330 * want just do a buffer ovreflow control, '0' if data has to be copied as well.
1332 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1333 * error message. This buffer has to be at least 'errbuflen' in length.
1334 * It can be NULL; in this case the error cannot be printed.
1336 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1337 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1339 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
1340 * is returned in the 'errbuf' variable. When the function returns, 'outbuf' will
1341 * have the new string appended, and 'offset' will keep the length of that buffer.
1342 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
1344 * \warning This function assumes that the buffer in which data has to be stored is
1345 * large 'totbuf' bytes.
1347 * \warning In case of 'checkonly', be carefully to call this function *before* copying
1348 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
1350 int sock_bufferize(const void *data
, int size
, char *outbuf
, int *offset
, int totsize
, int checkonly
, char *errbuf
, int errbuflen
)
1352 if ((*offset
+ size
) > totsize
)
1355 snprintf(errbuf
, errbuflen
, "Not enough space in the temporary send buffer.");
1360 memcpy(outbuf
+ (*offset
), data
, size
);
1368 * \brief It waits on a connected socket and it manages to receive data.
1370 * This function basically calls the recv() socket function and it checks that no
1371 * error occurred. If that happens, it writes the error message into 'errbuf'.
1373 * This function changes its behavior according to the 'receiveall' flag: if we
1374 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
1375 * data is arrived. Otherwise, it returns the data currently available.
1377 * In case the socket does not have enough data available, it cycles on the recv()
1378 * until the requested data (of size 'size') is arrived.
1379 * In this case, it blocks until the number of bytes read is equal to 'size'.
1381 * \param sock: the connected socket currently opened.
1383 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
1385 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
1386 * that we are expecting to be read.
1390 * SOCK_RECEIVALL_XXX:
1392 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
1393 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
1394 * received (in case the socket does not have enough data available).
1398 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
1399 * and return an error on any subsequent read that returns 0;
1400 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
1402 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1403 * error message. This buffer has to be at least 'errbuflen' in length.
1404 * It can be NULL; in this case the error cannot be printed.
1406 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1407 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1409 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
1410 * The error message is returned in the 'errbuf' variable.
1413 int sock_recv(SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
, size_t size
,
1414 int flags
, char *errbuf
, int errbuflen
)
1417 char *bufp
= buffer
;
1429 snprintf(errbuf
, errbuflen
,
1430 "Can't read more than %u bytes with sock_recv",
1436 if (flags
& SOCK_MSG_PEEK
)
1437 recv_flags
|= MSG_PEEK
;
1439 bufp
= (char *) buffer
;
1440 remaining
= (int) size
;
1443 * We don't use MSG_WAITALL because it's not supported in
1447 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1448 nread
= fuzz_recv(bufp
, remaining
);
1449 #elif defined(HAVE_OPENSSL)
1453 * XXX - what about MSG_PEEK?
1455 nread
= ssl_recv(ssl
, bufp
, remaining
, errbuf
, errbuflen
);
1456 if (nread
== -2) return -1;
1459 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1461 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1470 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1476 if ((flags
& SOCK_EOF_IS_ERROR
) ||
1477 (remaining
!= (int) size
))
1480 * Either we've already read some data,
1481 * or we're always supposed to return
1486 snprintf(errbuf
, errbuflen
,
1487 "The other host terminated the connection.");
1496 * Do we want to read the amount requested, or just return
1499 if (!(flags
& SOCK_RECEIVEALL_YES
))
1502 * Just return what we got.
1516 * Receives a datagram from a socket.
1518 * Returns the size of the datagram on success or -1 on error.
1520 int sock_recv_dgram(SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
, size_t size
,
1521 char *errbuf
, int errbuflen
)
1525 struct msghdr message
;
1537 snprintf(errbuf
, errbuflen
,
1538 "Can't read more than %u bytes with sock_recv_dgram",
1548 snprintf(errbuf
, errbuflen
, "DTLS not implemented yet");
1554 * This should be a datagram socket, so we should get the
1555 * entire datagram in one recv() or recvmsg() call, and
1556 * don't need to loop.
1559 nread
= recv(sock
, buffer
, (int)size
, 0);
1560 if (nread
== SOCKET_ERROR
)
1563 * To quote the MSDN documentation for recv(),
1564 * "If the datagram or message is larger than
1565 * the buffer specified, the buffer is filled
1566 * with the first part of the datagram, and recv
1567 * generates the error WSAEMSGSIZE. For unreliable
1568 * protocols (for example, UDP) the excess data is
1571 * So if the message is bigger than the buffer
1572 * supplied to us, the excess data is discarded,
1573 * and we'll report an error.
1575 sock_fmterrmsg(errbuf
, errbuflen
, sock_geterrcode(),
1581 * The Single UNIX Specification says that a recv() on
1582 * a socket for a message-oriented protocol will discard
1583 * the excess data. It does *not* indicate that the
1584 * receive will fail with, for example, EMSGSIZE.
1586 * Therefore, we use recvmsg(), which appears to be
1587 * the only way to get a "message truncated" indication
1588 * when receiving a message for a message-oriented
1591 message
.msg_name
= NULL
; /* we don't care who it's from */
1592 message
.msg_namelen
= 0;
1593 iov
.iov_base
= buffer
;
1595 message
.msg_iov
= &iov
;
1596 message
.msg_iovlen
= 1;
1597 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1598 message
.msg_control
= NULL
; /* we don't care about control information */
1599 message
.msg_controllen
= 0;
1601 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1602 message
.msg_flags
= 0;
1604 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1605 nread
= fuzz_recv(buffer
, size
);
1607 nread
= recvmsg(sock
, &message
, 0);
1613 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1616 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1618 * XXX - Solaris supports this, but only if you ask for the
1619 * X/Open version of recvmsg(); should we use that, or will
1620 * that cause other problems?
1622 if (message
.msg_flags
& MSG_TRUNC
)
1625 * Message was bigger than the specified buffer size.
1627 * Report this as an error, as the Microsoft documentation
1628 * implies we'd do in a similar case on Windows.
1630 snprintf(errbuf
, errbuflen
, "recv(): Message too long");
1633 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1637 * The size we're reading fits in an int, so the return value
1638 * will fit in an int.
1644 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1646 * This function is useful in case we receive a message we cannot understand (e.g.
1647 * wrong version number when receiving a network packet), so that we have to discard all
1648 * data before reading a new message.
1650 * This function will read 'size' bytes from the socket and discard them.
1651 * It defines an internal buffer in which data will be copied; however, in case
1652 * this buffer is not large enough, it will cycle in order to read everything as well.
1654 * \param sock: the connected socket currently opened.
1656 * \param size: number of bytes that have to be discarded.
1658 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1659 * error message. This buffer has to be at least 'errbuflen' in length.
1660 * It can be NULL; in this case the error cannot be printed.
1662 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1663 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1665 * \return '0' if everything is fine, '-1' if some errors occurred.
1666 * The error message is returned in the 'errbuf' variable.
1668 int sock_discard(SOCKET sock
, SSL
*ssl
, int size
, char *errbuf
, int errbuflen
)
1670 #define TEMP_BUF_SIZE 32768
1672 char buffer
[TEMP_BUF_SIZE
]; /* network buffer, to be used when the message is discarded */
1675 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1676 * Our feeling is that a buffer if 32KB is enough for most of the application;
1677 * in case this is not enough, the "while" loop discards the message by calling the
1678 * sockrecv() several times.
1679 * We do not want to create a bigger variable because this causes the program to exit on
1680 * some platforms (e.g. BSD)
1682 while (size
> TEMP_BUF_SIZE
)
1684 if (sock_recv(sock
, ssl
, buffer
, TEMP_BUF_SIZE
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1687 size
-= TEMP_BUF_SIZE
;
1691 * If there is still data to be discarded
1692 * In this case, the data can fit into the temporary buffer
1696 if (sock_recv(sock
, ssl
, buffer
, size
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1704 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1706 * This function is useful after an accept() call in order to check if the connecting
1707 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1708 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1709 * against this host list, and it returns '0' is the host is included in this list.
1711 * \param hostlist: pointer to a string that contains the list of the allowed host.
1713 * \param sep: a string that keeps the separators used between the hosts (for example the
1714 * space character) in the host list.
1716 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1718 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1719 * error message. This buffer has to be at least 'errbuflen' in length.
1720 * It can be NULL; in this case the error cannot be printed.
1722 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1723 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1725 * \return It returns:
1726 * - '1' if the host list is empty
1727 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1728 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1729 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1731 int sock_check_hostlist(char *hostlist
, const char *sep
, struct sockaddr_storage
*from
, char *errbuf
, int errbuflen
)
1733 /* checks if the connecting host is among the ones allowed */
1734 if ((hostlist
) && (hostlist
[0]))
1736 char *token
; /* temp, needed to separate items into the hostlist */
1737 struct addrinfo
*addrinfo
, *ai_next
;
1740 int getaddrinfo_failed
= 0;
1743 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1744 * So, we have to create a new temporary string in which the original content is kept
1746 temphostlist
= strdup(hostlist
);
1747 if (temphostlist
== NULL
)
1749 sock_geterrmsg(errbuf
, errbuflen
,
1750 "sock_check_hostlist(), malloc() failed");
1754 token
= pcap_strtok_r(temphostlist
, sep
, &lasts
);
1756 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1759 while (token
!= NULL
)
1761 struct addrinfo hints
;
1765 memset(&hints
, 0, sizeof(struct addrinfo
));
1766 hints
.ai_family
= PF_UNSPEC
;
1767 hints
.ai_socktype
= SOCK_STREAM
;
1769 retval
= getaddrinfo(token
, NULL
, &hints
, &addrinfo
);
1773 get_gai_errstring(errbuf
, errbuflen
,
1774 "Allowed host list error: ",
1775 retval
, token
, NULL
);
1778 * Note that at least one call to getaddrinfo()
1781 getaddrinfo_failed
= 1;
1783 /* Get next token */
1784 token
= pcap_strtok_r(NULL
, sep
, &lasts
);
1788 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1792 if (sock_cmpaddr(from
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
1795 freeaddrinfo(addrinfo
);
1800 * If we are here, it means that the current address does not matches
1801 * Let's try with the next one in the header chain
1803 ai_next
= ai_next
->ai_next
;
1806 freeaddrinfo(addrinfo
);
1809 /* Get next token */
1810 token
= pcap_strtok_r(NULL
, sep
, &lasts
);
1815 freeaddrinfo(addrinfo
);
1821 if (getaddrinfo_failed
) {
1823 * At least one getaddrinfo() call failed;
1824 * treat that as an error, so rpcapd knows
1825 * that it should log it locally as well
1826 * as telling the client about it.
1831 * All getaddrinfo() calls succeeded, but
1832 * the host wasn't in the list.
1835 snprintf(errbuf
, errbuflen
, "The host is not in the allowed host list. Connection refused.");
1840 /* No hostlist, so we have to return 'empty list' */
1845 * \brief Compares two addresses contained into two sockaddr_storage structures.
1847 * This function is useful to compare two addresses, given their internal representation,
1848 * i.e. an sockaddr_storage structure.
1850 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1851 * sockaddr_in6, properly acsted in order to be compliant to the function interface.
1853 * This function will return '0' if the two addresses matches, '-1' if not.
1855 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1856 * accept() call), containing the first address to compare.
1858 * \param second: a sockaddr_storage structure containing the second address to compare.
1860 * \return '0' if the addresses are equal, '-1' if they are different.
1862 int sock_cmpaddr(struct sockaddr_storage
*first
, struct sockaddr_storage
*second
)
1864 if (first
->ss_family
== second
->ss_family
)
1866 if (first
->ss_family
== AF_INET
)
1868 if (memcmp(&(((struct sockaddr_in
*) first
)->sin_addr
),
1869 &(((struct sockaddr_in
*) second
)->sin_addr
),
1870 sizeof(struct in_addr
)) == 0)
1873 else /* address family is AF_INET6 */
1875 if (memcmp(&(((struct sockaddr_in6
*) first
)->sin6_addr
),
1876 &(((struct sockaddr_in6
*) second
)->sin6_addr
),
1877 sizeof(struct in6_addr
)) == 0)
1886 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1888 * It is used to return the address and port the server picked for our socket on the local machine.
1890 * - connected sockets
1893 * On unconnected client sockets it does not work because the system dynamically chooses a port
1894 * only when the socket calls a send() call.
1896 * \param sock: the connected socket currently opened.
1898 * \param address: it contains the address that will be returned by the function. This buffer
1899 * must be properly allocated by the user. The address can be either literal or numeric depending
1900 * on the value of 'Flags'.
1902 * \param addrlen: the length of the 'address' buffer.
1904 * \param port: it contains the port that will be returned by the function. This buffer
1905 * must be properly allocated by the user.
1907 * \param portlen: the length of the 'port' buffer.
1909 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1910 * that determine if the resulting address must be in numeric / literal form, and so on.
1912 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1913 * error message. This buffer has to be at least 'errbuflen' in length.
1914 * It can be NULL; in this case the error cannot be printed.
1916 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1917 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1919 * \return It returns '-1' if this function succeeds, '0' otherwise.
1920 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1921 * In any case, the returned strings are '0' terminated.
1923 * \warning If the socket is using a connectionless protocol, the address may not be available
1924 * until I/O occurs on the socket.
1926 int sock_getmyinfo(SOCKET sock
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, int errbuflen
)
1928 struct sockaddr_storage mysockaddr
;
1929 socklen_t sockaddrlen
;
1932 sockaddrlen
= sizeof(struct sockaddr_storage
);
1934 if (getsockname(sock
, (struct sockaddr
*) &mysockaddr
, &sockaddrlen
) == -1)
1936 sock_geterrmsg(errbuf
, errbuflen
, "getsockname() failed");
1940 /* Returns the numeric address of the host that triggered the error */
1941 return sock_getascii_addrport(&mysockaddr
, address
, addrlen
, port
, portlen
, flags
, errbuf
, errbuflen
);
1945 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1947 * This function is basically an extended version of the inet_ntop(), which does not exist in
1948 * Winsock because the same result can be obtained by using the getnameinfo().
1949 * However, differently from inet_ntop(), this function is able to return also literal names
1950 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1952 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1953 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1954 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1955 * a standard IPv6 address like "::1".
1957 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1958 * are the ones allowed in the standard getnameinfo() socket function.
1960 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1961 * need to be translated from network form into the presentation form. This structure must be
1962 * zero-ed prior using it, and the address family field must be filled with the proper value.
1963 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1964 * calling this function.
1966 * \param address: it contains the address that will be returned by the function. This buffer
1967 * must be properly allocated by the user. The address can be either literal or numeric depending
1968 * on the value of 'Flags'.
1970 * \param addrlen: the length of the 'address' buffer.
1972 * \param port: it contains the port that will be returned by the function. This buffer
1973 * must be properly allocated by the user.
1975 * \param portlen: the length of the 'port' buffer.
1977 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1978 * that determine if the resulting address must be in numeric / literal form, and so on.
1980 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1981 * error message. This buffer has to be at least 'errbuflen' in length.
1982 * It can be NULL; in this case the error cannot be printed.
1984 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1985 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1987 * \return It returns '-1' if this function succeeds, '0' otherwise.
1988 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1990 * In any case, the returned strings are '0' terminated.
1992 int sock_getascii_addrport(const struct sockaddr_storage
*sockaddr
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, size_t errbuflen
)
1994 socklen_t sockaddrlen
;
1995 int retval
; /* Variable that keeps the return value; */
2000 if (sockaddr
->ss_family
== AF_INET
)
2001 sockaddrlen
= sizeof(struct sockaddr_in
);
2003 sockaddrlen
= sizeof(struct sockaddr_in6
);
2005 sockaddrlen
= sizeof(struct sockaddr_storage
);
2008 if ((flags
& NI_NUMERICHOST
) == 0) /* Check that we want literal names */
2010 if ((sockaddr
->ss_family
== AF_INET6
) &&
2011 (memcmp(&((struct sockaddr_in6
*) sockaddr
)->sin6_addr
, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(struct in6_addr
)) == 0))
2014 pcap_strlcpy(address
, SOCKET_NAME_NULL_DAD
, addrlen
);
2019 if (getnameinfo((struct sockaddr
*) sockaddr
, sockaddrlen
, address
, addrlen
, port
, portlen
, flags
) != 0)
2021 /* If the user wants to receive an error message */
2024 sock_geterrmsg(errbuf
, errbuflen
,
2025 "getnameinfo() failed");
2026 errbuf
[errbuflen
- 1] = 0;
2031 pcap_strlcpy(address
, SOCKET_NO_NAME_AVAILABLE
, addrlen
);
2032 address
[addrlen
- 1] = 0;
2037 pcap_strlcpy(port
, SOCKET_NO_PORT_AVAILABLE
, portlen
);
2038 port
[portlen
- 1] = 0;
2048 * \brief It translates an address from the 'presentation' form into the 'network' form.
2050 * This function basically replaces inet_pton(), which does not exist in Winsock because
2051 * the same result can be obtained by using the getaddrinfo().
2052 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
2053 * like in inet_pton() ) and a literal name (e.g. 'localhost').
2055 * This function does the reverse job of sock_getascii_addrport().
2057 * \param address: a zero-terminated string which contains the name you have to
2058 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
2060 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
2061 * 'network' form of the requested address.
2063 * \param addr_family: a constant which can assume the following values:
2064 * - 'AF_INET' if we want to ping an IPv4 host
2065 * - 'AF_INET6' if we want to ping an IPv6 host
2066 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
2068 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
2069 * error message. This buffer has to be at least 'errbuflen' in length.
2070 * It can be NULL; in this case the error cannot be printed.
2072 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
2073 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
2075 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
2076 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
2077 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
2078 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
2079 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
2081 * \warning The sockaddr_storage structure MUST be allocated by the user.
2083 int sock_present2network(const char *address
, struct sockaddr_storage
*sockaddr
, int addr_family
, char *errbuf
, int errbuflen
)
2086 struct addrinfo
*addrinfo
;
2087 struct addrinfo hints
;
2089 memset(&hints
, 0, sizeof(hints
));
2091 hints
.ai_family
= addr_family
;
2093 if ((retval
= sock_initaddress(address
, "22222" /* fake port */, &hints
, &addrinfo
, errbuf
, errbuflen
)) == -1)
2096 if (addrinfo
->ai_family
== PF_INET
)
2097 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in
));
2099 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in6
));
2101 if (addrinfo
->ai_next
!= NULL
)
2103 freeaddrinfo(addrinfo
);
2106 snprintf(errbuf
, errbuflen
, "More than one socket requested; using the first one returned");
2110 freeaddrinfo(addrinfo
);