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.
38 * The goal of this file is to provide a common set of primitives for socket
41 * Although the socket interface defined in the RFC 2553 (and its updates)
42 * is excellent, there are still differences between the behavior of those
43 * routines on UN*X and Windows, and between UN*Xes.
45 * These calls provide an interface similar to the socket interface, but
46 * that hides the differences between operating systems. It does not
47 * attempt to significantly improve on the socket interface in other
54 #include <errno.h> /* for the errno variable */
55 #include <stdio.h> /* for the stderr file */
56 #include <stdlib.h> /* for malloc() and free() */
57 #include <limits.h> /* for INT_MAX */
61 #include "sockutils.h"
62 #include "portability.h"
66 * Winsock initialization.
68 * Ask for Winsock 2.2.
70 #define WINSOCK_MAJOR_VERSION 2
71 #define WINSOCK_MINOR_VERSION 2
74 /* Some minor differences between UNIX and Win32 */
76 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
79 /* Size of the buffer that has to keep error messages */
80 #define SOCK_ERRBUF_SIZE 1024
82 /* Constants; used in order to keep strings here */
83 #define SOCKET_NO_NAME_AVAILABLE "No name available"
84 #define SOCKET_NO_PORT_AVAILABLE "No port available"
85 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
88 * On UN*X, send() and recv() return ssize_t.
90 * On Windows, send() and recv() return an int.
92 * With MSVC, there *is* no ssize_t.
94 * With MinGW, there is an ssize_t type; it is either an int (32 bit)
95 * or a long long (64 bit).
97 * So, on Windows, if we don't have ssize_t defined, define it as an
98 * int, so we can use it, on all platforms, as the type of variables
99 * that hold the return values from send() and recv().
101 #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
105 /****************************************************
107 * Locally defined functions *
109 ****************************************************/
111 static int sock_ismcastaddr(const struct sockaddr
*saddr
);
113 /****************************************************
117 ****************************************************/
119 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
120 const uint8_t *fuzzBuffer
;
124 void sock_initfuzz(const uint8_t *Data
, size_t Size
) {
130 static int fuzz_recv(char *bufp
, int remaining
) {
131 if (remaining
> fuzzSize
- fuzzPos
) {
132 remaining
= fuzzSize
- fuzzPos
;
134 if (fuzzPos
< fuzzSize
) {
135 memcpy(bufp
, fuzzBuffer
+ fuzzPos
, remaining
);
137 fuzzPos
+= remaining
;
142 int sock_geterrcode(void)
145 return GetLastError();
152 * Format an error message given an errno value (UN*X) or a Winsock error
155 void sock_vfmterrmsg(char *errbuf
, size_t errbuflen
, int errcode
,
156 const char *fmt
, va_list ap
)
162 pcapint_vfmt_errmsg_for_win32_err(errbuf
, errbuflen
, errcode
,
165 pcapint_vfmt_errmsg_for_errno(errbuf
, errbuflen
, errcode
,
170 void sock_fmterrmsg(char *errbuf
, size_t errbuflen
, int errcode
,
171 const char *fmt
, ...)
176 sock_vfmterrmsg(errbuf
, errbuflen
, errcode
, fmt
, ap
);
181 * Format an error message for the last socket error.
183 void sock_geterrmsg(char *errbuf
, size_t errbuflen
, const char *fmt
, ...)
188 sock_vfmterrmsg(errbuf
, errbuflen
, sock_geterrcode(), fmt
, ap
);
195 * These are sorted by how likely they are to be the "underlying" problem,
196 * so that lower-rated errors for a given address in a given family
197 * should not overwrite higher-rated errors for another address in that
198 * family, and higher-rated errors should overwrite lower-rated errors.
201 SOCK_CONNERR
, /* connection error */
202 SOCK_HOSTERR
, /* host error */
203 SOCK_NETERR
, /* network error */
204 SOCK_AFNOTSUPERR
, /* address family not supported */
205 SOCK_UNKNOWNERR
, /* unknown error */
206 SOCK_NOERR
/* no error */
209 static sock_errtype
sock_geterrtype(int errcode
)
215 case WSAECONNABORTED
:
216 case WSAECONNREFUSED
:
223 * Connection error; this means the problem is probably
224 * that there's no server set up on the remote machine,
225 * or that it is set up, but it's IPv4-only or IPv6-only
226 * and we're trying the wrong address family.
228 * These overwrite all other errors, as they indicate
229 * that, even if something else went wrong in another
230 * attempt, this probably wouldn't work even if the
231 * other problems were fixed.
233 return (SOCK_CONNERR
);
239 case WSAEHOSTUNREACH
:
247 * Network errors that could be IPv4-specific, IPv6-
248 * specific, or present with both.
250 * Don't overwrite connection errors, but overwrite
253 return (SOCK_HOSTERR
);
263 * Network error; this means we don't know whether
264 * there's a server set up on the remote machine,
265 * and we don't have a reason to believe that IPv6
266 * any worse or better than IPv4.
268 * These probably indicate a local failure, e.g.
269 * an interface is down.
271 * Don't overwrite connection errors or host errors,
272 * but overwrite everything else.
274 return (SOCK_NETERR
);
277 case WSAEAFNOSUPPORT
:
282 * "Address family not supported" probably means
283 * "No soup^WIPv6 for you!".
285 * Don't overwrite connection errors, host errors, or
286 * network errors (none of which we should get for this
287 * address family if it's not supported), but overwrite
290 return (SOCK_AFNOTSUPERR
);
296 * Don't overwrite any errors.
298 return (SOCK_UNKNOWNERR
);
303 * \brief This function initializes the socket mechanism, if
306 * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
309 * \param errbuf: a pointer to an user-allocated buffer that will contain
310 * the complete error message. This buffer has to be at least 'errbuflen'
311 * in length. It can be NULL; in this case no error message is supplied.
313 * \param errbuflen: length of the buffer that will contains the error.
314 * The error message cannot be larger than 'errbuflen - 1' because the
315 * last char is reserved for the string terminator.
317 * \return '0' if everything is fine, '-1' if some errors occurred. The
318 * error message is returned in the buffer pointed to by 'errbuf' variable.
321 int sock_init(char *errbuf
, int errbuflen
)
324 WSADATA wsaData
; /* helper variable needed to initialize Winsock */
326 errcode
= WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION
,
327 WINSOCK_MINOR_VERSION
), &wsaData
);
331 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
332 "WSAStartup() failed");
340 int sock_init(char *errbuf _U_
, int errbuflen _U_
)
343 * Nothing to do on UN*Xes.
350 * \brief This function cleans up after a sock_init().
352 * On UN*Xes, it doesn't need to do anything; on Windows, it needs
353 * to clean up Winsock.
355 * \return No error values.
357 void sock_cleanup(void)
365 * \brief It checks if the sockaddr variable contains a multicast address.
367 * \return '0' if the address is multicast, '-1' if it is not.
369 static int sock_ismcastaddr(const struct sockaddr
*saddr
)
371 if (saddr
->sa_family
== PF_INET
)
373 struct sockaddr_in
*saddr4
= (struct sockaddr_in
*) saddr
;
374 if (IN_MULTICAST(ntohl(saddr4
->sin_addr
.s_addr
))) return 0;
379 struct sockaddr_in6
*saddr6
= (struct sockaddr_in6
*) saddr
;
380 if (IN6_IS_ADDR_MULTICAST(&saddr6
->sin6_addr
)) return 0;
386 struct addrinfo
*info
;
388 sock_errtype errtype
;
392 * Sort by IPv4 address vs. IPv6 address.
394 static int compare_addrs_to_try_by_address_family(const void *a
, const void *b
)
396 const struct addr_status
*addr_a
= (const struct addr_status
*)a
;
397 const struct addr_status
*addr_b
= (const struct addr_status
*)b
;
399 return addr_a
->info
->ai_family
- addr_b
->info
->ai_family
;
403 * Sort by error type and, within a given error type, by error code and,
404 * within a given error code, by IPv4 address vs. IPv6 address.
406 static int compare_addrs_to_try_by_status(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 if (addr_a
->errtype
== addr_b
->errtype
)
413 if (addr_a
->errcode
== addr_b
->errcode
)
415 return addr_a
->info
->ai_family
- addr_b
->info
->ai_family
;
417 return addr_a
->errcode
- addr_b
->errcode
;
420 return addr_a
->errtype
- addr_b
->errtype
;
423 static PCAP_SOCKET
sock_create_socket(struct addrinfo
*addrinfo
, char *errbuf
,
431 sock
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
,
432 addrinfo
->ai_protocol
);
433 if (sock
== INVALID_SOCKET
)
435 sock_geterrmsg(errbuf
, errbuflen
, "socket() failed");
436 return INVALID_SOCKET
;
440 * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
441 * have to deal with signals if the peer closes the connection,
442 * especially in client programs, which may not even be aware that
443 * they're sending to sockets.
446 if (setsockopt(sock
, SOL_SOCKET
, SO_NOSIGPIPE
, (char *)&on
,
449 sock_geterrmsg(errbuf
, errbuflen
,
450 "setsockopt(SO_NOSIGPIPE) failed");
452 return INVALID_SOCKET
;
459 * \brief It initializes a network connection both from the client and the server side.
461 * In case of a client socket, this function calls socket() and connect().
462 * In the meanwhile, it checks for any socket error.
463 * If an error occurs, it writes the error message into 'errbuf'.
465 * In case of a server socket, the function calls socket(), bind() and listen().
467 * This function is usually preceded by the sock_initaddress().
469 * \param host: for client sockets, the host name to which we're trying
472 * \param addrinfo: pointer to an addrinfo variable which will be used to
473 * open the socket and such. This variable is the one returned by the previous call to
474 * sock_initaddress().
476 * \param server: '1' if this is a server socket, '0' otherwise.
478 * \param nconn: number of the connections that are allowed to wait into the listen() call.
479 * This value has no meanings in case of a client socket.
481 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
482 * error message. This buffer has to be at least 'errbuflen' in length.
483 * It can be NULL; in this case the error cannot be printed.
485 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
486 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
488 * \return the socket that has been opened (that has to be used in the following sockets calls)
489 * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
490 * in the 'errbuf' variable.
492 PCAP_SOCKET
sock_open(const char *host
, struct addrinfo
*addrinfo
,
493 int server
, int nconn
, char *errbuf
, int errbuflen
)
497 /* This is a server socket */
503 * Attempt to create the socket.
505 sock
= sock_create_socket(addrinfo
, errbuf
, errbuflen
);
506 if (sock
== INVALID_SOCKET
)
508 return INVALID_SOCKET
;
512 * Allow a new server to bind the socket after the old one
513 * exited, even if lingering sockets are still present.
515 * Don't treat an error as a failure.
518 (void)setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
,
519 (char *)&on
, sizeof (on
));
521 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
523 * Force the use of IPv6-only addresses.
525 * RFC 3493 indicates that you can support IPv4 on an
528 * https://tools.ietf.org/html/rfc3493#section-3.7
530 * and that this is the default behavior. This means
531 * that if we first create an IPv6 socket bound to the
532 * "any" address, it is, in effect, also bound to the
533 * IPv4 "any" address, so when we create an IPv4 socket
534 * and try to bind it to the IPv4 "any" address, it gets
537 * Not all network stacks support IPv4 on IPv6 sockets;
538 * pre-NT 6 Windows stacks don't support it, and the
539 * OpenBSD stack doesn't support it for security reasons
540 * (see the OpenBSD inet6(4) man page). Therefore, we
541 * don't want to rely on this behavior.
543 * So we try to disable it, using either the IPV6_V6ONLY
544 * option from RFC 3493:
546 * https://tools.ietf.org/html/rfc3493#section-5.3
548 * or the IPV6_BINDV6ONLY option from older UN*Xes.
551 /* For older systems */
552 #define IPV6_V6ONLY IPV6_BINDV6ONLY
553 #endif /* IPV6_V6ONLY */
554 if (addrinfo
->ai_family
== PF_INET6
)
557 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
,
558 (char *)&on
, sizeof (int)) == -1)
561 snprintf(errbuf
, errbuflen
, "setsockopt(IPV6_V6ONLY)");
563 return INVALID_SOCKET
;
566 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
568 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
569 if (bind(sock
, addrinfo
->ai_addr
, (int) addrinfo
->ai_addrlen
) != 0)
571 sock_geterrmsg(errbuf
, errbuflen
, "bind() failed");
573 return INVALID_SOCKET
;
576 if (addrinfo
->ai_socktype
== SOCK_STREAM
)
577 if (listen(sock
, nconn
) == -1)
579 sock_geterrmsg(errbuf
, errbuflen
,
582 return INVALID_SOCKET
;
585 /* server side ended */
588 else /* we're the client */
590 struct addr_status
*addrs_to_try
;
591 struct addrinfo
*tempaddrinfo
;
594 int current_af
= AF_UNSPEC
;
597 * We have to loop though all the addrinfos returned.
598 * For instance, we can have both IPv6 and IPv4 addresses,
599 * but the service we're trying to connect to is unavailable
600 * in IPv6, so we have to try in IPv4 as well.
602 * How many addrinfos do we have?
605 for (tempaddrinfo
= addrinfo
; tempaddrinfo
!= NULL
;
606 tempaddrinfo
= tempaddrinfo
->ai_next
)
611 if (numaddrinfos
== 0)
613 snprintf(errbuf
, errbuflen
,
614 "There are no addresses in the address list");
615 return INVALID_SOCKET
;
619 * Allocate an array of struct addr_status and fill it in.
621 addrs_to_try
= calloc(numaddrinfos
, sizeof *addrs_to_try
);
622 if (addrs_to_try
== NULL
)
624 snprintf(errbuf
, errbuflen
,
625 "Out of memory connecting to %s", host
);
626 return INVALID_SOCKET
;
629 for (tempaddrinfo
= addrinfo
, i
= 0; tempaddrinfo
!= NULL
;
630 tempaddrinfo
= tempaddrinfo
->ai_next
, i
++)
632 addrs_to_try
[i
].info
= tempaddrinfo
;
633 addrs_to_try
[i
].errcode
= 0;
634 addrs_to_try
[i
].errtype
= SOCK_NOERR
;
638 * Sort the structures to put the IPv4 addresses before the
639 * IPv6 addresses; we will have to create an IPv4 socket
640 * for the IPv4 addresses and an IPv6 socket for the IPv6
641 * addresses (one of the arguments to socket() is the
642 * address/protocol family to use, and IPv4 and IPv6 are
643 * separate address/protocol families).
645 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
646 compare_addrs_to_try_by_address_family
);
648 /* Start out with no socket. */
649 sock
= INVALID_SOCKET
;
654 for (i
= 0; i
< numaddrinfos
; i
++)
656 tempaddrinfo
= addrs_to_try
[i
].info
;
657 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
661 * If we have a socket, but it's for a
662 * different address family, close it.
664 if (sock
!= INVALID_SOCKET
&&
665 current_af
!= tempaddrinfo
->ai_family
)
668 sock
= INVALID_SOCKET
;
672 * If we don't have a socket, open one
673 * for *this* address's address family.
675 if (sock
== INVALID_SOCKET
)
677 sock
= sock_create_socket(tempaddrinfo
,
679 if (sock
== INVALID_SOCKET
)
682 return INVALID_SOCKET
;
685 if (connect(sock
, tempaddrinfo
->ai_addr
, (int) tempaddrinfo
->ai_addrlen
) == -1)
687 addrs_to_try
[i
].errcode
= sock_geterrcode();
688 addrs_to_try
[i
].errtype
=
689 sock_geterrtype(addrs_to_try
[i
].errcode
);
696 * Check how we exited from the previous loop.
697 * If tempaddrinfo is equal to NULL, it means that all
698 * the connect() attempts failed. Construct an
701 if (i
== numaddrinfos
)
703 int same_error_for_all
;
709 * Sort the statuses to group together categories
710 * of errors, errors within categories, and
711 * address families within error sets.
713 qsort(addrs_to_try
, numaddrinfos
, sizeof *addrs_to_try
,
714 compare_addrs_to_try_by_status
);
717 * Are all the errors the same?
719 same_error_for_all
= 1;
720 first_error
= addrs_to_try
[0].errcode
;
721 for (i
= 1; i
< numaddrinfos
; i
++)
723 if (addrs_to_try
[i
].errcode
!= first_error
)
725 same_error_for_all
= 0;
730 if (same_error_for_all
) {
732 * Yes. No need to show the IP
735 if (addrs_to_try
[0].errtype
== SOCK_CONNERR
) {
737 * Connection error; note that
738 * the daemon might not be set
739 * up correctly, or set up at all.
741 sock_fmterrmsg(errbuf
, errbuflen
,
742 addrs_to_try
[0].errcode
,
743 "Is the server properly installed? Cannot connect to %s",
746 sock_fmterrmsg(errbuf
, errbuflen
,
747 addrs_to_try
[0].errcode
,
748 "Cannot connect to %s", host
);
752 * Show all the errors and the IP addresses
753 * to which they apply.
759 snprintf(errbuf
, errbuflen
,
760 "Connect to %s failed: ", host
);
762 msglen
= strlen(errbuf
);
763 errbufptr
= errbuf
+ msglen
;
764 bufspaceleft
= errbuflen
- msglen
;
766 for (i
= 0; i
< numaddrinfos
&&
767 addrs_to_try
[i
].errcode
!= SOCK_NOERR
;
771 * Get the string for the address
772 * and port that got this error.
774 sock_getascii_addrport((struct sockaddr_storage
*) addrs_to_try
[i
].info
->ai_addr
,
775 errbufptr
, (int)bufspaceleft
,
776 NULL
, 0, NI_NUMERICHOST
, NULL
, 0);
777 msglen
= strlen(errbuf
);
778 errbufptr
= errbuf
+ msglen
;
779 bufspaceleft
= errbuflen
- msglen
;
781 if (i
+ 1 < numaddrinfos
&&
782 addrs_to_try
[i
+ 1].errcode
== addrs_to_try
[i
].errcode
)
785 * There's another error
786 * after this, and it has
787 * the same error code.
789 * Append a comma, as the
790 * list of addresses with
791 * this error has another
794 snprintf(errbufptr
, bufspaceleft
,
800 * Either there are no
801 * more errors after this,
802 * or the next error is
806 * the message for tis
807 * error, followed by a
811 sock_fmterrmsg(errbufptr
,
813 addrs_to_try
[i
].errcode
,
815 msglen
= strlen(errbuf
);
816 errbufptr
= errbuf
+ msglen
;
817 bufspaceleft
= errbuflen
- msglen
;
819 if (i
+ 1 < numaddrinfos
&&
820 addrs_to_try
[i
+ 1].errcode
!= SOCK_NOERR
)
830 msglen
= strlen(errbuf
);
831 errbufptr
= errbuf
+ msglen
;
832 bufspaceleft
= errbuflen
- msglen
;
836 return INVALID_SOCKET
;
847 * \brief Closes the present (TCP and UDP) socket connection.
849 * This function sends a shutdown() on the socket in order to disable send() calls
850 * (while recv() ones are still allowed). Then, it closes the socket.
852 * \param sock: the socket identifier of the connection that has to be closed.
854 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
855 * error message. This buffer has to be at least 'errbuflen' in length.
856 * It can be NULL; in this case the error cannot be printed.
858 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
859 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
861 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
862 * in the 'errbuf' variable.
864 int sock_close(PCAP_SOCKET sock
, char *errbuf
, int errbuflen
)
867 * SHUT_WR: subsequent calls to the send function are disallowed.
868 * For TCP sockets, a FIN will be sent after all data is sent and
869 * acknowledged by the Server.
871 if (shutdown(sock
, SHUT_WR
))
873 sock_geterrmsg(errbuf
, errbuflen
, "shutdown() failed");
874 /* close the socket anyway */
884 * gai_strerror() has some problems:
886 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
887 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
888 * thread-safe, so an implementation might use a static buffer
889 * for unknown error codes;
890 * 3) the error message for the most likely error, EAI_NONAME, is
891 * truly horrible on several platforms ("nodename nor servname
892 * provided, or not known"? It's typically going to be "not
893 * known", not "oopsie, I passed null pointers for the host name
894 * and service name", not to mention they forgot the "neither");
896 * so we roll our own.
899 get_gai_errstring(char *errbuf
, int errbuflen
, const char *prefix
, int err
,
900 const char *hostname
, const char *portname
)
902 char hostport
[PCAP_ERRBUF_SIZE
];
904 if (hostname
!= NULL
&& portname
!= NULL
)
905 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host and port %s:%s",
907 else if (hostname
!= NULL
)
908 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "host %s",
910 else if (portname
!= NULL
)
911 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "port %s",
914 snprintf(hostport
, PCAP_ERRBUF_SIZE
, "<no host or port!>");
917 #ifdef EAI_ADDRFAMILY
919 snprintf(errbuf
, errbuflen
,
920 "%sAddress family for %s not supported",
926 snprintf(errbuf
, errbuflen
,
927 "%s%s could not be resolved at this time",
932 snprintf(errbuf
, errbuflen
,
933 "%sThe ai_flags parameter for looking up %s had an invalid value",
938 snprintf(errbuf
, errbuflen
,
939 "%sA non-recoverable error occurred when attempting to resolve %s",
944 snprintf(errbuf
, errbuflen
,
945 "%sThe address family for looking up %s was not recognized",
950 snprintf(errbuf
, errbuflen
,
951 "%sOut of memory trying to allocate storage when looking up %s",
956 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
958 * RFC 3493 has only EAI_NONAME.
960 * Some implementations define EAI_NODATA and EAI_NONAME
961 * to the same value, others don't. If EAI_NODATA is
962 * defined and isn't the same as EAI_NONAME, we handle
965 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
967 snprintf(errbuf
, errbuflen
,
968 "%sNo address associated with %s",
974 snprintf(errbuf
, errbuflen
,
975 "%sThe %s couldn't be resolved",
980 snprintf(errbuf
, errbuflen
,
981 "%sThe service value specified when looking up %s as not recognized for the socket type",
986 snprintf(errbuf
, errbuflen
,
987 "%sThe socket type specified when looking up %s as not recognized",
994 * Assumed to be UN*X.
996 pcapint_fmt_errmsg_for_errno(errbuf
, errbuflen
, errno
,
997 "%sAn error occurred when looking up %s",
1004 snprintf(errbuf
, errbuflen
,
1005 "%sInvalid value for hints when looking up %s",
1012 snprintf(errbuf
, errbuflen
,
1013 "%sResolved protocol when looking up %s is unknown",
1020 snprintf(errbuf
, errbuflen
,
1021 "%sArgument buffer overflow when looking up %s",
1027 snprintf(errbuf
, errbuflen
,
1028 "%sgetaddrinfo() error %d when looking up %s",
1029 prefix
, err
, hostport
);
1035 * \brief Checks that the address, port and flags given are valid and it returns an 'addrinfo' structure.
1037 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
1038 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
1039 * If an error occurs, it writes the error message into 'errbuf'.
1041 * \param host: a pointer to a string identifying the host. It can be
1042 * a host name, a numeric literal address, or NULL or "" (useful
1043 * in case of a server socket which has to bind to all addresses).
1045 * \param port: a pointer to a user-allocated buffer containing the network port to use.
1047 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
1048 * addrinfo structure appropriately.
1050 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
1051 * (passed by reference), which will be allocated by this function and returned back to the caller.
1052 * This variable will be used in the next sockets calls.
1054 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1055 * error message. This buffer has to be at least 'errbuflen' in length.
1056 * It can be NULL; in this case the error cannot be printed.
1058 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1059 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1061 * \return a pointer to the first element in a list of addrinfo structures
1062 * if everything is fine, NULL if some errors occurred. The error message
1063 * is returned in the 'errbuf' variable.
1065 * \warning The list of addrinfo structures returned has to be deleted by
1066 * the programmer by calling freeaddrinfo() when it is no longer needed.
1068 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
1069 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
1070 * the programmer to look at that function in order to set the 'hints' variable appropriately.
1072 struct addrinfo
*sock_initaddress(const char *host
, const char *port
,
1073 struct addrinfo
*hints
, char *errbuf
, int errbuflen
)
1075 struct addrinfo
*addrinfo
;
1079 * We allow both the host and port to be null, but getaddrinfo()
1080 * is not guaranteed to do so; to handle that, if port is null,
1081 * we provide "0" as the port number.
1083 * This results in better error messages from get_gai_errstring(),
1084 * as those messages won't talk about a problem with the port if
1085 * no port was specified.
1087 retval
= getaddrinfo(host
, port
== NULL
? "0" : port
, hints
, &addrinfo
);
1092 * Determine whether the problem is that the host is bad.
1096 if (host
!= NULL
&& port
!= NULL
) {
1098 * Try with just a host, to distinguish
1099 * between "host is bad" and "port is
1104 try_retval
= getaddrinfo(host
, NULL
, hints
,
1106 if (try_retval
== 0) {
1108 * Worked with just the host,
1109 * so assume the problem is
1112 * Free up the address info first.
1114 freeaddrinfo(addrinfo
);
1115 get_gai_errstring(errbuf
, errbuflen
,
1116 "", retval
, NULL
, port
);
1119 * Didn't work with just the host,
1120 * so assume the problem is
1121 * with the host; we assume
1122 * the original error indicates
1123 * the underlying problem.
1125 get_gai_errstring(errbuf
, errbuflen
,
1126 "", retval
, host
, NULL
);
1130 * Either the host or port was null, so
1131 * there's nothing to determine; report
1132 * the error from the original call.
1134 get_gai_errstring(errbuf
, errbuflen
, "",
1135 retval
, host
, port
);
1141 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
1142 * addrinfo has more han one pointers
1146 * This software only supports PF_INET and PF_INET6.
1148 * XXX - should we just check that at least *one* address is
1149 * either PF_INET or PF_INET6, and, when using the list,
1150 * ignore all addresses that are neither? (What, no IPX
1153 if ((addrinfo
->ai_family
!= PF_INET
) &&
1154 (addrinfo
->ai_family
!= PF_INET6
))
1157 snprintf(errbuf
, errbuflen
, "getaddrinfo(): socket type not supported");
1158 freeaddrinfo(addrinfo
);
1163 * You can't do multicast (or broadcast) TCP.
1165 if ((addrinfo
->ai_socktype
== SOCK_STREAM
) &&
1166 (sock_ismcastaddr(addrinfo
->ai_addr
) == 0))
1169 snprintf(errbuf
, errbuflen
, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
1170 freeaddrinfo(addrinfo
);
1178 * \brief It sends the amount of data contained into 'buffer' on the given socket.
1180 * This function basically calls the send() socket function and it checks that all
1181 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
1182 * it writes the error message into 'errbuf'.
1183 * In case the socket buffer does not have enough space, it loops until all data
1186 * \param socket: the connected socket currently opened.
1188 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
1190 * \param size: number of bytes that have to be sent.
1192 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1193 * error message. This buffer has to be at least 'errbuflen' in length.
1194 * It can be NULL; in this case the error cannot be printed.
1196 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1197 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1199 * \return '0' if everything is fine, '-1' if an error other than
1200 * "connection reset" or "peer has closed the receive side" occurred,
1201 * '-2' if we got one of those errors.
1202 * For errors, an error message is returned in the 'errbuf' variable.
1204 int sock_send(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, const char *buffer
,
1205 size_t size
, char *errbuf
, int errbuflen
)
1214 snprintf(errbuf
, errbuflen
,
1215 "Can't send more than %u bytes with sock_send",
1220 remaining
= (int)size
;
1224 if (ssl
) return ssl_send(ssl
, buffer
, remaining
, errbuf
, errbuflen
);
1227 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1232 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
1233 * on errors on stream-oriented sockets when the other
1234 * end breaks the connection.
1235 * The EPIPE error is still returned.
1237 nsent
= send(sock
, buffer
, remaining
, MSG_NOSIGNAL
);
1239 nsent
= send(sock
, buffer
, remaining
, 0);
1241 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1246 * If the client closed the connection out from
1247 * under us, there's no need to log that as an
1253 errcode
= GetLastError();
1254 if (errcode
== WSAECONNRESET
||
1255 errcode
== WSAECONNABORTED
)
1258 * WSAECONNABORTED appears to be the error
1259 * returned in Winsock when you try to send
1260 * on a connection where the peer has closed
1265 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1269 if (errcode
== ECONNRESET
|| errcode
== EPIPE
)
1272 * EPIPE is what's returned on UN*X when
1273 * you try to send on a connection when
1274 * the peer has closed the receive side.
1278 sock_fmterrmsg(errbuf
, errbuflen
, errcode
,
1286 } while (remaining
!= 0);
1292 * \brief It copies the amount of data contained in 'data' into 'outbuf'.
1293 * and it checks for buffer overflows.
1295 * This function basically copies 'size' bytes of data contained in 'data'
1296 * into 'outbuf', starting at offset 'offset'. Before that, it checks that the
1297 * resulting buffer will not be larger than 'totsize'. Finally, it updates
1298 * the 'offset' variable in order to point to the first empty location of the buffer.
1300 * In case the function is called with 'checkonly' equal to 1, it does not copy
1301 * the data into the buffer. It only checks for buffer overflows and it updates the
1302 * 'offset' variable. This mode can be useful when the buffer already contains the
1303 * data (maybe because the producer writes directly into the target buffer), so
1304 * only the buffer overflow check has to be made.
1305 * In this case, both 'data' and 'outbuf' can be NULL values.
1307 * This function is useful in case the userland application does not know immediately
1308 * all the data it has to write into the socket. This function provides a way to create
1309 * the "stream" step by step, appending the new data to the old one. Then, when all the
1310 * data has been bufferized, the application can call the sock_send() function.
1312 * \param data: a void pointer to the data that has to be copied.
1314 * \param size: number of bytes that have to be copied.
1316 * \param outbuf: user-allocated buffer (of size 'totsize') into which data
1319 * \param offset: an index into 'outbuf' which keeps the location of its first
1322 * \param totsize: total size of the buffer into which data is being copied.
1324 * \param checkonly: '1' if we do not want to copy data into the buffer and we
1325 * want just do a buffer overflow control, '0' if data has to be copied as well.
1327 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1328 * error message. This buffer has to be at least 'errbuflen' in length.
1329 * It can be NULL; in this case the error cannot be printed.
1331 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1332 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1334 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
1335 * is returned in the 'errbuf' variable. When the function returns, 'outbuf' will
1336 * have the new string appended, and 'offset' will keep the length of that buffer.
1337 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
1339 * \warning This function assumes that the buffer in which data has to be stored is
1340 * large 'totbuf' bytes.
1342 * \warning In case of 'checkonly', be carefully to call this function *before* copying
1343 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
1345 int sock_bufferize(const void *data
, int size
, char *outbuf
, int *offset
, int totsize
, int checkonly
, char *errbuf
, int errbuflen
)
1347 if ((*offset
+ size
) > totsize
)
1350 snprintf(errbuf
, errbuflen
, "Not enough space in the temporary send buffer.");
1355 memcpy(outbuf
+ (*offset
), data
, size
);
1363 * \brief It waits on a connected socket and it manages to receive data.
1365 * This function basically calls the recv() socket function and it checks that no
1366 * error occurred. If that happens, it writes the error message into 'errbuf'.
1368 * This function changes its behavior according to the 'receiveall' flag: if we
1369 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
1370 * data is arrived. Otherwise, it returns the data currently available.
1372 * In case the socket does not have enough data available, it cycles on the recv()
1373 * until the requested data (of size 'size') is arrived.
1374 * In this case, it blocks until the number of bytes read is equal to 'size'.
1376 * \param sock: the connected socket currently opened.
1378 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
1380 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
1381 * that we are expecting to be read.
1385 * SOCK_RECEIVALL_XXX:
1387 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
1388 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
1389 * received (in case the socket does not have enough data available).
1393 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
1394 * and return an error on any subsequent read that returns 0;
1395 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
1397 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1398 * error message. This buffer has to be at least 'errbuflen' in length.
1399 * It can be NULL; in this case the error cannot be printed.
1401 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1402 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1404 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
1405 * The error message is returned in the 'errbuf' variable.
1408 int sock_recv(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
, size_t size
,
1409 int flags
, char *errbuf
, int errbuflen
)
1412 char *bufp
= buffer
;
1424 snprintf(errbuf
, errbuflen
,
1425 "Can't read more than %u bytes with sock_recv",
1431 if (flags
& SOCK_MSG_PEEK
)
1432 recv_flags
|= MSG_PEEK
;
1434 bufp
= (char *) buffer
;
1435 remaining
= (int) size
;
1438 * We don't use MSG_WAITALL because it's not supported in
1442 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1443 nread
= fuzz_recv(bufp
, remaining
);
1444 #elif defined(HAVE_OPENSSL)
1448 * XXX - what about MSG_PEEK?
1450 nread
= ssl_recv(ssl
, bufp
, remaining
, errbuf
, errbuflen
);
1451 if (nread
== -2) return -1;
1454 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1456 nread
= recv(sock
, bufp
, remaining
, recv_flags
);
1465 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1471 if ((flags
& SOCK_EOF_IS_ERROR
) ||
1472 (remaining
!= (int) size
))
1475 * Either we've already read some data,
1476 * or we're always supposed to return
1481 snprintf(errbuf
, errbuflen
,
1482 "The other host terminated the connection.");
1491 * Do we want to read the amount requested, or just return
1494 if (!(flags
& SOCK_RECEIVEALL_YES
))
1497 * Just return what we got.
1511 * Receives a datagram from a socket.
1513 * Returns the size of the datagram on success or -1 on error.
1515 int sock_recv_dgram(PCAP_SOCKET sock
, SSL
*ssl _U_NOSSL_
, void *buffer
,
1516 size_t size
, char *errbuf
, int errbuflen
)
1520 struct msghdr message
;
1532 snprintf(errbuf
, errbuflen
,
1533 "Can't read more than %u bytes with sock_recv_dgram",
1543 snprintf(errbuf
, errbuflen
, "DTLS not implemented yet");
1549 * This should be a datagram socket, so we should get the
1550 * entire datagram in one recv() or recvmsg() call, and
1551 * don't need to loop.
1554 nread
= recv(sock
, buffer
, (int)size
, 0);
1555 if (nread
== SOCKET_ERROR
)
1558 * To quote the MSDN documentation for recv(),
1559 * "If the datagram or message is larger than
1560 * the buffer specified, the buffer is filled
1561 * with the first part of the datagram, and recv
1562 * generates the error WSAEMSGSIZE. For unreliable
1563 * protocols (for example, UDP) the excess data is
1566 * So if the message is bigger than the buffer
1567 * supplied to us, the excess data is discarded,
1568 * and we'll report an error.
1570 sock_fmterrmsg(errbuf
, errbuflen
, sock_geterrcode(),
1576 * The Single UNIX Specification says that a recv() on
1577 * a socket for a message-oriented protocol will discard
1578 * the excess data. It does *not* indicate that the
1579 * receive will fail with, for example, EMSGSIZE.
1581 * Therefore, we use recvmsg(), which appears to be
1582 * the only way to get a "message truncated" indication
1583 * when receiving a message for a message-oriented
1586 message
.msg_name
= NULL
; /* we don't care who it's from */
1587 message
.msg_namelen
= 0;
1588 iov
.iov_base
= buffer
;
1590 message
.msg_iov
= &iov
;
1591 message
.msg_iovlen
= 1;
1592 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1593 message
.msg_control
= NULL
; /* we don't care about control information */
1594 message
.msg_controllen
= 0;
1596 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1597 message
.msg_flags
= 0;
1599 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1600 nread
= fuzz_recv(buffer
, size
);
1602 nread
= recvmsg(sock
, &message
, 0);
1608 sock_geterrmsg(errbuf
, errbuflen
, "recv() failed");
1611 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1613 * XXX - Solaris supports this, but only if you ask for the
1614 * X/Open version of recvmsg(); should we use that, or will
1615 * that cause other problems?
1617 if (message
.msg_flags
& MSG_TRUNC
)
1620 * Message was bigger than the specified buffer size.
1622 * Report this as an error, as the Microsoft documentation
1623 * implies we'd do in a similar case on Windows.
1625 snprintf(errbuf
, errbuflen
, "recv(): Message too long");
1628 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1632 * The size we're reading fits in an int, so the return value
1633 * will fit in an int.
1639 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1641 * This function is useful in case we receive a message we cannot understand (e.g.
1642 * wrong version number when receiving a network packet), so that we have to discard all
1643 * data before reading a new message.
1645 * This function will read 'size' bytes from the socket and discard them.
1646 * It defines an internal buffer in which data will be copied; however, in case
1647 * this buffer is not large enough, it will cycle in order to read everything as well.
1649 * \param sock: the connected socket currently opened.
1651 * \param size: number of bytes that have to be discarded.
1653 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1654 * error message. This buffer has to be at least 'errbuflen' in length.
1655 * It can be NULL; in this case the error cannot be printed.
1657 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1658 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1660 * \return '0' if everything is fine, '-1' if some errors occurred.
1661 * The error message is returned in the 'errbuf' variable.
1663 int sock_discard(PCAP_SOCKET sock
, SSL
*ssl
, int size
, char *errbuf
,
1666 #define TEMP_BUF_SIZE 32768
1668 char buffer
[TEMP_BUF_SIZE
]; /* network buffer, to be used when the message is discarded */
1671 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1672 * Our feeling is that a buffer if 32KB is enough for most of the application;
1673 * in case this is not enough, the "while" loop discards the message by calling the
1674 * sockrecv() several times.
1675 * We do not want to create a bigger variable because this causes the program to exit on
1676 * some platforms (e.g. BSD)
1678 while (size
> TEMP_BUF_SIZE
)
1680 if (sock_recv(sock
, ssl
, buffer
, TEMP_BUF_SIZE
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1683 size
-= TEMP_BUF_SIZE
;
1687 * If there is still data to be discarded
1688 * In this case, the data can fit into the temporary buffer
1692 if (sock_recv(sock
, ssl
, buffer
, size
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
1700 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1702 * This function is useful after an accept() call in order to check if the connecting
1703 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1704 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1705 * against this host list, and it returns '0' is the host is included in this list.
1707 * \param hostlist: pointer to a string that contains the list of the allowed host.
1709 * \param sep: a string that keeps the separators used between the hosts (for example the
1710 * space character) in the host list.
1712 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1714 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1715 * error message. This buffer has to be at least 'errbuflen' in length.
1716 * It can be NULL; in this case the error cannot be printed.
1718 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1719 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1721 * \return It returns:
1722 * - '1' if the host list is empty
1723 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1724 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1725 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1727 int sock_check_hostlist(const char *hostlist
, const char *sep
, struct sockaddr_storage
*from
, char *errbuf
, int errbuflen
)
1729 /* checks if the connecting host is among the ones allowed */
1730 if ((hostlist
) && (hostlist
[0]))
1732 char *token
; /* temp, needed to separate items into the hostlist */
1733 struct addrinfo
*addrinfo
, *ai_next
;
1736 int getaddrinfo_failed
= 0;
1739 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1740 * So, we have to create a new temporary string in which the original content is kept
1742 temphostlist
= strdup(hostlist
);
1743 if (temphostlist
== NULL
)
1745 sock_geterrmsg(errbuf
, errbuflen
,
1746 "sock_check_hostlist(), malloc() failed");
1750 token
= pcapint_strtok_r(temphostlist
, sep
, &lasts
);
1752 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1755 while (token
!= NULL
)
1757 struct addrinfo hints
;
1761 memset(&hints
, 0, sizeof(struct addrinfo
));
1762 hints
.ai_family
= PF_UNSPEC
;
1763 hints
.ai_socktype
= SOCK_STREAM
;
1765 retval
= getaddrinfo(token
, NULL
, &hints
, &addrinfo
);
1769 get_gai_errstring(errbuf
, errbuflen
,
1770 "Allowed host list error: ",
1771 retval
, token
, NULL
);
1774 * Note that at least one call to getaddrinfo()
1777 getaddrinfo_failed
= 1;
1779 /* Get next token */
1780 token
= pcapint_strtok_r(NULL
, sep
, &lasts
);
1784 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1788 if (sock_cmpaddr(from
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
1791 freeaddrinfo(addrinfo
);
1796 * If we are here, it means that the current address does not matches
1797 * Let's try with the next one in the header chain
1799 ai_next
= ai_next
->ai_next
;
1802 freeaddrinfo(addrinfo
);
1805 /* Get next token */
1806 token
= pcapint_strtok_r(NULL
, sep
, &lasts
);
1811 freeaddrinfo(addrinfo
);
1817 if (getaddrinfo_failed
) {
1819 * At least one getaddrinfo() call failed;
1820 * treat that as an error, so rpcapd knows
1821 * that it should log it locally as well
1822 * as telling the client about it.
1827 * All getaddrinfo() calls succeeded, but
1828 * the host wasn't in the list.
1831 snprintf(errbuf
, errbuflen
, "The host is not in the allowed host list. Connection refused.");
1836 /* No hostlist, so we have to return 'empty list' */
1841 * \brief Compares two addresses contained into two sockaddr_storage structures.
1843 * This function is useful to compare two addresses, given their internal representation,
1844 * i.e. an sockaddr_storage structure.
1846 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1847 * sockaddr_in6, properly casted in order to be compliant to the function interface.
1849 * This function will return '0' if the two addresses matches, '-1' if not.
1851 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1852 * accept() call), containing the first address to compare.
1854 * \param second: a sockaddr_storage structure containing the second address to compare.
1856 * \return '0' if the addresses are equal, '-1' if they are different.
1858 int sock_cmpaddr(struct sockaddr_storage
*first
, struct sockaddr_storage
*second
)
1860 if (first
->ss_family
== second
->ss_family
)
1862 if (first
->ss_family
== AF_INET
)
1864 if (memcmp(&(((struct sockaddr_in
*) first
)->sin_addr
),
1865 &(((struct sockaddr_in
*) second
)->sin_addr
),
1866 sizeof(struct in_addr
)) == 0)
1869 else /* address family is AF_INET6 */
1871 if (memcmp(&(((struct sockaddr_in6
*) first
)->sin6_addr
),
1872 &(((struct sockaddr_in6
*) second
)->sin6_addr
),
1873 sizeof(struct in6_addr
)) == 0)
1882 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1884 * It is used to return the address and port the server picked for our socket on the local machine.
1886 * - connected sockets
1889 * On unconnected client sockets it does not work because the system dynamically chooses a port
1890 * only when the socket calls a send() call.
1892 * \param sock: the connected socket currently opened.
1894 * \param address: it contains the address that will be returned by the function. This buffer
1895 * must be properly allocated by the user. The address can be either literal or numeric depending
1896 * on the value of 'Flags'.
1898 * \param addrlen: the length of the 'address' buffer.
1900 * \param port: it contains the port that will be returned by the function. This buffer
1901 * must be properly allocated by the user.
1903 * \param portlen: the length of the 'port' buffer.
1905 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1906 * that determine if the resulting address must be in numeric / literal form, and so on.
1908 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1909 * error message. This buffer has to be at least 'errbuflen' in length.
1910 * It can be NULL; in this case the error cannot be printed.
1912 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1913 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1915 * \return It returns '-1' if this function succeeds, '0' otherwise.
1916 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1917 * In any case, the returned strings are '0' terminated.
1919 * \warning If the socket is using a connectionless protocol, the address may not be available
1920 * until I/O occurs on the socket.
1922 int sock_getmyinfo(PCAP_SOCKET sock
, char *address
, int addrlen
, char *port
,
1923 int portlen
, int flags
, char *errbuf
, int errbuflen
)
1925 struct sockaddr_storage mysockaddr
;
1926 socklen_t sockaddrlen
;
1929 sockaddrlen
= sizeof(struct sockaddr_storage
);
1931 if (getsockname(sock
, (struct sockaddr
*) &mysockaddr
, &sockaddrlen
) == -1)
1933 sock_geterrmsg(errbuf
, errbuflen
, "getsockname() failed");
1937 /* Returns the numeric address of the host that triggered the error */
1938 return sock_getascii_addrport(&mysockaddr
, address
, addrlen
, port
, portlen
, flags
, errbuf
, errbuflen
);
1942 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1944 * This function is basically an extended version of the inet_ntop(), which does not exist in
1945 * Winsock because the same result can be obtained by using the getnameinfo().
1946 * However, differently from inet_ntop(), this function is able to return also literal names
1947 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1949 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1950 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1951 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1952 * a standard IPv6 address like "::1".
1954 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1955 * are the ones allowed in the standard getnameinfo() socket function.
1957 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1958 * need to be translated from network form into the presentation form. This structure must be
1959 * zero-ed prior using it, and the address family field must be filled with the proper value.
1960 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1961 * calling this function.
1963 * \param address: it contains the address that will be returned by the function. This buffer
1964 * must be properly allocated by the user. The address can be either literal or numeric depending
1965 * on the value of 'Flags'.
1967 * \param addrlen: the length of the 'address' buffer.
1969 * \param port: it contains the port that will be returned by the function. This buffer
1970 * must be properly allocated by the user.
1972 * \param portlen: the length of the 'port' buffer.
1974 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1975 * that determine if the resulting address must be in numeric / literal form, and so on.
1977 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1978 * error message. This buffer has to be at least 'errbuflen' in length.
1979 * It can be NULL; in this case the error cannot be printed.
1981 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1982 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1984 * \return It returns '-1' if this function succeeds, '0' otherwise.
1985 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1987 * In any case, the returned strings are '0' terminated.
1989 int sock_getascii_addrport(const struct sockaddr_storage
*sockaddr
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, size_t errbuflen
)
1991 socklen_t sockaddrlen
;
1992 int retval
; /* Variable that keeps the return value; */
1997 if (sockaddr
->ss_family
== AF_INET
)
1998 sockaddrlen
= sizeof(struct sockaddr_in
);
2000 sockaddrlen
= sizeof(struct sockaddr_in6
);
2002 sockaddrlen
= sizeof(struct sockaddr_storage
);
2005 if ((flags
& NI_NUMERICHOST
) == 0) /* Check that we want literal names */
2007 if ((sockaddr
->ss_family
== AF_INET6
) &&
2008 (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))
2011 pcapint_strlcpy(address
, SOCKET_NAME_NULL_DAD
, addrlen
);
2016 if (getnameinfo((struct sockaddr
*) sockaddr
, sockaddrlen
, address
, addrlen
, port
, portlen
, flags
) != 0)
2018 /* If the user wants to receive an error message */
2021 sock_geterrmsg(errbuf
, errbuflen
,
2022 "getnameinfo() failed");
2023 errbuf
[errbuflen
- 1] = 0;
2028 pcapint_strlcpy(address
, SOCKET_NO_NAME_AVAILABLE
, addrlen
);
2029 address
[addrlen
- 1] = 0;
2034 pcapint_strlcpy(port
, SOCKET_NO_PORT_AVAILABLE
, portlen
);
2035 port
[portlen
- 1] = 0;
2045 * \brief It translates an address from the 'presentation' form into the 'network' form.
2047 * This function basically replaces inet_pton(), which does not exist in Winsock because
2048 * the same result can be obtained by using the getaddrinfo().
2049 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
2050 * like in inet_pton() ) and a literal name (e.g. 'localhost').
2052 * This function does the reverse job of sock_getascii_addrport().
2054 * \param address: a zero-terminated string which contains the name you have to
2055 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
2057 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
2058 * 'network' form of the requested address.
2060 * \param addr_family: a constant which can assume the following values:
2061 * - 'AF_INET' if we want to ping an IPv4 host
2062 * - 'AF_INET6' if we want to ping an IPv6 host
2063 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
2065 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
2066 * error message. This buffer has to be at least 'errbuflen' in length.
2067 * It can be NULL; in this case the error cannot be printed.
2069 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
2070 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
2072 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
2073 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
2074 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
2075 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
2076 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
2078 * \warning The sockaddr_storage structure MUST be allocated by the user.
2080 int sock_present2network(const char *address
, struct sockaddr_storage
*sockaddr
, int addr_family
, char *errbuf
, int errbuflen
)
2082 struct addrinfo
*addrinfo
;
2083 struct addrinfo hints
;
2085 memset(&hints
, 0, sizeof(hints
));
2087 hints
.ai_family
= addr_family
;
2089 addrinfo
= sock_initaddress(address
, "22222" /* fake port */, &hints
,
2091 if (addrinfo
== NULL
)
2094 if (addrinfo
->ai_family
== PF_INET
)
2095 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in
));
2097 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in6
));
2099 if (addrinfo
->ai_next
!= NULL
)
2101 freeaddrinfo(addrinfo
);
2104 snprintf(errbuf
, errbuflen
, "More than one socket requested; using the first one returned");
2108 freeaddrinfo(addrinfo
);