]> The Tcpdump Group git mirrors - libpcap/blob - sockutils.c
8909c3a0880d64f847468c707d1ec26b536a18db
[libpcap] / sockutils.c
1 /*
2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
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.
18 *
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.
30 *
31 */
32
33 #ifdef HAVE_CONFIG_H
34 #include <config.h>
35 #endif
36
37 /*
38 * \file sockutils.c
39 *
40 * The goal of this file is to provide a common set of primitives for socket
41 * manipulation.
42 *
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.
46 *
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
50 * ways.
51 */
52
53 #include "ftmacros.h"
54
55 #include <string.h>
56 #include <errno.h> /* for the errno variable */
57 #include <stdio.h> /* for the stderr file */
58 #include <stdlib.h> /* for malloc() and free() */
59 #include <limits.h> /* for INT_MAX */
60
61 #include "pcap-int.h"
62
63 #include "sockutils.h"
64 #include "portability.h"
65
66 #ifdef _WIN32
67 /*
68 * Winsock initialization.
69 *
70 * Ask for WinSock 2.2.
71 */
72 #define WINSOCK_MAJOR_VERSION 2
73 #define WINSOCK_MINOR_VERSION 2
74
75 static int sockcount = 0; /*!< Variable that allows calling the WSAStartup() only one time */
76 #endif
77
78 /* Some minor differences between UNIX and Win32 */
79 #ifdef _WIN32
80 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
81 #endif
82
83 /* Size of the buffer that has to keep error messages */
84 #define SOCK_ERRBUF_SIZE 1024
85
86 /* Constants; used in order to keep strings here */
87 #define SOCKET_NO_NAME_AVAILABLE "No name available"
88 #define SOCKET_NO_PORT_AVAILABLE "No port available"
89 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
90
91 /*
92 * On UN*X, send() and recv() return ssize_t.
93 *
94 * On Windows, send() and recv() return an int.
95 *
96 * Wth MSVC, there *is* no ssize_t.
97 *
98 * With MinGW, there is an ssize_t type; it is either an int (32 bit)
99 * or a long long (64 bit).
100 *
101 * So, on Windows, if we don't have ssize_t defined, define it as an
102 * int, so we can use it, on all platforms, as the type of variables
103 * that hold the return values from send() and recv().
104 */
105 #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
106 typedef int ssize_t;
107 #endif
108
109 /****************************************************
110 * *
111 * Locally defined functions *
112 * *
113 ****************************************************/
114
115 static int sock_ismcastaddr(const struct sockaddr *saddr);
116
117 /****************************************************
118 * *
119 * Function bodies *
120 * *
121 ****************************************************/
122
123 /*
124 * Format an error message given an errno value (UN*X) or a WinSock error
125 * (Windows).
126 */
127 void sock_fmterror(const char *caller, int errcode, char *errbuf, int errbuflen)
128 {
129 if (errbuf == NULL)
130 return;
131
132 #ifdef _WIN32
133 pcap_fmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
134 "%s", caller);
135 #else
136 pcap_fmt_errmsg_for_errno(errbuf, errbuflen, errcode,
137 "%s", caller);
138 #endif
139 }
140
141 /*
142 * \brief It retrieves the error message after an error occurred in the socket interface.
143 *
144 * This function is defined because of the different way errors are returned in UNIX
145 * and Win32. This function provides a consistent way to retrieve the error message
146 * (after a socket error occurred) on all the platforms.
147 *
148 * \param caller: a pointer to a user-allocated string which contains a message that has
149 * to be printed *before* the true error message. It could be, for example, 'this error
150 * comes from the recv() call at line 31'.
151 *
152 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
153 * error message. This buffer has to be at least 'errbuflen' in length.
154 * It can be NULL; in this case the error cannot be printed.
155 *
156 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
157 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
158 *
159 * \return No return values. The error message is returned in the 'string' parameter.
160 */
161 void sock_geterror(const char *caller, char *errbuf, int errbuflen)
162 {
163 #ifdef _WIN32
164 sock_fmterror(caller, GetLastError(), errbuf, errbuflen);
165 #else
166 sock_fmterror(caller, errno, errbuf, errbuflen);
167 #endif
168 }
169
170 /*
171 * \brief This function initializes the socket mechanism if it hasn't
172 * already been initialized or reinitializes it after it has been
173 * cleaned up.
174 *
175 * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
176 * initialize Winsock.
177 *
178 * \param errbuf: a pointer to an user-allocated buffer that will contain
179 * the complete error message. This buffer has to be at least 'errbuflen'
180 * in length. It can be NULL; in this case no error message is supplied.
181 *
182 * \param errbuflen: length of the buffer that will contains the error.
183 * The error message cannot be larger than 'errbuflen - 1' because the
184 * last char is reserved for the string terminator.
185 *
186 * \return '0' if everything is fine, '-1' if some errors occurred. The
187 * error message is returned in the buffer pointed to by 'errbuf' variable.
188 */
189 #ifdef _WIN32
190 int sock_init(char *errbuf, int errbuflen)
191 {
192 if (sockcount == 0)
193 {
194 WSADATA wsaData; /* helper variable needed to initialize Winsock */
195
196 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
197 WINSOCK_MINOR_VERSION), &wsaData) != 0)
198 {
199 if (errbuf)
200 pcap_snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
201
202 WSACleanup();
203
204 return -1;
205 }
206 }
207
208 sockcount++;
209 return 0;
210 }
211 #else
212 int sock_init(char *errbuf _U_, int errbuflen _U_)
213 {
214 /*
215 * Nothing to do on UN*Xes.
216 */
217 return 0;
218 }
219 #endif
220
221 /*
222 * \brief This function cleans up the socket mechanism if we have no
223 * sockets left open.
224 *
225 * On UN*Xes, it doesn't need to do anything; on Windows, it needs
226 * to clean up Winsock.
227 *
228 * \return No error values.
229 */
230 void sock_cleanup(void)
231 {
232 #ifdef _WIN32
233 sockcount--;
234
235 if (sockcount == 0)
236 WSACleanup();
237 #endif
238 }
239
240 /*
241 * \brief It checks if the sockaddr variable contains a multicast address.
242 *
243 * \return '0' if the address is multicast, '-1' if it is not.
244 */
245 static int sock_ismcastaddr(const struct sockaddr *saddr)
246 {
247 if (saddr->sa_family == PF_INET)
248 {
249 struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
250 if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
251 else return -1;
252 }
253 else
254 {
255 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
256 if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
257 else return -1;
258 }
259 }
260
261 /*
262 * \brief It initializes a network connection both from the client and the server side.
263 *
264 * In case of a client socket, this function calls socket() and connect().
265 * In the meanwhile, it checks for any socket error.
266 * If an error occurs, it writes the error message into 'errbuf'.
267 *
268 * In case of a server socket, the function calls socket(), bind() and listen().
269 *
270 * This function is usually preceeded by the sock_initaddress().
271 *
272 * \param addrinfo: pointer to an addrinfo variable which will be used to
273 * open the socket and such. This variable is the one returned by the previous call to
274 * sock_initaddress().
275 *
276 * \param server: '1' if this is a server socket, '0' otherwise.
277 *
278 * \param nconn: number of the connections that are allowed to wait into the listen() call.
279 * This value has no meanings in case of a client socket.
280 *
281 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
282 * error message. This buffer has to be at least 'errbuflen' in length.
283 * It can be NULL; in this case the error cannot be printed.
284 *
285 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
286 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
287 *
288 * \return the socket that has been opened (that has to be used in the following sockets calls)
289 * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
290 * in the 'errbuf' variable.
291 */
292 SOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
293 {
294 SOCKET sock;
295 #if defined(SO_NOSIGPIPE) || defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
296 int on = 1;
297 #endif
298
299 sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
300 if (sock == INVALID_SOCKET)
301 {
302 sock_geterror("socket()", errbuf, errbuflen);
303 return INVALID_SOCKET;
304 }
305
306 /*
307 * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
308 * have to deal with signals if the peer closes the connection,
309 * especially in client programs, which may not even be aware that
310 * they're sending to sockets.
311 */
312 #ifdef SO_NOSIGPIPE
313 if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
314 sizeof (int)) == -1)
315 {
316 sock_geterror("setsockopt(SO_NOSIGPIPE)", errbuf, errbuflen);
317 closesocket(sock);
318 return INVALID_SOCKET;
319 }
320 #endif
321
322 /* This is a server socket */
323 if (server)
324 {
325 /*
326 * Allow a new server to bind the socket after the old one
327 * exited, even if lingering sockets are still present.
328 *
329 * Don't treat an error as a failure.
330 */
331 int optval = 1;
332 (void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
333 (char *)&optval, sizeof (optval));
334
335 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
336 /*
337 * Force the use of IPv6-only addresses.
338 *
339 * RFC 3493 indicates that you can support IPv4 on an
340 * IPv6 socket:
341 *
342 * https://tools.ietf.org/html/rfc3493#section-3.7
343 *
344 * and that this is the default behavior. This means
345 * that if we first create an IPv6 socket bound to the
346 * "any" address, it is, in effect, also bound to the
347 * IPv4 "any" address, so when we create an IPv4 socket
348 * and try to bind it to the IPv4 "any" address, it gets
349 * EADDRINUSE.
350 *
351 * Not all network stacks support IPv4 on IPv6 sockets;
352 * pre-NT 6 Windows stacks don't support it, and the
353 * OpenBSD stack doesn't support it for security reasons
354 * (see the OpenBSD inet6(4) man page). Therefore, we
355 * don't want to rely on this behavior.
356 *
357 * So we try to disable it, using either the IPV6_V6ONLY
358 * option from RFC 3493:
359 *
360 * https://tools.ietf.org/html/rfc3493#section-5.3
361 *
362 * or the IPV6_BINDV6ONLY option from older UN*Xes.
363 */
364 #ifndef IPV6_V6ONLY
365 /* For older systems */
366 #define IPV6_V6ONLY IPV6_BINDV6ONLY
367 #endif /* IPV6_V6ONLY */
368 if (addrinfo->ai_family == PF_INET6)
369 {
370 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
371 (char *)&on, sizeof (int)) == -1)
372 {
373 if (errbuf)
374 pcap_snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
375 closesocket(sock);
376 return INVALID_SOCKET;
377 }
378 }
379 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
380
381 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
382 if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
383 {
384 sock_geterror("bind()", errbuf, errbuflen);
385 closesocket(sock);
386 return INVALID_SOCKET;
387 }
388
389 if (addrinfo->ai_socktype == SOCK_STREAM)
390 if (listen(sock, nconn) == -1)
391 {
392 sock_geterror("listen()", errbuf, errbuflen);
393 closesocket(sock);
394 return INVALID_SOCKET;
395 }
396
397 /* server side ended */
398 return sock;
399 }
400 else /* we're the client */
401 {
402 struct addrinfo *tempaddrinfo;
403 char *errbufptr;
404 size_t bufspaceleft;
405
406 tempaddrinfo = addrinfo;
407 errbufptr = errbuf;
408 bufspaceleft = errbuflen;
409 *errbufptr = 0;
410
411 /*
412 * We have to loop though all the addinfo returned.
413 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
414 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
415 */
416 while (tempaddrinfo)
417 {
418
419 if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
420 {
421 size_t msglen;
422 char TmpBuffer[100];
423 char SocketErrorMessage[SOCK_ERRBUF_SIZE];
424
425 /*
426 * We have to retrieve the error message before any other socket call completes, otherwise
427 * the error message is lost
428 */
429 sock_geterror("Connect to socket failed",
430 SocketErrorMessage, sizeof(SocketErrorMessage));
431
432 /* Returns the numeric address of the host that triggered the error */
433 sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
434
435 pcap_snprintf(errbufptr, bufspaceleft,
436 "Is the server properly installed on %s? %s", TmpBuffer, SocketErrorMessage);
437
438 /* In case more then one 'connect' fails, we manage to keep all the error messages */
439 msglen = strlen(errbufptr);
440
441 errbufptr[msglen] = ' ';
442 errbufptr[msglen + 1] = 0;
443
444 bufspaceleft = bufspaceleft - (msglen + 1);
445 errbufptr += (msglen + 1);
446
447 tempaddrinfo = tempaddrinfo->ai_next;
448 }
449 else
450 break;
451 }
452
453 /*
454 * Check how we exit from the previous loop
455 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
456 */
457 if (tempaddrinfo == NULL)
458 {
459 closesocket(sock);
460 return INVALID_SOCKET;
461 }
462 else
463 return sock;
464 }
465 }
466
467 /*
468 * \brief Closes the present (TCP and UDP) socket connection.
469 *
470 * This function sends a shutdown() on the socket in order to disable send() calls
471 * (while recv() ones are still allowed). Then, it closes the socket.
472 *
473 * \param sock: the socket identifier of the connection that has to be closed.
474 *
475 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
476 * error message. This buffer has to be at least 'errbuflen' in length.
477 * It can be NULL; in this case the error cannot be printed.
478 *
479 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
480 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
481 *
482 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
483 * in the 'errbuf' variable.
484 */
485 int sock_close(SOCKET sock, char *errbuf, int errbuflen)
486 {
487 /*
488 * SHUT_WR: subsequent calls to the send function are disallowed.
489 * For TCP sockets, a FIN will be sent after all data is sent and
490 * acknowledged by the Server.
491 */
492 if (shutdown(sock, SHUT_WR))
493 {
494 sock_geterror("shutdown()", errbuf, errbuflen);
495 /* close the socket anyway */
496 closesocket(sock);
497 return -1;
498 }
499
500 closesocket(sock);
501 return 0;
502 }
503
504 /*
505 * gai_errstring() has some problems:
506 *
507 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
508 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
509 * thread-safe, so an implementation might use a static buffer
510 * for unknown error codes;
511 * 3) the error message for the most likely error, EAI_NONAME, is
512 * truly horrible on several platforms ("nodename nor servname
513 * provided, or not known"? It's typically going to be "not
514 * known", not "oopsie, I passed null pointers for the host name
515 * and service name", not to mention they forgot the "neither");
516 *
517 * so we roll our own.
518 */
519 static void
520 get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
521 const char *hostname, const char *portname)
522 {
523 char hostport[PCAP_ERRBUF_SIZE];
524
525 if (hostname != NULL && portname != NULL)
526 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s:%s",
527 hostname, portname);
528 else if (hostname != NULL)
529 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "%s",
530 hostname);
531 else if (portname != NULL)
532 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, ":%s",
533 portname);
534 else
535 pcap_snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
536 switch (err)
537 {
538 #ifdef EAI_ADDRFAMILY
539 case EAI_ADDRFAMILY:
540 pcap_snprintf(errbuf, errbuflen,
541 "%sAddress family for %s not supported",
542 prefix, hostport);
543 break;
544 #endif
545
546 case EAI_AGAIN:
547 pcap_snprintf(errbuf, errbuflen,
548 "%s%s could not be resolved at this time",
549 prefix, hostport);
550 break;
551
552 case EAI_BADFLAGS:
553 pcap_snprintf(errbuf, errbuflen,
554 "%sThe ai_flags parameter for looking up %s had an invalid value",
555 prefix, hostport);
556 break;
557
558 case EAI_FAIL:
559 pcap_snprintf(errbuf, errbuflen,
560 "%sA non-recoverable error occurred when attempting to resolve %s",
561 prefix, hostport);
562 break;
563
564 case EAI_FAMILY:
565 pcap_snprintf(errbuf, errbuflen,
566 "%sThe address family for looking up %s was not recognized",
567 prefix, hostport);
568 break;
569
570 case EAI_MEMORY:
571 pcap_snprintf(errbuf, errbuflen,
572 "%sOut of memory trying to allocate storage when looking up %s",
573 prefix, hostport);
574 break;
575
576 /*
577 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
578 *
579 * RFC 3493 has only EAI_NONAME.
580 *
581 * Some implementations define EAI_NODATA and EAI_NONAME
582 * to the same value, others don't. If EAI_NODATA is
583 * defined and isn't the same as EAI_NONAME, we handle
584 * EAI_NODATA.
585 */
586 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
587 case EAI_NODATA:
588 pcap_snprintf(errbuf, errbuflen,
589 "%sNo address associated with %s",
590 prefix, hostport);
591 break;
592 #endif
593
594 case EAI_NONAME:
595 pcap_snprintf(errbuf, errbuflen,
596 "%sThe host name %s couldn't be resolved",
597 prefix, hostport);
598 break;
599
600 case EAI_SERVICE:
601 pcap_snprintf(errbuf, errbuflen,
602 "%sThe service value specified when looking up %s as not recognized for the socket type",
603 prefix, hostport);
604 break;
605
606 case EAI_SOCKTYPE:
607 pcap_snprintf(errbuf, errbuflen,
608 "%sThe socket type specified when looking up %s as not recognized",
609 prefix, hostport);
610 break;
611
612 #ifdef EAI_SYSTEM
613 case EAI_SYSTEM:
614 /*
615 * Assumed to be UN*X.
616 */
617 pcap_snprintf(errbuf, errbuflen,
618 "%sAn error occurred when looking up %s: %s",
619 prefix, hostport, pcap_strerror(errno));
620 break;
621 #endif
622
623 #ifdef EAI_BADHINTS
624 case EAI_BADHINTS:
625 pcap_snprintf(errbuf, errbuflen,
626 "%sInvalid value for hints when looking up %s",
627 prefix, hostport);
628 break;
629 #endif
630
631 #ifdef EAI_PROTOCOL
632 case EAI_PROTOCOL:
633 pcap_snprintf(errbuf, errbuflen,
634 "%sResolved protocol when looking up %s is unknown",
635 prefix, hostport);
636 break;
637 #endif
638
639 #ifdef EAI_OVERFLOW
640 case EAI_OVERFLOW:
641 pcap_snprintf(errbuf, errbuflen,
642 "%sArgument buffer overflow when looking up %s",
643 prefix, hostport);
644 break;
645 #endif
646
647 default:
648 pcap_snprintf(errbuf, errbuflen,
649 "%sgetaddrinfo() error %d when looking up %s",
650 prefix, err, hostport);
651 break;
652 }
653 }
654
655 /*
656 * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
657 *
658 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
659 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
660 * If an error occurs, it writes the error message into 'errbuf'.
661 *
662 * \param host: a pointer to a string identifying the host. It can be
663 * a host name, a numeric literal address, or NULL or "" (useful
664 * in case of a server socket which has to bind to all addresses).
665 *
666 * \param port: a pointer to a user-allocated buffer containing the network port to use.
667 *
668 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
669 * addrinfo structure appropriately.
670 *
671 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
672 * (passed by reference), which will be allocated by this function and returned back to the caller.
673 * This variable will be used in the next sockets calls.
674 *
675 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
676 * error message. This buffer has to be at least 'errbuflen' in length.
677 * It can be NULL; in this case the error cannot be printed.
678 *
679 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
680 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
681 *
682 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
683 * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
684 * returned into the addrinfo parameter.
685 *
686 * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
687 * it is no longer needed.
688 *
689 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
690 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
691 * the programmer to look at that function in order to set the 'hints' variable appropriately.
692 */
693 int sock_initaddress(const char *host, const char *port,
694 struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
695 {
696 int retval;
697
698 retval = getaddrinfo(host, port, hints, addrinfo);
699 if (retval != 0)
700 {
701 if (errbuf)
702 {
703 get_gai_errstring(errbuf, errbuflen, "", retval,
704 host, port);
705 }
706 return -1;
707 }
708 /*
709 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
710 * addrinfo has more han one pointers
711 */
712
713 /*
714 * This software only supports PF_INET and PF_INET6.
715 *
716 * XXX - should we just check that at least *one* address is
717 * either PF_INET or PF_INET6, and, when using the list,
718 * ignore all addresses that are neither? (What, no IPX
719 * support? :-))
720 */
721 if (((*addrinfo)->ai_family != PF_INET) &&
722 ((*addrinfo)->ai_family != PF_INET6))
723 {
724 if (errbuf)
725 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
726 freeaddrinfo(*addrinfo);
727 *addrinfo = NULL;
728 return -1;
729 }
730
731 /*
732 * You can't do multicast (or broadcast) TCP.
733 */
734 if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
735 (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
736 {
737 if (errbuf)
738 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
739 freeaddrinfo(*addrinfo);
740 *addrinfo = NULL;
741 return -1;
742 }
743
744 return 0;
745 }
746
747 /*
748 * \brief It sends the amount of data contained into 'buffer' on the given socket.
749 *
750 * This function basically calls the send() socket function and it checks that all
751 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
752 * it writes the error message into 'errbuf'.
753 * In case the socket buffer does not have enough space, it loops until all data
754 * has been sent.
755 *
756 * \param socket: the connected socket currently opened.
757 *
758 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
759 *
760 * \param size: number of bytes that have to be sent.
761 *
762 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
763 * error message. This buffer has to be at least 'errbuflen' in length.
764 * It can be NULL; in this case the error cannot be printed.
765 *
766 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
767 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
768 *
769 * \return '0' if everything is fine, '-1' if an error other than
770 * "connection reset" or "peer has closed the receive side" occurred,
771 * '-2' if we got one of those errors.
772 * For errors, an error message is returned in the 'errbuf' variable.
773 */
774 int sock_send(SOCKET sock, SSL *ssl _U_NOSSL_, const char *buffer, size_t size,
775 char *errbuf, int errbuflen)
776 {
777 int remaining;
778 ssize_t nsent;
779
780 if (size > INT_MAX)
781 {
782 if (errbuf)
783 {
784 pcap_snprintf(errbuf, errbuflen,
785 "Can't send more than %u bytes with sock_send",
786 INT_MAX);
787 }
788 return -1;
789 }
790 remaining = (int)size;
791
792 do {
793 #ifdef HAVE_OPENSSL
794 if (ssl) return ssl_send(ssl, buffer, remaining, errbuf, errbuflen);
795 #endif
796
797 #ifdef MSG_NOSIGNAL
798 /*
799 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
800 * on errors on stream-oriented sockets when the other
801 * end breaks the connection.
802 * The EPIPE error is still returned.
803 */
804 nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
805 #else
806 nsent = send(sock, buffer, remaining, 0);
807 #endif
808
809 if (nsent == -1)
810 {
811 /*
812 * If the client closed the connection out from
813 * under us, there's no need to log that as an
814 * error.
815 */
816 int errcode;
817
818 #ifdef _WIN32
819 errcode = GetLastError();
820 if (errcode == WSAECONNRESET ||
821 errcode == WSAECONNABORTED)
822 {
823 /*
824 * WSAECONNABORTED appears to be the error
825 * returned in Winsock when you try to send
826 * on a connection where the peer has closed
827 * the receive side.
828 */
829 return -2;
830 }
831 sock_fmterror("send()", errcode, errbuf, errbuflen);
832 #else
833 errcode = errno;
834 if (errcode == ECONNRESET || errcode == EPIPE)
835 {
836 /*
837 * EPIPE is what's returned on UN*X when
838 * you try to send on a connection when
839 * the peer has closed the receive side.
840 */
841 return -2;
842 }
843 sock_fmterror("send()", errcode, errbuf, errbuflen);
844 #endif
845 return -1;
846 }
847
848 remaining -= nsent;
849 buffer += nsent;
850 } while (remaining != 0);
851
852 return 0;
853 }
854
855 /*
856 * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
857 * and it checks for buffer overflows.
858 *
859 * This function basically copies 'size' bytes of data contained into 'buffer'
860 * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
861 * resulting buffer will not be larger than 'totsize'. Finally, it updates
862 * the 'offset' variable in order to point to the first empty location of the buffer.
863 *
864 * In case the function is called with 'checkonly' equal to 1, it does not copy
865 * the data into the buffer. It only checks for buffer overflows and it updates the
866 * 'offset' variable. This mode can be useful when the buffer already contains the
867 * data (maybe because the producer writes directly into the target buffer), so
868 * only the buffer overflow check has to be made.
869 * In this case, both 'buffer' and 'tempbuf' can be NULL values.
870 *
871 * This function is useful in case the userland application does not know immediately
872 * all the data it has to write into the socket. This function provides a way to create
873 * the "stream" step by step, appending the new data to the old one. Then, when all the
874 * data has been bufferized, the application can call the sock_send() function.
875 *
876 * \param buffer: a char pointer to a user-allocated buffer that keeps the data
877 * that has to be copied.
878 *
879 * \param size: number of bytes that have to be copied.
880 *
881 * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
882 * has to be copied.
883 *
884 * \param offset: an index into 'tempbuf' which keeps the location of its first
885 * empty location.
886 *
887 * \param totsize: total size of the buffer in which data is being copied.
888 *
889 * \param checkonly: '1' if we do not want to copy data into the buffer and we
890 * want just do a buffer ovreflow control, '0' if data has to be copied as well.
891 *
892 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
893 * error message. This buffer has to be at least 'errbuflen' in length.
894 * It can be NULL; in this case the error cannot be printed.
895 *
896 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
897 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
898 *
899 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
900 * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
901 * have the new string appended, and 'offset' will keep the length of that buffer.
902 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
903 *
904 * \warning This function assumes that the buffer in which data has to be stored is
905 * large 'totbuf' bytes.
906 *
907 * \warning In case of 'checkonly', be carefully to call this function *before* copying
908 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
909 */
910 int sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
911 {
912 if ((*offset + size) > totsize)
913 {
914 if (errbuf)
915 pcap_snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
916 return -1;
917 }
918
919 if (!checkonly)
920 memcpy(tempbuf + (*offset), buffer, size);
921
922 (*offset) += size;
923
924 return 0;
925 }
926
927 /*
928 * \brief It waits on a connected socket and it manages to receive data.
929 *
930 * This function basically calls the recv() socket function and it checks that no
931 * error occurred. If that happens, it writes the error message into 'errbuf'.
932 *
933 * This function changes its behavior according to the 'receiveall' flag: if we
934 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
935 * data is arrived. Otherwise, it returns the data currently available.
936 *
937 * In case the socket does not have enough data available, it cycles on the recv()
938 * until the requested data (of size 'size') is arrived.
939 * In this case, it blocks until the number of bytes read is equal to 'size'.
940 *
941 * \param sock: the connected socket currently opened.
942 *
943 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
944 *
945 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
946 * that we are expecting to be read.
947 *
948 * \param flags:
949 *
950 * SOCK_RECEIVALL_XXX:
951 *
952 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
953 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
954 * received (in case the socket does not have enough data available).
955 *
956 * SOCK_EOF_XXX:
957 *
958 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
959 * and return an error on any subsequent read that returns 0;
960 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
961 *
962 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
963 * error message. This buffer has to be at least 'errbuflen' in length.
964 * It can be NULL; in this case the error cannot be printed.
965 *
966 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
967 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
968 *
969 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
970 * The error message is returned in the 'errbuf' variable.
971 */
972
973 int sock_recv(SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
974 int flags, char *errbuf, int errbuflen)
975 {
976 int recv_flags = 0;
977 char *bufp = buffer;
978 int remaining;
979 ssize_t nread;
980
981 if (size == 0)
982 {
983 return 0;
984 }
985 if (size > INT_MAX)
986 {
987 if (errbuf)
988 {
989 pcap_snprintf(errbuf, errbuflen,
990 "Can't read more than %u bytes with sock_recv",
991 INT_MAX);
992 }
993 return -1;
994 }
995
996 if (flags & SOCK_MSG_PEEK)
997 recv_flags |= MSG_PEEK;
998
999 bufp = (char *) buffer;
1000 remaining = (int) size;
1001
1002 /*
1003 * We don't use MSG_WAITALL because it's not supported in
1004 * Win32.
1005 */
1006 for (;;) {
1007 #ifdef HAVE_OPENSSL
1008 if (ssl)
1009 {
1010 /*
1011 * XXX - what about MSG_PEEK?
1012 */
1013 nread = ssl_recv(ssl, bufp, remaining, errbuf, errbuflen);
1014 if (nread == -2) return -1;
1015 }
1016 else
1017 nread = recv(sock, bufp, remaining, recv_flags);
1018 #else
1019 nread = recv(sock, bufp, remaining, recv_flags);
1020 #endif
1021
1022 if (nread == -1)
1023 {
1024 #ifndef _WIN32
1025 if (errno == EINTR)
1026 return -3;
1027 #endif
1028 sock_geterror("recv()", errbuf, errbuflen);
1029 return -1;
1030 }
1031
1032 if (nread == 0)
1033 {
1034 if ((flags & SOCK_EOF_IS_ERROR) ||
1035 (remaining != (int) size))
1036 {
1037 /*
1038 * Either we've already read some data,
1039 * or we're always supposed to return
1040 * an error on EOF.
1041 */
1042 if (errbuf)
1043 {
1044 pcap_snprintf(errbuf, errbuflen,
1045 "The other host terminated the connection.");
1046 }
1047 return -1;
1048 }
1049 else
1050 return 0;
1051 }
1052
1053 /*
1054 * Do we want to read the amount requested, or just return
1055 * what we got?
1056 */
1057 if (!(flags & SOCK_RECEIVEALL_YES))
1058 {
1059 /*
1060 * Just return what we got.
1061 */
1062 return (int) nread;
1063 }
1064
1065 bufp += nread;
1066 remaining -= nread;
1067
1068 if (remaining == 0)
1069 return (int) size;
1070 }
1071 }
1072
1073 /*
1074 * Receives a datagram from a socket.
1075 *
1076 * Returns the size of the datagram on success or -1 on error.
1077 */
1078 int sock_recv_dgram(SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
1079 char *errbuf, int errbuflen)
1080 {
1081 ssize_t nread;
1082 #ifndef _WIN32
1083 struct msghdr message;
1084 struct iovec iov;
1085 #endif
1086
1087 if (size == 0)
1088 {
1089 return 0;
1090 }
1091 if (size > INT_MAX)
1092 {
1093 if (errbuf)
1094 {
1095 pcap_snprintf(errbuf, errbuflen,
1096 "Can't read more than %u bytes with sock_recv_dgram",
1097 INT_MAX);
1098 }
1099 return -1;
1100 }
1101
1102 #ifdef HAVE_OPENSSL
1103 // TODO: DTLS
1104 if (ssl)
1105 {
1106 pcap_snprintf(errbuf, errbuflen, "DTLS not implemented yet");
1107 return -1;
1108 }
1109 #endif
1110
1111 /*
1112 * This should be a datagram socket, so we should get the
1113 * entire datagram in one recv() or recvmsg() call, and
1114 * don't need to loop.
1115 */
1116 #ifdef _WIN32
1117 nread = recv(sock, buffer, (int)size, 0);
1118 if (nread == SOCKET_ERROR)
1119 {
1120 /*
1121 * To quote the MSDN documentation for recv(),
1122 * "If the datagram or message is larger than
1123 * the buffer specified, the buffer is filled
1124 * with the first part of the datagram, and recv
1125 * generates the error WSAEMSGSIZE. For unreliable
1126 * protocols (for example, UDP) the excess data is
1127 * lost..."
1128 *
1129 * So if the message is bigger than the buffer
1130 * supplied to us, the excess data is discarded,
1131 * and we'll report an error.
1132 */
1133 sock_geterror("recv()", errbuf, errbuflen);
1134 return -1;
1135 }
1136 #else /* _WIN32 */
1137 /*
1138 * The Single UNIX Specification says that a recv() on
1139 * a socket for a message-oriented protocol will discard
1140 * the excess data. It does *not* indicate that the
1141 * receive will fail with, for example, EMSGSIZE.
1142 *
1143 * Therefore, we use recvmsg(), which appears to be
1144 * the only way to get a "message truncated" indication
1145 * when receiving a message for a message-oriented
1146 * protocol.
1147 */
1148 message.msg_name = NULL; /* we don't care who it's from */
1149 message.msg_namelen = 0;
1150 iov.iov_base = buffer;
1151 iov.iov_len = size;
1152 message.msg_iov = &iov;
1153 message.msg_iovlen = 1;
1154 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1155 message.msg_control = NULL; /* we don't care about control information */
1156 message.msg_controllen = 0;
1157 #endif
1158 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1159 message.msg_flags = 0;
1160 #endif
1161 nread = recvmsg(sock, &message, 0);
1162 if (nread == -1)
1163 {
1164 if (errno == EINTR)
1165 return -3;
1166 sock_geterror("recv()", errbuf, errbuflen);
1167 return -1;
1168 }
1169 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1170 /*
1171 * XXX - Solaris supports this, but only if you ask for the
1172 * X/Open version of recvmsg(); should we use that, or will
1173 * that cause other problems?
1174 */
1175 if (message.msg_flags & MSG_TRUNC)
1176 {
1177 /*
1178 * Message was bigger than the specified buffer size.
1179 *
1180 * Report this as an error, as the Microsoft documentation
1181 * implies we'd do in a similar case on Windows.
1182 */
1183 pcap_snprintf(errbuf, errbuflen, "recv(): Message too long");
1184 return -1;
1185 }
1186 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1187 #endif /* _WIN32 */
1188
1189 /*
1190 * The size we're reading fits in an int, so the return value
1191 * will fit in an int.
1192 */
1193 return (int)nread;
1194 }
1195
1196 /*
1197 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1198 *
1199 * This function is useful in case we receive a message we cannot understand (e.g.
1200 * wrong version number when receiving a network packet), so that we have to discard all
1201 * data before reading a new message.
1202 *
1203 * This function will read 'size' bytes from the socket and discard them.
1204 * It defines an internal buffer in which data will be copied; however, in case
1205 * this buffer is not large enough, it will cycle in order to read everything as well.
1206 *
1207 * \param sock: the connected socket currently opened.
1208 *
1209 * \param size: number of bytes that have to be discarded.
1210 *
1211 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1212 * error message. This buffer has to be at least 'errbuflen' in length.
1213 * It can be NULL; in this case the error cannot be printed.
1214 *
1215 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1216 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1217 *
1218 * \return '0' if everything is fine, '-1' if some errors occurred.
1219 * The error message is returned in the 'errbuf' variable.
1220 */
1221 int sock_discard(SOCKET sock, SSL *ssl, int size, char *errbuf, int errbuflen)
1222 {
1223 #define TEMP_BUF_SIZE 32768
1224
1225 char buffer[TEMP_BUF_SIZE]; /* network buffer, to be used when the message is discarded */
1226
1227 /*
1228 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1229 * Our feeling is that a buffer if 32KB is enough for most of the application;
1230 * in case this is not enough, the "while" loop discards the message by calling the
1231 * sockrecv() several times.
1232 * We do not want to create a bigger variable because this causes the program to exit on
1233 * some platforms (e.g. BSD)
1234 */
1235 while (size > TEMP_BUF_SIZE)
1236 {
1237 if (sock_recv(sock, ssl, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1238 return -1;
1239
1240 size -= TEMP_BUF_SIZE;
1241 }
1242
1243 /*
1244 * If there is still data to be discarded
1245 * In this case, the data can fit into the temporary buffer
1246 */
1247 if (size)
1248 {
1249 if (sock_recv(sock, ssl, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1250 return -1;
1251 }
1252
1253 return 0;
1254 }
1255
1256 /*
1257 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1258 *
1259 * This function is useful after an accept() call in order to check if the connecting
1260 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1261 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1262 * against this host list, and it returns '0' is the host is included in this list.
1263 *
1264 * \param hostlist: pointer to a string that contains the list of the allowed host.
1265 *
1266 * \param sep: a string that keeps the separators used between the hosts (for example the
1267 * space character) in the host list.
1268 *
1269 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1270 *
1271 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1272 * error message. This buffer has to be at least 'errbuflen' in length.
1273 * It can be NULL; in this case the error cannot be printed.
1274 *
1275 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1276 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1277 *
1278 * \return It returns:
1279 * - '1' if the host list is empty
1280 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1281 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1282 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1283 */
1284 int sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
1285 {
1286 /* checks if the connecting host is among the ones allowed */
1287 if ((hostlist) && (hostlist[0]))
1288 {
1289 char *token; /* temp, needed to separate items into the hostlist */
1290 struct addrinfo *addrinfo, *ai_next;
1291 char *temphostlist;
1292 char *lasts;
1293 int getaddrinfo_failed = 0;
1294
1295 /*
1296 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1297 * So, we have to create a new temporary string in which the original content is kept
1298 */
1299 temphostlist = strdup(hostlist);
1300 if (temphostlist == NULL)
1301 {
1302 sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
1303 return -2;
1304 }
1305
1306 token = pcap_strtok_r(temphostlist, sep, &lasts);
1307
1308 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1309 addrinfo = NULL;
1310
1311 while (token != NULL)
1312 {
1313 struct addrinfo hints;
1314 int retval;
1315
1316 addrinfo = NULL;
1317 memset(&hints, 0, sizeof(struct addrinfo));
1318 hints.ai_family = PF_UNSPEC;
1319 hints.ai_socktype = SOCK_STREAM;
1320
1321 retval = getaddrinfo(token, NULL, &hints, &addrinfo);
1322 if (retval != 0)
1323 {
1324 if (errbuf)
1325 get_gai_errstring(errbuf, errbuflen,
1326 "Allowed host list error: ",
1327 retval, token, NULL);
1328
1329 /*
1330 * Note that at least one call to getaddrinfo()
1331 * failed.
1332 */
1333 getaddrinfo_failed = 1;
1334
1335 /* Get next token */
1336 token = pcap_strtok_r(NULL, sep, &lasts);
1337 continue;
1338 }
1339
1340 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1341 ai_next = addrinfo;
1342 while (ai_next)
1343 {
1344 if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1345 {
1346 free(temphostlist);
1347 freeaddrinfo(addrinfo);
1348 return 0;
1349 }
1350
1351 /*
1352 * If we are here, it means that the current address does not matches
1353 * Let's try with the next one in the header chain
1354 */
1355 ai_next = ai_next->ai_next;
1356 }
1357
1358 freeaddrinfo(addrinfo);
1359 addrinfo = NULL;
1360
1361 /* Get next token */
1362 token = pcap_strtok_r(NULL, sep, &lasts);
1363 }
1364
1365 if (addrinfo)
1366 {
1367 freeaddrinfo(addrinfo);
1368 addrinfo = NULL;
1369 }
1370
1371 free(temphostlist);
1372
1373 if (getaddrinfo_failed) {
1374 /*
1375 * At least one getaddrinfo() call failed;
1376 * treat that as an error, so rpcapd knows
1377 * that it should log it locally as well
1378 * as telling the client about it.
1379 */
1380 return -2;
1381 } else {
1382 /*
1383 * All getaddrinfo() calls succeeded, but
1384 * the host wasn't in the list.
1385 */
1386 if (errbuf)
1387 pcap_snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1388 return -1;
1389 }
1390 }
1391
1392 /* No hostlist, so we have to return 'empty list' */
1393 return 1;
1394 }
1395
1396 /*
1397 * \brief Compares two addresses contained into two sockaddr_storage structures.
1398 *
1399 * This function is useful to compare two addresses, given their internal representation,
1400 * i.e. an sockaddr_storage structure.
1401 *
1402 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1403 * sockaddr_in6, properly acsted in order to be compliant to the function interface.
1404 *
1405 * This function will return '0' if the two addresses matches, '-1' if not.
1406 *
1407 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1408 * accept() call), containing the first address to compare.
1409 *
1410 * \param second: a sockaddr_storage structure containing the second address to compare.
1411 *
1412 * \return '0' if the addresses are equal, '-1' if they are different.
1413 */
1414 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
1415 {
1416 if (first->ss_family == second->ss_family)
1417 {
1418 if (first->ss_family == AF_INET)
1419 {
1420 if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
1421 &(((struct sockaddr_in *) second)->sin_addr),
1422 sizeof(struct in_addr)) == 0)
1423 return 0;
1424 }
1425 else /* address family is AF_INET6 */
1426 {
1427 if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
1428 &(((struct sockaddr_in6 *) second)->sin6_addr),
1429 sizeof(struct in6_addr)) == 0)
1430 return 0;
1431 }
1432 }
1433
1434 return -1;
1435 }
1436
1437 /*
1438 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1439 *
1440 * It is used to return the address and port the server picked for our socket on the local machine.
1441 * It works only on:
1442 * - connected sockets
1443 * - server sockets
1444 *
1445 * On unconnected client sockets it does not work because the system dynamically chooses a port
1446 * only when the socket calls a send() call.
1447 *
1448 * \param sock: the connected socket currently opened.
1449 *
1450 * \param address: it contains the address that will be returned by the function. This buffer
1451 * must be properly allocated by the user. The address can be either literal or numeric depending
1452 * on the value of 'Flags'.
1453 *
1454 * \param addrlen: the length of the 'address' buffer.
1455 *
1456 * \param port: it contains the port that will be returned by the function. This buffer
1457 * must be properly allocated by the user.
1458 *
1459 * \param portlen: the length of the 'port' buffer.
1460 *
1461 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1462 * that determine if the resulting address must be in numeric / literal form, and so on.
1463 *
1464 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1465 * error message. This buffer has to be at least 'errbuflen' in length.
1466 * It can be NULL; in this case the error cannot be printed.
1467 *
1468 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1469 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1470 *
1471 * \return It returns '-1' if this function succeeds, '0' otherwise.
1472 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1473 * In any case, the returned strings are '0' terminated.
1474 *
1475 * \warning If the socket is using a connectionless protocol, the address may not be available
1476 * until I/O occurs on the socket.
1477 */
1478 int sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1479 {
1480 struct sockaddr_storage mysockaddr;
1481 socklen_t sockaddrlen;
1482
1483
1484 sockaddrlen = sizeof(struct sockaddr_storage);
1485
1486 if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1487 {
1488 sock_geterror("getsockname()", errbuf, errbuflen);
1489 return 0;
1490 }
1491
1492 /* Returns the numeric address of the host that triggered the error */
1493 return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1494 }
1495
1496 /*
1497 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1498 *
1499 * This function is basically an extended version of the inet_ntop(), which does not exist in
1500 * Winsock because the same result can be obtained by using the getnameinfo().
1501 * However, differently from inet_ntop(), this function is able to return also literal names
1502 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1503 *
1504 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1505 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1506 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1507 * a standard IPv6 address like "::1".
1508 *
1509 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1510 * are the ones allowed in the standard getnameinfo() socket function.
1511 *
1512 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1513 * need to be translated from network form into the presentation form. This structure must be
1514 * zero-ed prior using it, and the address family field must be filled with the proper value.
1515 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1516 * calling this function.
1517 *
1518 * \param address: it contains the address that will be returned by the function. This buffer
1519 * must be properly allocated by the user. The address can be either literal or numeric depending
1520 * on the value of 'Flags'.
1521 *
1522 * \param addrlen: the length of the 'address' buffer.
1523 *
1524 * \param port: it contains the port that will be returned by the function. This buffer
1525 * must be properly allocated by the user.
1526 *
1527 * \param portlen: the length of the 'port' buffer.
1528 *
1529 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1530 * that determine if the resulting address must be in numeric / literal form, and so on.
1531 *
1532 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1533 * error message. This buffer has to be at least 'errbuflen' in length.
1534 * It can be NULL; in this case the error cannot be printed.
1535 *
1536 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1537 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1538 *
1539 * \return It returns '-1' if this function succeeds, '0' otherwise.
1540 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1541 * and 'port'.
1542 * In any case, the returned strings are '0' terminated.
1543 */
1544 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1545 {
1546 socklen_t sockaddrlen;
1547 int retval; /* Variable that keeps the return value; */
1548
1549 retval = -1;
1550
1551 #ifdef _WIN32
1552 if (sockaddr->ss_family == AF_INET)
1553 sockaddrlen = sizeof(struct sockaddr_in);
1554 else
1555 sockaddrlen = sizeof(struct sockaddr_in6);
1556 #else
1557 sockaddrlen = sizeof(struct sockaddr_storage);
1558 #endif
1559
1560 if ((flags & NI_NUMERICHOST) == 0) /* Check that we want literal names */
1561 {
1562 if ((sockaddr->ss_family == AF_INET6) &&
1563 (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))
1564 {
1565 if (address)
1566 pcap_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
1567 return retval;
1568 }
1569 }
1570
1571 if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
1572 {
1573 /* If the user wants to receive an error message */
1574 if (errbuf)
1575 {
1576 sock_geterror("getnameinfo()", errbuf, errbuflen);
1577 errbuf[errbuflen - 1] = 0;
1578 }
1579
1580 if (address)
1581 {
1582 pcap_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
1583 address[addrlen - 1] = 0;
1584 }
1585
1586 if (port)
1587 {
1588 pcap_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
1589 port[portlen - 1] = 0;
1590 }
1591
1592 retval = 0;
1593 }
1594
1595 return retval;
1596 }
1597
1598 /*
1599 * \brief It translates an address from the 'presentation' form into the 'network' form.
1600 *
1601 * This function basically replaces inet_pton(), which does not exist in Winsock because
1602 * the same result can be obtained by using the getaddrinfo().
1603 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
1604 * like in inet_pton() ) and a literal name (e.g. 'localhost').
1605 *
1606 * This function does the reverse job of sock_getascii_addrport().
1607 *
1608 * \param address: a zero-terminated string which contains the name you have to
1609 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
1610 *
1611 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
1612 * 'network' form of the requested address.
1613 *
1614 * \param addr_family: a constant which can assume the following values:
1615 * - 'AF_INET' if we want to ping an IPv4 host
1616 * - 'AF_INET6' if we want to ping an IPv6 host
1617 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
1618 *
1619 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1620 * error message. This buffer has to be at least 'errbuflen' in length.
1621 * It can be NULL; in this case the error cannot be printed.
1622 *
1623 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1624 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1625 *
1626 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
1627 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
1628 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
1629 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
1630 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
1631 *
1632 * \warning The sockaddr_storage structure MUST be allocated by the user.
1633 */
1634 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
1635 {
1636 int retval;
1637 struct addrinfo *addrinfo;
1638 struct addrinfo hints;
1639
1640 memset(&hints, 0, sizeof(hints));
1641
1642 hints.ai_family = addr_family;
1643
1644 if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
1645 return 0;
1646
1647 if (addrinfo->ai_family == PF_INET)
1648 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
1649 else
1650 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
1651
1652 if (addrinfo->ai_next != NULL)
1653 {
1654 freeaddrinfo(addrinfo);
1655
1656 if (errbuf)
1657 pcap_snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
1658 return -2;
1659 }
1660
1661 freeaddrinfo(addrinfo);
1662 return -1;
1663 }