2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the Politecnico di Torino nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The goal of this file is to provide a common set of primitives for socket
43 * Although the socket interface defined in the RFC 2553 (and its updates)
44 * is excellent, there are still differences between the behavior of those
45 * routines on UN*X and Windows, and between UN*Xes.
47 * These calls provide an interface similar to the socket interface, but
48 * that hides the differences between operating systems. It does not
49 * attempt to significantly improve on the socket interface in other
56 #include <errno.h> /* for the errno variable */
57 #include <stdio.h> /* for the stderr file */
58 #include <stdlib.h> /* for malloc() and free() */
62 #define INT_MAX 2147483647
65 #include "portability.h"
66 #include "sockutils.h"
70 * Winsock initialization.
72 * Ask for WinSock 2.2.
74 #define WINSOCK_MAJOR_VERSION 2
75 #define WINSOCK_MINOR_VERSION 2
77 static int sockcount
= 0; /*!< Variable that allows calling the WSAStartup() only one time */
80 /* Some minor differences between UNIX and Win32 */
82 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
85 /* Size of the buffer that has to keep error messages */
86 #define SOCK_ERRBUF_SIZE 1024
88 /* Constants; used in order to keep strings here */
89 #define SOCKET_NO_NAME_AVAILABLE "No name available"
90 #define SOCKET_NO_PORT_AVAILABLE "No port available"
91 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
93 /****************************************************
95 * Locally defined functions *
97 ****************************************************/
99 static int sock_ismcastaddr(const struct sockaddr
*saddr
);
101 /****************************************************
105 ****************************************************/
108 * \brief It retrieves the error message after an error occurred in the socket interface.
110 * This function is defined because of the different way errors are returned in UNIX
111 * and Win32. This function provides a consistent way to retrieve the error message
112 * (after a socket error occurred) on all the platforms.
114 * \param caller: a pointer to a user-allocated string which contains a message that has
115 * to be printed *before* the true error message. It could be, for example, 'this error
116 * comes from the recv() call at line 31'. It may be NULL.
118 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
119 * error message. This buffer has to be at least 'errbuflen' in length.
120 * It can be NULL; in this case the error cannot be printed.
122 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
123 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
125 * \return No return values. The error message is returned in the 'string' parameter.
127 void sock_geterror(const char *caller
, char *errbuf
, int errbuflen
)
132 TCHAR message
[SOCK_ERRBUF_SIZE
]; /* It will be char (if we're using ascii) or wchar_t (if we're using unicode) */
137 code
= GetLastError();
139 retval
= FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
|
140 FORMAT_MESSAGE_MAX_WIDTH_MASK
,
141 NULL
, code
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
142 message
, sizeof(message
) / sizeof(TCHAR
), NULL
);
146 if ((caller
) && (*caller
))
147 pcap_snprintf(errbuf
, errbuflen
, "%sUnable to get the exact error message", caller
);
149 pcap_snprintf(errbuf
, errbuflen
, "Unable to get the exact error message");
154 if ((caller
) && (*caller
))
155 pcap_snprintf(errbuf
, errbuflen
, "%s%s (code %d)", caller
, message
, code
);
157 pcap_snprintf(errbuf
, errbuflen
, "%s (code %d)", message
, code
);
165 message
= strerror(errno
);
167 if ((caller
) && (*caller
))
168 pcap_snprintf(errbuf
, errbuflen
, "%s%s (code %d)", caller
, message
, errno
);
170 pcap_snprintf(errbuf
, errbuflen
, "%s (code %d)", message
, errno
);
175 * \brief It initializes sockets.
177 * This function is pretty useless on UNIX, since socket initialization is not required.
178 * However it is required on Win32. In UNIX, this function appears to be completely empty.
180 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
181 * error message. This buffer has to be at least 'errbuflen' in length.
182 * It can be NULL; in this case the error cannot be printed.
184 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
185 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
187 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
188 * in the 'errbuf' variable.
190 int sock_init(char *errbuf
, int errbuflen
)
195 WSADATA wsaData
; /* helper variable needed to initialize Winsock */
197 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION
,
198 WINSOCK_MINOR_VERSION
), &wsaData
) != 0)
201 pcap_snprintf(errbuf
, errbuflen
, "Failed to initialize Winsock\n");
216 * \brief It deallocates sockets.
218 * This function is pretty useless on UNIX, since socket deallocation is not required.
219 * However it is required on Win32. In UNIX, this function appears to be completely empty.
221 * \return No error values.
223 void sock_cleanup(void)
234 * \brief It checks if the sockaddr variable contains a multicast address.
236 * \return '0' if the address is multicast, '-1' if it is not.
238 static int sock_ismcastaddr(const struct sockaddr
*saddr
)
240 if (saddr
->sa_family
== PF_INET
)
242 struct sockaddr_in
*saddr4
= (struct sockaddr_in
*) saddr
;
243 if (IN_MULTICAST(ntohl(saddr4
->sin_addr
.s_addr
))) return 0;
248 struct sockaddr_in6
*saddr6
= (struct sockaddr_in6
*) saddr
;
249 if (IN6_IS_ADDR_MULTICAST(&saddr6
->sin6_addr
)) return 0;
255 * \brief It initializes a network connection both from the client and the server side.
257 * In case of a client socket, this function calls socket() and connect().
258 * In the meanwhile, it checks for any socket error.
259 * If an error occurs, it writes the error message into 'errbuf'.
261 * In case of a server socket, the function calls socket(), bind() and listen().
263 * This function is usually preceeded by the sock_initaddress().
265 * \param addrinfo: pointer to an addrinfo variable which will be used to
266 * open the socket and such. This variable is the one returned by the previous call to
267 * sock_initaddress().
269 * \param server: '1' if this is a server socket, '0' otherwise.
271 * \param nconn: number of the connections that are allowed to wait into the listen() call.
272 * This value has no meanings in case of a client socket.
274 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
275 * error message. This buffer has to be at least 'errbuflen' in length.
276 * It can be NULL; in this case the error cannot be printed.
278 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
279 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
281 * \return the socket that has been opened (that has to be used in the following sockets calls)
282 * if everything is fine, '0' if some errors occurred. The error message is returned
283 * in the 'errbuf' variable.
285 SOCKET
sock_open(struct addrinfo
*addrinfo
, int server
, int nconn
, char *errbuf
, int errbuflen
)
289 sock
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
);
292 sock_geterror("socket(): ", errbuf
, errbuflen
);
297 /* This is a server socket */
302 * Force the use of IPv6-only addresses; in BSD you can accept both v4 and v6
303 * connections if you have a "NULL" pointer as the nodename in the getaddrinfo()
304 * This behavior is not clear in the RFC 2553, so each system implements the
305 * bind() differently from this point of view
307 if (addrinfo
->ai_family
== PF_INET6
)
311 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_BINDV6ONLY
, (char *)&on
, sizeof (int)) == -1)
314 pcap_snprintf(errbuf
, errbuflen
, "setsockopt(IPV6_BINDV6ONLY)");
320 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
321 if (bind(sock
, addrinfo
->ai_addr
, (int) addrinfo
->ai_addrlen
) != 0)
323 sock_geterror("bind(): ", errbuf
, errbuflen
);
327 if (addrinfo
->ai_socktype
== SOCK_STREAM
)
328 if (listen(sock
, nconn
) == -1)
330 sock_geterror("listen(): ", errbuf
, errbuflen
);
334 /* server side ended */
337 else /* we're the client */
339 struct addrinfo
*tempaddrinfo
;
343 tempaddrinfo
= addrinfo
;
345 bufspaceleft
= errbuflen
;
349 * We have to loop though all the addinfo returned.
350 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
351 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
356 if (connect(sock
, tempaddrinfo
->ai_addr
, (int) tempaddrinfo
->ai_addrlen
) == -1)
360 char SocketErrorMessage
[SOCK_ERRBUF_SIZE
];
363 * We have to retrieve the error message before any other socket call completes, otherwise
364 * the error message is lost
366 sock_geterror(NULL
, SocketErrorMessage
, sizeof(SocketErrorMessage
));
368 /* Returns the numeric address of the host that triggered the error */
369 sock_getascii_addrport((struct sockaddr_storage
*) tempaddrinfo
->ai_addr
, TmpBuffer
, sizeof(TmpBuffer
), NULL
, 0, NI_NUMERICHOST
, TmpBuffer
, sizeof(TmpBuffer
));
371 pcap_snprintf(errbufptr
, bufspaceleft
,
372 "Is the server properly installed on %s? connect() failed: %s", TmpBuffer
, SocketErrorMessage
);
374 /* In case more then one 'connect' fails, we manage to keep all the error messages */
375 msglen
= strlen(errbufptr
);
377 errbufptr
[msglen
] = ' ';
378 errbufptr
[msglen
+ 1] = 0;
380 bufspaceleft
= bufspaceleft
- (msglen
+ 1);
381 errbufptr
+= (msglen
+ 1);
383 tempaddrinfo
= tempaddrinfo
->ai_next
;
390 * Check how we exit from the previous loop
391 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
393 if (tempaddrinfo
== NULL
)
404 * \brief Closes the present (TCP and UDP) socket connection.
406 * This function sends a shutdown() on the socket in order to disable send() calls
407 * (while recv() ones are still allowed). Then, it closes the socket.
409 * \param sock: the socket identifier of the connection that has to be closed.
411 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
412 * error message. This buffer has to be at least 'errbuflen' in length.
413 * It can be NULL; in this case the error cannot be printed.
415 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
416 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
418 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
419 * in the 'errbuf' variable.
421 int sock_close(SOCKET sock
, char *errbuf
, int errbuflen
)
424 * SHUT_WR: subsequent calls to the send function are disallowed.
425 * For TCP sockets, a FIN will be sent after all data is sent and
426 * acknowledged by the Server.
428 if (shutdown(sock
, SHUT_WR
))
430 sock_geterror("shutdown(): ", errbuf
, errbuflen
);
431 /* close the socket anyway */
441 * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
443 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
444 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
445 * If an error occurs, it writes the error message into 'errbuf'.
447 * \param host: a pointer to a string identifying the host. It can be
448 * a host name, a numeric literal address, or NULL or "" (useful
449 * in case of a server socket which has to bind to all addresses).
451 * \param port: a pointer to a user-allocated buffer containing the network port to use.
453 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
454 * addrinfo structure appropriately.
456 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
457 * (passed by reference), which will be allocated by this function and returned back to the caller.
458 * This variable will be used in the next sockets calls.
460 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
461 * error message. This buffer has to be at least 'errbuflen' in length.
462 * It can be NULL; in this case the error cannot be printed.
464 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
465 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
467 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
468 * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
469 * returned into the addrinfo parameter.
471 * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
472 * it is no longer needed.
474 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
475 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
476 * the programmer to look at that function in order to set the 'hints' variable appropriately.
478 int sock_initaddress(const char *host
, const char *port
,
479 struct addrinfo
*hints
, struct addrinfo
**addrinfo
, char *errbuf
, int errbuflen
)
483 retval
= getaddrinfo(host
, port
, hints
, addrinfo
);
487 * if the getaddrinfo() fails, you have to use gai_strerror(), instead of using the standard
488 * error routines (errno) in UNIX; Winsock suggests using the GetLastError() instead.
493 sock_geterror("getaddrinfo(): ", errbuf
, errbuflen
);
495 pcap_snprintf(errbuf
, errbuflen
, "getaddrinfo() %s", gai_strerror(retval
));
501 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
502 * addrinfo has more han one pointers
506 * This software only supports PF_INET and PF_INET6.
508 * XXX - should we just check that at least *one* address is
509 * either PF_INET or PF_INET6, and, when using the list,
510 * ignore all addresses that are neither? (What, no IPX
513 if (((*addrinfo
)->ai_family
!= PF_INET
) &&
514 ((*addrinfo
)->ai_family
!= PF_INET6
))
517 pcap_snprintf(errbuf
, errbuflen
, "getaddrinfo(): socket type not supported");
522 * You can't do multicast (or broadcast) TCP.
524 if (((*addrinfo
)->ai_socktype
== SOCK_STREAM
) &&
525 (sock_ismcastaddr((*addrinfo
)->ai_addr
) == 0))
528 pcap_snprintf(errbuf
, errbuflen
, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
536 * \brief It sends the amount of data contained into 'buffer' on the given socket.
538 * This function basically calls the send() socket function and it checks that all
539 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
540 * it writes the error message into 'errbuf'.
541 * In case the socket buffer does not have enough space, it loops until all data
544 * \param socket: the connected socket currently opened.
546 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
548 * \param size: number of bytes that have to be sent.
550 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
551 * error message. This buffer has to be at least 'errbuflen' in length.
552 * It can be NULL; in this case the error cannot be printed.
554 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
555 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
557 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
558 * in the 'errbuf' variable.
560 int sock_send(SOCKET sock
, const char *buffer
, int size
, char *errbuf
, int errbuflen
)
567 * Another pain... in Linux there's this flag
569 * Requests not to send SIGPIPE on errors on stream-oriented
570 * sockets when the other end breaks the connection.
571 * The EPIPE error is still returned.
573 nsent
= send(sock
, buffer
, size
, MSG_NOSIGNAL
);
575 nsent
= send(sock
, buffer
, size
, 0);
580 sock_geterror("send(): ", errbuf
, errbuflen
);
595 * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
596 * and it checks for buffer overflows.
598 * This function basically copies 'size' bytes of data contained into 'buffer'
599 * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
600 * resulting buffer will not be larger than 'totsize'. Finally, it updates
601 * the 'offset' variable in order to point to the first empty location of the buffer.
603 * In case the function is called with 'checkonly' equal to 1, it does not copy
604 * the data into the buffer. It only checks for buffer overflows and it updates the
605 * 'offset' variable. This mode can be useful when the buffer already contains the
606 * data (maybe because the producer writes directly into the target buffer), so
607 * only the buffer overflow check has to be made.
608 * In this case, both 'buffer' and 'tempbuf' can be NULL values.
610 * This function is useful in case the userland application does not know immediately
611 * all the data it has to write into the socket. This function provides a way to create
612 * the "stream" step by step, appending the new data to the old one. Then, when all the
613 * data has been bufferized, the application can call the sock_send() function.
615 * \param buffer: a char pointer to a user-allocated buffer that keeps the data
616 * that has to be copied.
618 * \param size: number of bytes that have to be copied.
620 * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
623 * \param offset: an index into 'tempbuf' which keeps the location of its first
626 * \param totsize: total size of the buffer in which data is being copied.
628 * \param checkonly: '1' if we do not want to copy data into the buffer and we
629 * want just do a buffer ovreflow control, '0' if data has to be copied as well.
631 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
632 * error message. This buffer has to be at least 'errbuflen' in length.
633 * It can be NULL; in this case the error cannot be printed.
635 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
636 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
638 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
639 * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
640 * have the new string appended, and 'offset' will keep the length of that buffer.
641 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
643 * \warning This function assumes that the buffer in which data has to be stored is
644 * large 'totbuf' bytes.
646 * \warning In case of 'checkonly', be carefully to call this function *before* copying
647 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
649 int sock_bufferize(const char *buffer
, int size
, char *tempbuf
, int *offset
, int totsize
, int checkonly
, char *errbuf
, int errbuflen
)
651 if ((*offset
+ size
) > totsize
)
654 pcap_snprintf(errbuf
, errbuflen
, "Not enough space in the temporary send buffer.");
659 memcpy(tempbuf
+ (*offset
), buffer
, size
);
667 * \brief It waits on a connected socket and it manages to receive data.
669 * This function basically calls the recv() socket function and it checks that no
670 * error occurred. If that happens, it writes the error message into 'errbuf'.
672 * This function changes its behavior according to the 'receiveall' flag: if we
673 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
674 * data is arrived. Otherwise, it returns the data currently available.
676 * In case the socket does not have enough data available, it cycles on the recv()
677 * until the requested data (of size 'size') is arrived.
678 * In this case, it blocks until the number of bytes read is equal to 'size'.
680 * \param sock: the connected socket currently opened.
682 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
684 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
685 * that we are expecting to be read.
687 * \param receiveall: if '0' (or SOCK_RECEIVEALL_NO), it returns as soon as some data
688 * is ready; otherwise, (or SOCK_RECEIVEALL_YES) it waits until 'size' data has been
689 * received (in case the socket does not have enough data available).
691 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
692 * error message. This buffer has to be at least 'errbuflen' in length.
693 * It can be NULL; in this case the error cannot be printed.
695 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
696 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
698 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
699 * The error message is returned in the 'errbuf' variable.
703 * On UN*X, recv() returns ssize_t.
704 * On Windows, there *is* no ssize_t, and it returns an int.
705 * Define ssize_t as int on Windows so we can use it as the return value
712 int sock_recv(SOCKET sock
, void *buffer
, size_t size
, int receiveall
,
713 char *errbuf
, int errbuflen
)
721 SOCK_ASSERT("I have been requested to read zero bytes", 1);
726 pcap_snprintf(errbuf
, errbuflen
, "Can't read more than %u bytes with sock_recv",
731 bufp
= (char *) buffer
;
732 remaining
= (int) size
;
735 * We don't use MSG_WAITALL because it's not supported in
739 nread
= recv(sock
, bufp
, remaining
, 0);
747 sock_geterror("recv(): ", errbuf
, errbuflen
);
755 pcap_snprintf(errbuf
, errbuflen
,
756 "The other host terminated the connection.");
762 * Do we want to read the amount requested, or just return
768 * Just return what we got.
782 * \brief It discards N bytes that are currently waiting to be read on the current socket.
784 * This function is useful in case we receive a message we cannot understand (e.g.
785 * wrong version number when receiving a network packet), so that we have to discard all
786 * data before reading a new message.
788 * This function will read 'size' bytes from the socket and discard them.
789 * It defines an internal buffer in which data will be copied; however, in case
790 * this buffer is not large enough, it will cycle in order to read everything as well.
792 * \param sock: the connected socket currently opened.
794 * \param size: number of bytes that have to be discarded.
796 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
797 * error message. This buffer has to be at least 'errbuflen' in length.
798 * It can be NULL; in this case the error cannot be printed.
800 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
801 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
803 * \return '0' if everything is fine, '-1' if some errors occurred.
804 * The error message is returned in the 'errbuf' variable.
806 int sock_discard(SOCKET sock
, int size
, char *errbuf
, int errbuflen
)
808 #define TEMP_BUF_SIZE 32768
810 char buffer
[TEMP_BUF_SIZE
]; /* network buffer, to be used when the message is discarded */
813 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
814 * Our feeling is that a buffer if 32KB is enough for most of the application;
815 * in case this is not enough, the "while" loop discards the message by calling the
816 * sockrecv() several times.
817 * We do not want to create a bigger variable because this causes the program to exit on
818 * some platforms (e.g. BSD)
820 while (size
> TEMP_BUF_SIZE
)
822 if (sock_recv(sock
, buffer
, TEMP_BUF_SIZE
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
825 size
-= TEMP_BUF_SIZE
;
829 * If there is still data to be discarded
830 * In this case, the data can fit into the temporary buffer
834 if (sock_recv(sock
, buffer
, size
, SOCK_RECEIVEALL_YES
, errbuf
, errbuflen
) == -1)
838 SOCK_ASSERT("I'm currently discarding data\n", 1);
844 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
846 * This function is useful after an accept() call in order to check if the connecting
847 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
848 * allowed host; this function checks the sockaddr_storage structure of the connecting host
849 * against this host list, and it returns '0' is the host is included in this list.
851 * \param hostlist: pointer to a string that contains the list of the allowed host.
853 * \param sep: a string that keeps the separators used between the hosts (for example the
854 * space character) in the host list.
856 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
858 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
859 * error message. This buffer has to be at least 'errbuflen' in length.
860 * It can be NULL; in this case the error cannot be printed.
862 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
863 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
865 * \return It returns:
866 * - '1' if the host list is empty
867 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
868 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
869 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
871 int sock_check_hostlist(char *hostlist
, const char *sep
, struct sockaddr_storage
*from
, char *errbuf
, int errbuflen
)
873 /* checks if the connecting host is among the ones allowed */
874 if ((hostlist
) && (hostlist
[0]))
876 char *token
; /* temp, needed to separate items into the hostlist */
877 struct addrinfo
*addrinfo
, *ai_next
;
882 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
883 * So, we have to create a new temporary string in which the original content is kept
885 temphostlist
= strdup(hostlist
);
886 if (temphostlist
== NULL
)
888 sock_geterror("sock_check_hostlist(), malloc() failed", errbuf
, errbuflen
);
892 token
= pcap_strtok_r(temphostlist
, sep
, &lasts
);
894 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
897 while (token
!= NULL
)
899 struct addrinfo hints
;
903 memset(&hints
, 0, sizeof(struct addrinfo
));
904 hints
.ai_family
= PF_UNSPEC
;
905 hints
.ai_socktype
= SOCK_STREAM
;
907 retval
= getaddrinfo(token
, "0", &hints
, &addrinfo
);
911 pcap_snprintf(errbuf
, errbuflen
, "getaddrinfo() %s", gai_strerror(retval
));
913 SOCK_ASSERT(errbuf
, 1);
916 token
= pcap_strtok_r(NULL
, sep
, &lasts
);
920 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
924 if (sock_cmpaddr(from
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
931 * If we are here, it means that the current address does not matches
932 * Let's try with the next one in the header chain
934 ai_next
= ai_next
->ai_next
;
937 freeaddrinfo(addrinfo
);
941 token
= pcap_strtok_r(NULL
, sep
, &lasts
);
946 freeaddrinfo(addrinfo
);
951 pcap_snprintf(errbuf
, errbuflen
, "The host is not in the allowed host list. Connection refused.");
957 /* No hostlist, so we have to return 'empty list' */
962 * \brief Compares two addresses contained into two sockaddr_storage structures.
964 * This function is useful to compare two addresses, given their internal representation,
965 * i.e. an sockaddr_storage structure.
967 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
968 * sockaddr_in6, properly acsted in order to be compliant to the function interface.
970 * This function will return '0' if the two addresses matches, '-1' if not.
972 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
973 * accept() call), containing the first address to compare.
975 * \param second: a sockaddr_storage structure containing the second address to compare.
977 * \return '0' if the addresses are equal, '-1' if they are different.
979 int sock_cmpaddr(struct sockaddr_storage
*first
, struct sockaddr_storage
*second
)
981 if (first
->ss_family
== second
->ss_family
)
983 if (first
->ss_family
== AF_INET
)
985 if (memcmp(&(((struct sockaddr_in
*) first
)->sin_addr
),
986 &(((struct sockaddr_in
*) second
)->sin_addr
),
987 sizeof(struct in_addr
)) == 0)
990 else /* address family is AF_INET6 */
992 if (memcmp(&(((struct sockaddr_in6
*) first
)->sin6_addr
),
993 &(((struct sockaddr_in6
*) second
)->sin6_addr
),
994 sizeof(struct in6_addr
)) == 0)
1003 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1005 * It is used to return the address and port the server picked for our socket on the local machine.
1007 * - connected sockets
1010 * On unconnected client sockets it does not work because the system dynamically chooses a port
1011 * only when the socket calls a send() call.
1013 * \param sock: the connected socket currently opened.
1015 * \param address: it contains the address that will be returned by the function. This buffer
1016 * must be properly allocated by the user. The address can be either literal or numeric depending
1017 * on the value of 'Flags'.
1019 * \param addrlen: the length of the 'address' buffer.
1021 * \param port: it contains the port that will be returned by the function. This buffer
1022 * must be properly allocated by the user.
1024 * \param portlen: the length of the 'port' buffer.
1026 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1027 * that determine if the resulting address must be in numeric / literal form, and so on.
1029 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1030 * error message. This buffer has to be at least 'errbuflen' in length.
1031 * It can be NULL; in this case the error cannot be printed.
1033 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1034 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1036 * \return It returns '-1' if this function succeeds, '0' otherwise.
1037 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1038 * In any case, the returned strings are '0' terminated.
1040 * \warning If the socket is using a connectionless protocol, the address may not be available
1041 * until I/O occurs on the socket.
1043 int sock_getmyinfo(SOCKET sock
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, int errbuflen
)
1045 struct sockaddr_storage mysockaddr
;
1046 socklen_t sockaddrlen
;
1049 sockaddrlen
= sizeof(struct sockaddr_storage
);
1051 if (getsockname(sock
, (struct sockaddr
*) &mysockaddr
, &sockaddrlen
) == -1)
1053 sock_geterror("getsockname(): ", errbuf
, errbuflen
);
1057 /* Returns the numeric address of the host that triggered the error */
1058 return sock_getascii_addrport(&mysockaddr
, address
, addrlen
, port
, portlen
, flags
, errbuf
, errbuflen
);
1062 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1064 * This function is basically an extended version of the inet_ntop(), which does not exist in
1065 * Winsock because the same result can be obtained by using the getnameinfo().
1066 * However, differently from inet_ntop(), this function is able to return also literal names
1067 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1069 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1070 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1071 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1072 * a standard IPv6 address like "::1".
1074 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1075 * are the ones allowed in the standard getnameinfo() socket function.
1077 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1078 * need to be translated from network form into the presentation form. This structure must be
1079 * zero-ed prior using it, and the address family field must be filled with the proper value.
1080 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1081 * calling this function.
1083 * \param address: it contains the address that will be returned by the function. This buffer
1084 * must be properly allocated by the user. The address can be either literal or numeric depending
1085 * on the value of 'Flags'.
1087 * \param addrlen: the length of the 'address' buffer.
1089 * \param port: it contains the port that will be returned by the function. This buffer
1090 * must be properly allocated by the user.
1092 * \param portlen: the length of the 'port' buffer.
1094 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1095 * that determine if the resulting address must be in numeric / literal form, and so on.
1097 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1098 * error message. This buffer has to be at least 'errbuflen' in length.
1099 * It can be NULL; in this case the error cannot be printed.
1101 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1102 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1104 * \return It returns '-1' if this function succeeds, '0' otherwise.
1105 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1107 * In any case, the returned strings are '0' terminated.
1109 int sock_getascii_addrport(const struct sockaddr_storage
*sockaddr
, char *address
, int addrlen
, char *port
, int portlen
, int flags
, char *errbuf
, int errbuflen
)
1111 socklen_t sockaddrlen
;
1112 int retval
; /* Variable that keeps the return value; */
1117 if (sockaddr
->ss_family
== AF_INET
)
1118 sockaddrlen
= sizeof(struct sockaddr_in
);
1120 sockaddrlen
= sizeof(struct sockaddr_in6
);
1122 sockaddrlen
= sizeof(struct sockaddr_storage
);
1125 if ((flags
& NI_NUMERICHOST
) == 0) /* Check that we want literal names */
1127 if ((sockaddr
->ss_family
== AF_INET6
) &&
1128 (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))
1131 strlcpy(address
, SOCKET_NAME_NULL_DAD
, addrlen
);
1136 if (getnameinfo((struct sockaddr
*) sockaddr
, sockaddrlen
, address
, addrlen
, port
, portlen
, flags
) != 0)
1138 /* If the user wants to receive an error message */
1141 sock_geterror("getnameinfo(): ", errbuf
, errbuflen
);
1142 errbuf
[errbuflen
- 1] = 0;
1147 strlcpy(address
, SOCKET_NO_NAME_AVAILABLE
, addrlen
);
1148 address
[addrlen
- 1] = 0;
1153 strlcpy(port
, SOCKET_NO_PORT_AVAILABLE
, portlen
);
1154 port
[portlen
- 1] = 0;
1164 * \brief It translates an address from the 'presentation' form into the 'network' form.
1166 * This function basically replaces inet_pton(), which does not exist in Winsock because
1167 * the same result can be obtained by using the getaddrinfo().
1168 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
1169 * like in inet_pton() ) and a literal name (e.g. 'localhost').
1171 * This function does the reverse job of sock_getascii_addrport().
1173 * \param address: a zero-terminated string which contains the name you have to
1174 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
1176 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
1177 * 'network' form of the requested address.
1179 * \param addr_family: a constant which can assume the following values:
1180 * - 'AF_INET' if we want to ping an IPv4 host
1181 * - 'AF_INET6' if we want to ping an IPv6 host
1182 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
1184 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1185 * error message. This buffer has to be at least 'errbuflen' in length.
1186 * It can be NULL; in this case the error cannot be printed.
1188 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1189 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1191 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
1192 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
1193 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
1194 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
1195 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
1197 * \warning The sockaddr_storage structure MUST be allocated by the user.
1199 int sock_present2network(const char *address
, struct sockaddr_storage
*sockaddr
, int addr_family
, char *errbuf
, int errbuflen
)
1202 struct addrinfo
*addrinfo
;
1203 struct addrinfo hints
;
1205 memset(&hints
, 0, sizeof(hints
));
1207 hints
.ai_family
= addr_family
;
1209 if ((retval
= sock_initaddress(address
, "22222" /* fake port */, &hints
, &addrinfo
, errbuf
, errbuflen
)) == -1)
1212 if (addrinfo
->ai_family
== PF_INET
)
1213 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in
));
1215 memcpy(sockaddr
, addrinfo
->ai_addr
, sizeof(struct sockaddr_in6
));
1217 if (addrinfo
->ai_next
!= NULL
)
1219 freeaddrinfo(addrinfo
);
1222 pcap_snprintf(errbuf
, errbuflen
, "More than one socket requested; using the first one returned");
1226 freeaddrinfo(addrinfo
);