]> The Tcpdump Group git mirrors - libpcap/blob - sockutils.c
Don't define SOCKET ourselves.
[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 * With 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 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
124 const uint8_t *fuzzBuffer;
125 size_t fuzzSize;
126 size_t fuzzPos;
127
128 void sock_initfuzz(const uint8_t *Data, size_t Size) {
129 fuzzPos = 0;
130 fuzzSize = Size;
131 fuzzBuffer = Data;
132 }
133
134 static int fuzz_recv(char *bufp, int remaining) {
135 if (remaining > fuzzSize - fuzzPos) {
136 remaining = fuzzSize - fuzzPos;
137 }
138 if (fuzzPos < fuzzSize) {
139 memcpy(bufp, fuzzBuffer + fuzzPos, remaining);
140 }
141 fuzzPos += remaining;
142 return remaining;
143 }
144 #endif
145
146 int sock_geterrcode(void)
147 {
148 #ifdef _WIN32
149 return GetLastError();
150 #else
151 return errno;
152 #endif
153 }
154
155 /*
156 * Format an error message given an errno value (UN*X) or a Winsock error
157 * (Windows).
158 */
159 void sock_vfmterrmsg(char *errbuf, size_t errbuflen, int errcode,
160 const char *fmt, va_list ap)
161 {
162 if (errbuf == NULL)
163 return;
164
165 #ifdef _WIN32
166 pcapint_vfmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
167 fmt, ap);
168 #else
169 pcapint_vfmt_errmsg_for_errno(errbuf, errbuflen, errcode,
170 fmt, ap);
171 #endif
172 }
173
174 void sock_fmterrmsg(char *errbuf, size_t errbuflen, int errcode,
175 const char *fmt, ...)
176 {
177 va_list ap;
178
179 va_start(ap, fmt);
180 sock_vfmterrmsg(errbuf, errbuflen, errcode, fmt, ap);
181 va_end(ap);
182 }
183
184 /*
185 * Format an error message for the last socket error.
186 */
187 void sock_geterrmsg(char *errbuf, size_t errbuflen, const char *fmt, ...)
188 {
189 va_list ap;
190
191 va_start(ap, fmt);
192 sock_vfmterrmsg(errbuf, errbuflen, sock_geterrcode(), fmt, ap);
193 va_end(ap);
194 }
195
196 /*
197 * Types of error.
198 *
199 * These are sorted by how likely they are to be the "underlying" problem,
200 * so that lower-rated errors for a given address in a given family
201 * should not overwrite higher-rated errors for another address in that
202 * family, and higher-rated errors should overwrite lower-rated errors.
203 */
204 typedef enum {
205 SOCK_CONNERR, /* connection error */
206 SOCK_HOSTERR, /* host error */
207 SOCK_NETERR, /* network error */
208 SOCK_AFNOTSUPERR, /* address family not supported */
209 SOCK_UNKNOWNERR, /* unknown error */
210 SOCK_NOERR /* no error */
211 } sock_errtype;
212
213 static sock_errtype sock_geterrtype(int errcode)
214 {
215 switch (errcode) {
216
217 #ifdef _WIN32
218 case WSAECONNRESET:
219 case WSAECONNABORTED:
220 case WSAECONNREFUSED:
221 #else
222 case ECONNRESET:
223 case ECONNABORTED:
224 case ECONNREFUSED:
225 #endif
226 /*
227 * Connection error; this means the problem is probably
228 * that there's no server set up on the remote machine,
229 * or that it is set up, but it's IPv4-only or IPv6-only
230 * and we're trying the wrong address family.
231 *
232 * These overwrite all other errors, as they indicate
233 * that, even if something else went wrong in another
234 * attempt, this probably wouldn't work even if the
235 * other problems were fixed.
236 */
237 return (SOCK_CONNERR);
238
239 #ifdef _WIN32
240 case WSAENETUNREACH:
241 case WSAETIMEDOUT:
242 case WSAEHOSTDOWN:
243 case WSAEHOSTUNREACH:
244 #else
245 case ENETUNREACH:
246 case ETIMEDOUT:
247 case EHOSTDOWN:
248 case EHOSTUNREACH:
249 #endif
250 /*
251 * Network errors that could be IPv4-specific, IPv6-
252 * specific, or present with both.
253 *
254 * Don't overwrite connection errors, but overwrite
255 * everything else.
256 */
257 return (SOCK_HOSTERR);
258
259 #ifdef _WIN32
260 case WSAENETDOWN:
261 case WSAENETRESET:
262 #else
263 case ENETDOWN:
264 case ENETRESET:
265 #endif
266 /*
267 * Network error; this means we don't know whether
268 * there's a server set up on the remote machine,
269 * and we don't have a reason to believe that IPv6
270 * any worse or better than IPv4.
271 *
272 * These probably indicate a local failure, e.g.
273 * an interface is down.
274 *
275 * Don't overwrite connection errors or host errors,
276 * but overwrite everything else.
277 */
278 return (SOCK_NETERR);
279
280 #ifdef _WIN32
281 case WSAEAFNOSUPPORT:
282 #else
283 case EAFNOSUPPORT:
284 #endif
285 /*
286 * "Address family not supported" probably means
287 * "No soup^WIPv6 for you!".
288 *
289 * Don't overwrite connection errors, host errors, or
290 * network errors (none of which we should get for this
291 * address family if it's not supported), but overwrite
292 * everything else.
293 */
294 return (SOCK_AFNOTSUPERR);
295
296 default:
297 /*
298 * Anything else.
299 *
300 * Don't overwrite any errors.
301 */
302 return (SOCK_UNKNOWNERR);
303 }
304 }
305
306 /*
307 * \brief This function initializes the socket mechanism if it hasn't
308 * already been initialized or reinitializes it after it has been
309 * cleaned up.
310 *
311 * On UN*Xes, it doesn't need to do anything; on Windows, it needs to
312 * initialize Winsock.
313 *
314 * \param errbuf: a pointer to an user-allocated buffer that will contain
315 * the complete error message. This buffer has to be at least 'errbuflen'
316 * in length. It can be NULL; in this case no error message is supplied.
317 *
318 * \param errbuflen: length of the buffer that will contains the error.
319 * The error message cannot be larger than 'errbuflen - 1' because the
320 * last char is reserved for the string terminator.
321 *
322 * \return '0' if everything is fine, '-1' if some errors occurred. The
323 * error message is returned in the buffer pointed to by 'errbuf' variable.
324 */
325 #ifdef _WIN32
326 int sock_init(char *errbuf, int errbuflen)
327 {
328 if (sockcount == 0)
329 {
330 WSADATA wsaData; /* helper variable needed to initialize Winsock */
331
332 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
333 WINSOCK_MINOR_VERSION), &wsaData) != 0)
334 {
335 if (errbuf)
336 snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
337
338 WSACleanup();
339
340 return -1;
341 }
342 }
343
344 sockcount++;
345 return 0;
346 }
347 #else
348 int sock_init(char *errbuf _U_, int errbuflen _U_)
349 {
350 /*
351 * Nothing to do on UN*Xes.
352 */
353 return 0;
354 }
355 #endif
356
357 /*
358 * \brief This function cleans up the socket mechanism if we have no
359 * sockets left open.
360 *
361 * On UN*Xes, it doesn't need to do anything; on Windows, it needs
362 * to clean up Winsock.
363 *
364 * \return No error values.
365 */
366 void sock_cleanup(void)
367 {
368 #ifdef _WIN32
369 sockcount--;
370
371 if (sockcount == 0)
372 WSACleanup();
373 #endif
374 }
375
376 /*
377 * \brief It checks if the sockaddr variable contains a multicast address.
378 *
379 * \return '0' if the address is multicast, '-1' if it is not.
380 */
381 static int sock_ismcastaddr(const struct sockaddr *saddr)
382 {
383 if (saddr->sa_family == PF_INET)
384 {
385 struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
386 if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
387 else return -1;
388 }
389 else
390 {
391 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
392 if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
393 else return -1;
394 }
395 }
396
397 struct addr_status {
398 struct addrinfo *info;
399 int errcode;
400 sock_errtype errtype;
401 };
402
403 /*
404 * Sort by IPv4 address vs. IPv6 address.
405 */
406 static int compare_addrs_to_try_by_address_family(const void *a, const void *b)
407 {
408 const struct addr_status *addr_a = (const struct addr_status *)a;
409 const struct addr_status *addr_b = (const struct addr_status *)b;
410
411 return addr_a->info->ai_family - addr_b->info->ai_family;
412 }
413
414 /*
415 * Sort by error type and, within a given error type, by error code and,
416 * within a given error code, by IPv4 address vs. IPv6 address.
417 */
418 static int compare_addrs_to_try_by_status(const void *a, const void *b)
419 {
420 const struct addr_status *addr_a = (const struct addr_status *)a;
421 const struct addr_status *addr_b = (const struct addr_status *)b;
422
423 if (addr_a->errtype == addr_b->errtype)
424 {
425 if (addr_a->errcode == addr_b->errcode)
426 {
427 return addr_a->info->ai_family - addr_b->info->ai_family;
428 }
429 return addr_a->errcode - addr_b->errcode;
430 }
431
432 return addr_a->errtype - addr_b->errtype;
433 }
434
435 static PCAP_SOCKET sock_create_socket(struct addrinfo *addrinfo, char *errbuf,
436 int errbuflen)
437 {
438 PCAP_SOCKET sock;
439 #ifdef SO_NOSIGPIPE
440 int on = 1;
441 #endif
442
443 sock = socket(addrinfo->ai_family, addrinfo->ai_socktype,
444 addrinfo->ai_protocol);
445 if (sock == INVALID_SOCKET)
446 {
447 sock_geterrmsg(errbuf, errbuflen, "socket() failed");
448 return INVALID_SOCKET;
449 }
450
451 /*
452 * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
453 * have to deal with signals if the peer closes the connection,
454 * especially in client programs, which may not even be aware that
455 * they're sending to sockets.
456 */
457 #ifdef SO_NOSIGPIPE
458 if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
459 sizeof (int)) == -1)
460 {
461 sock_geterrmsg(errbuf, errbuflen,
462 "setsockopt(SO_NOSIGPIPE) failed");
463 closesocket(sock);
464 return INVALID_SOCKET;
465 }
466 #endif
467 return sock;
468 }
469
470 /*
471 * \brief It initializes a network connection both from the client and the server side.
472 *
473 * In case of a client socket, this function calls socket() and connect().
474 * In the meanwhile, it checks for any socket error.
475 * If an error occurs, it writes the error message into 'errbuf'.
476 *
477 * In case of a server socket, the function calls socket(), bind() and listen().
478 *
479 * This function is usually preceded by the sock_initaddress().
480 *
481 * \param host: for client sockets, the host name to which we're trying
482 * to connect.
483 *
484 * \param addrinfo: pointer to an addrinfo variable which will be used to
485 * open the socket and such. This variable is the one returned by the previous call to
486 * sock_initaddress().
487 *
488 * \param server: '1' if this is a server socket, '0' otherwise.
489 *
490 * \param nconn: number of the connections that are allowed to wait into the listen() call.
491 * This value has no meanings in case of a client socket.
492 *
493 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
494 * error message. This buffer has to be at least 'errbuflen' in length.
495 * It can be NULL; in this case the error cannot be printed.
496 *
497 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
498 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
499 *
500 * \return the socket that has been opened (that has to be used in the following sockets calls)
501 * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
502 * in the 'errbuf' variable.
503 */
504 PCAP_SOCKET sock_open(const char *host, struct addrinfo *addrinfo,
505 int server, int nconn, char *errbuf, int errbuflen)
506 {
507 PCAP_SOCKET sock;
508
509 /* This is a server socket */
510 if (server)
511 {
512 int on;
513
514 /*
515 * Attempt to create the socket.
516 */
517 sock = sock_create_socket(addrinfo, errbuf, errbuflen);
518 if (sock == INVALID_SOCKET)
519 {
520 return INVALID_SOCKET;
521 }
522
523 /*
524 * Allow a new server to bind the socket after the old one
525 * exited, even if lingering sockets are still present.
526 *
527 * Don't treat an error as a failure.
528 */
529 on = 1;
530 (void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
531 (char *)&on, sizeof (on));
532
533 #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
534 /*
535 * Force the use of IPv6-only addresses.
536 *
537 * RFC 3493 indicates that you can support IPv4 on an
538 * IPv6 socket:
539 *
540 * https://tools.ietf.org/html/rfc3493#section-3.7
541 *
542 * and that this is the default behavior. This means
543 * that if we first create an IPv6 socket bound to the
544 * "any" address, it is, in effect, also bound to the
545 * IPv4 "any" address, so when we create an IPv4 socket
546 * and try to bind it to the IPv4 "any" address, it gets
547 * EADDRINUSE.
548 *
549 * Not all network stacks support IPv4 on IPv6 sockets;
550 * pre-NT 6 Windows stacks don't support it, and the
551 * OpenBSD stack doesn't support it for security reasons
552 * (see the OpenBSD inet6(4) man page). Therefore, we
553 * don't want to rely on this behavior.
554 *
555 * So we try to disable it, using either the IPV6_V6ONLY
556 * option from RFC 3493:
557 *
558 * https://tools.ietf.org/html/rfc3493#section-5.3
559 *
560 * or the IPV6_BINDV6ONLY option from older UN*Xes.
561 */
562 #ifndef IPV6_V6ONLY
563 /* For older systems */
564 #define IPV6_V6ONLY IPV6_BINDV6ONLY
565 #endif /* IPV6_V6ONLY */
566 if (addrinfo->ai_family == PF_INET6)
567 {
568 on = 1;
569 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
570 (char *)&on, sizeof (int)) == -1)
571 {
572 if (errbuf)
573 snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
574 closesocket(sock);
575 return INVALID_SOCKET;
576 }
577 }
578 #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
579
580 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
581 if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
582 {
583 sock_geterrmsg(errbuf, errbuflen, "bind() failed");
584 closesocket(sock);
585 return INVALID_SOCKET;
586 }
587
588 if (addrinfo->ai_socktype == SOCK_STREAM)
589 if (listen(sock, nconn) == -1)
590 {
591 sock_geterrmsg(errbuf, errbuflen,
592 "listen() failed");
593 closesocket(sock);
594 return INVALID_SOCKET;
595 }
596
597 /* server side ended */
598 return sock;
599 }
600 else /* we're the client */
601 {
602 struct addr_status *addrs_to_try;
603 struct addrinfo *tempaddrinfo;
604 size_t numaddrinfos;
605 size_t i;
606 int current_af = AF_UNSPEC;
607
608 /*
609 * We have to loop though all the addrinfos returned.
610 * For instance, we can have both IPv6 and IPv4 addresses,
611 * but the service we're trying to connect to is unavailable
612 * in IPv6, so we have to try in IPv4 as well.
613 *
614 * How many addrinfos do we have?
615 */
616 numaddrinfos = 0;
617 for (tempaddrinfo = addrinfo; tempaddrinfo != NULL;
618 tempaddrinfo = tempaddrinfo->ai_next)
619 {
620 numaddrinfos++;
621 }
622
623 if (numaddrinfos == 0)
624 {
625 snprintf(errbuf, errbuflen,
626 "There are no addresses in the address list");
627 return INVALID_SOCKET;
628 }
629
630 /*
631 * Allocate an array of struct addr_status and fill it in.
632 */
633 addrs_to_try = calloc(numaddrinfos, sizeof *addrs_to_try);
634 if (addrs_to_try == NULL)
635 {
636 snprintf(errbuf, errbuflen,
637 "Out of memory connecting to %s", host);
638 return INVALID_SOCKET;
639 }
640
641 for (tempaddrinfo = addrinfo, i = 0; tempaddrinfo != NULL;
642 tempaddrinfo = tempaddrinfo->ai_next, i++)
643 {
644 addrs_to_try[i].info = tempaddrinfo;
645 addrs_to_try[i].errcode = 0;
646 addrs_to_try[i].errtype = SOCK_NOERR;
647 }
648
649 /*
650 * Sort the structures to put the IPv4 addresses before the
651 * IPv6 addresses; we will have to create an IPv4 socket
652 * for the IPv4 addresses and an IPv6 socket for the IPv6
653 * addresses (one of the arguments to socket() is the
654 * address/protocol family to use, and IPv4 and IPv6 are
655 * separate address/protocol families).
656 */
657 qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
658 compare_addrs_to_try_by_address_family);
659
660 /* Start out with no socket. */
661 sock = INVALID_SOCKET;
662
663 /*
664 * Now try them all.
665 */
666 for (i = 0; i < numaddrinfos; i++)
667 {
668 tempaddrinfo = addrs_to_try[i].info;
669 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
670 break;
671 #endif
672 /*
673 * If we have a socket, but it's for a
674 * different address family, close it.
675 */
676 if (sock != INVALID_SOCKET &&
677 current_af != tempaddrinfo->ai_family)
678 {
679 closesocket(sock);
680 sock = INVALID_SOCKET;
681 }
682
683 /*
684 * If we don't have a socket, open one
685 * for *this* address's address family.
686 */
687 if (sock == INVALID_SOCKET)
688 {
689 sock = sock_create_socket(tempaddrinfo,
690 errbuf, errbuflen);
691 if (sock == INVALID_SOCKET)
692 {
693 free(addrs_to_try);
694 return INVALID_SOCKET;
695 }
696 }
697 if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
698 {
699 addrs_to_try[i].errcode = sock_geterrcode();
700 addrs_to_try[i].errtype =
701 sock_geterrtype(addrs_to_try[i].errcode);
702 }
703 else
704 break;
705 }
706
707 /*
708 * Check how we exited from the previous loop.
709 * If tempaddrinfo is equal to NULL, it means that all
710 * the connect() attempts failed. Construct an
711 * error message.
712 */
713 if (i == numaddrinfos)
714 {
715 int same_error_for_all;
716 int first_error;
717
718 closesocket(sock);
719
720 /*
721 * Sort the statuses to group together categories
722 * of errors, errors within categories, and
723 * address families within error sets.
724 */
725 qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
726 compare_addrs_to_try_by_status);
727
728 /*
729 * Are all the errors the same?
730 */
731 same_error_for_all = 1;
732 first_error = addrs_to_try[0].errcode;
733 for (i = 1; i < numaddrinfos; i++)
734 {
735 if (addrs_to_try[i].errcode != first_error)
736 {
737 same_error_for_all = 0;
738 break;
739 }
740 }
741
742 if (same_error_for_all) {
743 /*
744 * Yes. No need to show the IP
745 * addresses.
746 */
747 if (addrs_to_try[0].errtype == SOCK_CONNERR) {
748 /*
749 * Connection error; note that
750 * the daemon might not be set
751 * up correctly, or set up at all.
752 */
753 sock_fmterrmsg(errbuf, errbuflen,
754 addrs_to_try[0].errcode,
755 "Is the server properly installed? Cannot connect to %s",
756 host);
757 } else {
758 sock_fmterrmsg(errbuf, errbuflen,
759 addrs_to_try[0].errcode,
760 "Cannot connect to %s", host);
761 }
762 } else {
763 /*
764 * Show all the errors and the IP addresses
765 * to which they apply.
766 */
767 char *errbufptr;
768 size_t bufspaceleft;
769 size_t msglen;
770
771 snprintf(errbuf, errbuflen,
772 "Connect to %s failed: ", host);
773
774 msglen = strlen(errbuf);
775 errbufptr = errbuf + msglen;
776 bufspaceleft = errbuflen - msglen;
777
778 for (i = 0; i < numaddrinfos &&
779 addrs_to_try[i].errcode != SOCK_NOERR;
780 i++)
781 {
782 /*
783 * Get the string for the address
784 * and port that got this error.
785 */
786 sock_getascii_addrport((struct sockaddr_storage *) addrs_to_try[i].info->ai_addr,
787 errbufptr, (int)bufspaceleft,
788 NULL, 0, NI_NUMERICHOST, NULL, 0);
789 msglen = strlen(errbuf);
790 errbufptr = errbuf + msglen;
791 bufspaceleft = errbuflen - msglen;
792
793 if (i + 1 < numaddrinfos &&
794 addrs_to_try[i + 1].errcode == addrs_to_try[i].errcode)
795 {
796 /*
797 * There's another error
798 * after this, and it has
799 * the same error code.
800 *
801 * Append a comma, as the
802 * list of addresses with
803 * this error has another
804 * entry.
805 */
806 snprintf(errbufptr, bufspaceleft,
807 ", ");
808 }
809 else
810 {
811 /*
812 * Either there are no
813 * more errors after this,
814 * or the next error is
815 * different.
816 *
817 * Append a colon and
818 * the message for tis
819 * error, followed by a
820 * comma if there are
821 * more errors.
822 */
823 sock_fmterrmsg(errbufptr,
824 bufspaceleft,
825 addrs_to_try[i].errcode,
826 "%s", "");
827 msglen = strlen(errbuf);
828 errbufptr = errbuf + msglen;
829 bufspaceleft = errbuflen - msglen;
830
831 if (i + 1 < numaddrinfos &&
832 addrs_to_try[i + 1].errcode != SOCK_NOERR)
833 {
834 /*
835 * More to come.
836 */
837 snprintf(errbufptr,
838 bufspaceleft,
839 ", ");
840 }
841 }
842 msglen = strlen(errbuf);
843 errbufptr = errbuf + msglen;
844 bufspaceleft = errbuflen - msglen;
845 }
846 }
847 free(addrs_to_try);
848 return INVALID_SOCKET;
849 }
850 else
851 {
852 free(addrs_to_try);
853 return sock;
854 }
855 }
856 }
857
858 /*
859 * \brief Closes the present (TCP and UDP) socket connection.
860 *
861 * This function sends a shutdown() on the socket in order to disable send() calls
862 * (while recv() ones are still allowed). Then, it closes the socket.
863 *
864 * \param sock: the socket identifier of the connection that has to be closed.
865 *
866 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
867 * error message. This buffer has to be at least 'errbuflen' in length.
868 * It can be NULL; in this case the error cannot be printed.
869 *
870 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
871 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
872 *
873 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
874 * in the 'errbuf' variable.
875 */
876 int sock_close(PCAP_SOCKET sock, char *errbuf, int errbuflen)
877 {
878 /*
879 * SHUT_WR: subsequent calls to the send function are disallowed.
880 * For TCP sockets, a FIN will be sent after all data is sent and
881 * acknowledged by the Server.
882 */
883 if (shutdown(sock, SHUT_WR))
884 {
885 sock_geterrmsg(errbuf, errbuflen, "shutdown() failed");
886 /* close the socket anyway */
887 closesocket(sock);
888 return -1;
889 }
890
891 closesocket(sock);
892 return 0;
893 }
894
895 /*
896 * gai_strerror() has some problems:
897 *
898 * 1) on Windows, Microsoft explicitly says it's not thread-safe;
899 * 2) on UN*X, the Single UNIX Specification doesn't say it *is*
900 * thread-safe, so an implementation might use a static buffer
901 * for unknown error codes;
902 * 3) the error message for the most likely error, EAI_NONAME, is
903 * truly horrible on several platforms ("nodename nor servname
904 * provided, or not known"? It's typically going to be "not
905 * known", not "oopsie, I passed null pointers for the host name
906 * and service name", not to mention they forgot the "neither");
907 *
908 * so we roll our own.
909 */
910 static void
911 get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
912 const char *hostname, const char *portname)
913 {
914 char hostport[PCAP_ERRBUF_SIZE];
915
916 if (hostname != NULL && portname != NULL)
917 snprintf(hostport, PCAP_ERRBUF_SIZE, "host and port %s:%s",
918 hostname, portname);
919 else if (hostname != NULL)
920 snprintf(hostport, PCAP_ERRBUF_SIZE, "host %s",
921 hostname);
922 else if (portname != NULL)
923 snprintf(hostport, PCAP_ERRBUF_SIZE, "port %s",
924 portname);
925 else
926 snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
927 switch (err)
928 {
929 #ifdef EAI_ADDRFAMILY
930 case EAI_ADDRFAMILY:
931 snprintf(errbuf, errbuflen,
932 "%sAddress family for %s not supported",
933 prefix, hostport);
934 break;
935 #endif
936
937 case EAI_AGAIN:
938 snprintf(errbuf, errbuflen,
939 "%s%s could not be resolved at this time",
940 prefix, hostport);
941 break;
942
943 case EAI_BADFLAGS:
944 snprintf(errbuf, errbuflen,
945 "%sThe ai_flags parameter for looking up %s had an invalid value",
946 prefix, hostport);
947 break;
948
949 case EAI_FAIL:
950 snprintf(errbuf, errbuflen,
951 "%sA non-recoverable error occurred when attempting to resolve %s",
952 prefix, hostport);
953 break;
954
955 case EAI_FAMILY:
956 snprintf(errbuf, errbuflen,
957 "%sThe address family for looking up %s was not recognized",
958 prefix, hostport);
959 break;
960
961 case EAI_MEMORY:
962 snprintf(errbuf, errbuflen,
963 "%sOut of memory trying to allocate storage when looking up %s",
964 prefix, hostport);
965 break;
966
967 /*
968 * RFC 2553 had both EAI_NODATA and EAI_NONAME.
969 *
970 * RFC 3493 has only EAI_NONAME.
971 *
972 * Some implementations define EAI_NODATA and EAI_NONAME
973 * to the same value, others don't. If EAI_NODATA is
974 * defined and isn't the same as EAI_NONAME, we handle
975 * EAI_NODATA.
976 */
977 #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
978 case EAI_NODATA:
979 snprintf(errbuf, errbuflen,
980 "%sNo address associated with %s",
981 prefix, hostport);
982 break;
983 #endif
984
985 case EAI_NONAME:
986 snprintf(errbuf, errbuflen,
987 "%sThe %s couldn't be resolved",
988 prefix, hostport);
989 break;
990
991 case EAI_SERVICE:
992 snprintf(errbuf, errbuflen,
993 "%sThe service value specified when looking up %s as not recognized for the socket type",
994 prefix, hostport);
995 break;
996
997 case EAI_SOCKTYPE:
998 snprintf(errbuf, errbuflen,
999 "%sThe socket type specified when looking up %s as not recognized",
1000 prefix, hostport);
1001 break;
1002
1003 #ifdef EAI_SYSTEM
1004 case EAI_SYSTEM:
1005 /*
1006 * Assumed to be UN*X.
1007 */
1008 pcapint_fmt_errmsg_for_errno(errbuf, errbuflen, errno,
1009 "%sAn error occurred when looking up %s",
1010 prefix, hostport);
1011 break;
1012 #endif
1013
1014 #ifdef EAI_BADHINTS
1015 case EAI_BADHINTS:
1016 snprintf(errbuf, errbuflen,
1017 "%sInvalid value for hints when looking up %s",
1018 prefix, hostport);
1019 break;
1020 #endif
1021
1022 #ifdef EAI_PROTOCOL
1023 case EAI_PROTOCOL:
1024 snprintf(errbuf, errbuflen,
1025 "%sResolved protocol when looking up %s is unknown",
1026 prefix, hostport);
1027 break;
1028 #endif
1029
1030 #ifdef EAI_OVERFLOW
1031 case EAI_OVERFLOW:
1032 snprintf(errbuf, errbuflen,
1033 "%sArgument buffer overflow when looking up %s",
1034 prefix, hostport);
1035 break;
1036 #endif
1037
1038 default:
1039 snprintf(errbuf, errbuflen,
1040 "%sgetaddrinfo() error %d when looking up %s",
1041 prefix, err, hostport);
1042 break;
1043 }
1044 }
1045
1046 /*
1047 * \brief Checks that the address, port and flags given are valid and it returns an 'addrinfo' structure.
1048 *
1049 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
1050 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
1051 * If an error occurs, it writes the error message into 'errbuf'.
1052 *
1053 * \param host: a pointer to a string identifying the host. It can be
1054 * a host name, a numeric literal address, or NULL or "" (useful
1055 * in case of a server socket which has to bind to all addresses).
1056 *
1057 * \param port: a pointer to a user-allocated buffer containing the network port to use.
1058 *
1059 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
1060 * addrinfo structure appropriately.
1061 *
1062 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
1063 * (passed by reference), which will be allocated by this function and returned back to the caller.
1064 * This variable will be used in the next sockets calls.
1065 *
1066 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1067 * error message. This buffer has to be at least 'errbuflen' in length.
1068 * It can be NULL; in this case the error cannot be printed.
1069 *
1070 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1071 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1072 *
1073 * \return a pointer to the first element in a list of addrinfo structures
1074 * if everything is fine, NULL if some errors occurred. The error message
1075 * is returned in the 'errbuf' variable.
1076 *
1077 * \warning The list of addrinfo structures returned has to be deleted by
1078 * the programmer by calling freeaddrinfo() when it is no longer needed.
1079 *
1080 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
1081 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
1082 * the programmer to look at that function in order to set the 'hints' variable appropriately.
1083 */
1084 struct addrinfo *sock_initaddress(const char *host, const char *port,
1085 struct addrinfo *hints, char *errbuf, int errbuflen)
1086 {
1087 struct addrinfo *addrinfo;
1088 int retval;
1089
1090 /*
1091 * We allow both the host and port to be null, but getaddrinfo()
1092 * is not guaranteed to do so; to handle that, if port is null,
1093 * we provide "0" as the port number.
1094 *
1095 * This results in better error messages from get_gai_errstring(),
1096 * as those messages won't talk about a problem with the port if
1097 * no port was specified.
1098 */
1099 retval = getaddrinfo(host, port == NULL ? "0" : port, hints, &addrinfo);
1100 if (retval != 0)
1101 {
1102 /*
1103 * That call failed.
1104 * Determine whether the problem is that the host is bad.
1105 */
1106 if (errbuf)
1107 {
1108 if (host != NULL && port != NULL) {
1109 /*
1110 * Try with just a host, to distinguish
1111 * between "host is bad" and "port is
1112 * bad".
1113 */
1114 int try_retval;
1115
1116 try_retval = getaddrinfo(host, NULL, hints,
1117 &addrinfo);
1118 if (try_retval == 0) {
1119 /*
1120 * Worked with just the host,
1121 * so assume the problem is
1122 * with the port.
1123 *
1124 * Free up the address info first.
1125 */
1126 freeaddrinfo(addrinfo);
1127 get_gai_errstring(errbuf, errbuflen,
1128 "", retval, NULL, port);
1129 } else {
1130 /*
1131 * Didn't work with just the host,
1132 * so assume the problem is
1133 * with the host; we assume
1134 * the original error indicates
1135 * the underlying problem.
1136 */
1137 get_gai_errstring(errbuf, errbuflen,
1138 "", retval, host, NULL);
1139 }
1140 } else {
1141 /*
1142 * Either the host or port was null, so
1143 * there's nothing to determine; report
1144 * the error from the original call.
1145 */
1146 get_gai_errstring(errbuf, errbuflen, "",
1147 retval, host, port);
1148 }
1149 }
1150 return NULL;
1151 }
1152 /*
1153 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
1154 * addrinfo has more han one pointers
1155 */
1156
1157 /*
1158 * This software only supports PF_INET and PF_INET6.
1159 *
1160 * XXX - should we just check that at least *one* address is
1161 * either PF_INET or PF_INET6, and, when using the list,
1162 * ignore all addresses that are neither? (What, no IPX
1163 * support? :-))
1164 */
1165 if ((addrinfo->ai_family != PF_INET) &&
1166 (addrinfo->ai_family != PF_INET6))
1167 {
1168 if (errbuf)
1169 snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
1170 freeaddrinfo(addrinfo);
1171 return NULL;
1172 }
1173
1174 /*
1175 * You can't do multicast (or broadcast) TCP.
1176 */
1177 if ((addrinfo->ai_socktype == SOCK_STREAM) &&
1178 (sock_ismcastaddr(addrinfo->ai_addr) == 0))
1179 {
1180 if (errbuf)
1181 snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
1182 freeaddrinfo(addrinfo);
1183 return NULL;
1184 }
1185
1186 return addrinfo;
1187 }
1188
1189 /*
1190 * \brief It sends the amount of data contained into 'buffer' on the given socket.
1191 *
1192 * This function basically calls the send() socket function and it checks that all
1193 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
1194 * it writes the error message into 'errbuf'.
1195 * In case the socket buffer does not have enough space, it loops until all data
1196 * has been sent.
1197 *
1198 * \param socket: the connected socket currently opened.
1199 *
1200 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
1201 *
1202 * \param size: number of bytes that have to be sent.
1203 *
1204 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1205 * error message. This buffer has to be at least 'errbuflen' in length.
1206 * It can be NULL; in this case the error cannot be printed.
1207 *
1208 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1209 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1210 *
1211 * \return '0' if everything is fine, '-1' if an error other than
1212 * "connection reset" or "peer has closed the receive side" occurred,
1213 * '-2' if we got one of those errors.
1214 * For errors, an error message is returned in the 'errbuf' variable.
1215 */
1216 int sock_send(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, const char *buffer,
1217 size_t size, char *errbuf, int errbuflen)
1218 {
1219 int remaining;
1220 ssize_t nsent;
1221
1222 if (size > INT_MAX)
1223 {
1224 if (errbuf)
1225 {
1226 snprintf(errbuf, errbuflen,
1227 "Can't send more than %u bytes with sock_send",
1228 INT_MAX);
1229 }
1230 return -1;
1231 }
1232 remaining = (int)size;
1233
1234 do {
1235 #ifdef HAVE_OPENSSL
1236 if (ssl) return ssl_send(ssl, buffer, remaining, errbuf, errbuflen);
1237 #endif
1238
1239 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1240 nsent = remaining;
1241 #else
1242 #ifdef MSG_NOSIGNAL
1243 /*
1244 * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
1245 * on errors on stream-oriented sockets when the other
1246 * end breaks the connection.
1247 * The EPIPE error is still returned.
1248 */
1249 nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
1250 #else
1251 nsent = send(sock, buffer, remaining, 0);
1252 #endif
1253 #endif //FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1254
1255 if (nsent == -1)
1256 {
1257 /*
1258 * If the client closed the connection out from
1259 * under us, there's no need to log that as an
1260 * error.
1261 */
1262 int errcode;
1263
1264 #ifdef _WIN32
1265 errcode = GetLastError();
1266 if (errcode == WSAECONNRESET ||
1267 errcode == WSAECONNABORTED)
1268 {
1269 /*
1270 * WSAECONNABORTED appears to be the error
1271 * returned in Winsock when you try to send
1272 * on a connection where the peer has closed
1273 * the receive side.
1274 */
1275 return -2;
1276 }
1277 sock_fmterrmsg(errbuf, errbuflen, errcode,
1278 "send() failed");
1279 #else
1280 errcode = errno;
1281 if (errcode == ECONNRESET || errcode == EPIPE)
1282 {
1283 /*
1284 * EPIPE is what's returned on UN*X when
1285 * you try to send on a connection when
1286 * the peer has closed the receive side.
1287 */
1288 return -2;
1289 }
1290 sock_fmterrmsg(errbuf, errbuflen, errcode,
1291 "send() failed");
1292 #endif
1293 return -1;
1294 }
1295
1296 remaining -= nsent;
1297 buffer += nsent;
1298 } while (remaining != 0);
1299
1300 return 0;
1301 }
1302
1303 /*
1304 * \brief It copies the amount of data contained in 'data' into 'outbuf'.
1305 * and it checks for buffer overflows.
1306 *
1307 * This function basically copies 'size' bytes of data contained in 'data'
1308 * into 'outbuf', starting at offset 'offset'. Before that, it checks that the
1309 * resulting buffer will not be larger than 'totsize'. Finally, it updates
1310 * the 'offset' variable in order to point to the first empty location of the buffer.
1311 *
1312 * In case the function is called with 'checkonly' equal to 1, it does not copy
1313 * the data into the buffer. It only checks for buffer overflows and it updates the
1314 * 'offset' variable. This mode can be useful when the buffer already contains the
1315 * data (maybe because the producer writes directly into the target buffer), so
1316 * only the buffer overflow check has to be made.
1317 * In this case, both 'data' and 'outbuf' can be NULL values.
1318 *
1319 * This function is useful in case the userland application does not know immediately
1320 * all the data it has to write into the socket. This function provides a way to create
1321 * the "stream" step by step, appending the new data to the old one. Then, when all the
1322 * data has been bufferized, the application can call the sock_send() function.
1323 *
1324 * \param data: a void pointer to the data that has to be copied.
1325 *
1326 * \param size: number of bytes that have to be copied.
1327 *
1328 * \param outbuf: user-allocated buffer (of size 'totsize') into which data
1329 * has to be copied.
1330 *
1331 * \param offset: an index into 'outbuf' which keeps the location of its first
1332 * empty location.
1333 *
1334 * \param totsize: total size of the buffer into which data is being copied.
1335 *
1336 * \param checkonly: '1' if we do not want to copy data into the buffer and we
1337 * want just do a buffer overflow control, '0' if data has to be copied as well.
1338 *
1339 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1340 * error message. This buffer has to be at least 'errbuflen' in length.
1341 * It can be NULL; in this case the error cannot be printed.
1342 *
1343 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1344 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1345 *
1346 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
1347 * is returned in the 'errbuf' variable. When the function returns, 'outbuf' will
1348 * have the new string appended, and 'offset' will keep the length of that buffer.
1349 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
1350 *
1351 * \warning This function assumes that the buffer in which data has to be stored is
1352 * large 'totbuf' bytes.
1353 *
1354 * \warning In case of 'checkonly', be carefully to call this function *before* copying
1355 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
1356 */
1357 int sock_bufferize(const void *data, int size, char *outbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
1358 {
1359 if ((*offset + size) > totsize)
1360 {
1361 if (errbuf)
1362 snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
1363 return -1;
1364 }
1365
1366 if (!checkonly)
1367 memcpy(outbuf + (*offset), data, size);
1368
1369 (*offset) += size;
1370
1371 return 0;
1372 }
1373
1374 /*
1375 * \brief It waits on a connected socket and it manages to receive data.
1376 *
1377 * This function basically calls the recv() socket function and it checks that no
1378 * error occurred. If that happens, it writes the error message into 'errbuf'.
1379 *
1380 * This function changes its behavior according to the 'receiveall' flag: if we
1381 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
1382 * data is arrived. Otherwise, it returns the data currently available.
1383 *
1384 * In case the socket does not have enough data available, it cycles on the recv()
1385 * until the requested data (of size 'size') is arrived.
1386 * In this case, it blocks until the number of bytes read is equal to 'size'.
1387 *
1388 * \param sock: the connected socket currently opened.
1389 *
1390 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
1391 *
1392 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
1393 * that we are expecting to be read.
1394 *
1395 * \param flags:
1396 *
1397 * SOCK_RECEIVALL_XXX:
1398 *
1399 * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
1400 * if SOCK_RECEIVALL_YES, wait until 'size' data has been
1401 * received (in case the socket does not have enough data available).
1402 *
1403 * SOCK_EOF_XXX:
1404 *
1405 * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
1406 * and return an error on any subsequent read that returns 0;
1407 * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
1408 *
1409 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1410 * error message. This buffer has to be at least 'errbuflen' in length.
1411 * It can be NULL; in this case the error cannot be printed.
1412 *
1413 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1414 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1415 *
1416 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
1417 * The error message is returned in the 'errbuf' variable.
1418 */
1419
1420 int sock_recv(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer, size_t size,
1421 int flags, char *errbuf, int errbuflen)
1422 {
1423 int recv_flags = 0;
1424 char *bufp = buffer;
1425 int remaining;
1426 ssize_t nread;
1427
1428 if (size == 0)
1429 {
1430 return 0;
1431 }
1432 if (size > INT_MAX)
1433 {
1434 if (errbuf)
1435 {
1436 snprintf(errbuf, errbuflen,
1437 "Can't read more than %u bytes with sock_recv",
1438 INT_MAX);
1439 }
1440 return -1;
1441 }
1442
1443 if (flags & SOCK_MSG_PEEK)
1444 recv_flags |= MSG_PEEK;
1445
1446 bufp = (char *) buffer;
1447 remaining = (int) size;
1448
1449 /*
1450 * We don't use MSG_WAITALL because it's not supported in
1451 * Win32.
1452 */
1453 for (;;) {
1454 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1455 nread = fuzz_recv(bufp, remaining);
1456 #elif defined(HAVE_OPENSSL)
1457 if (ssl)
1458 {
1459 /*
1460 * XXX - what about MSG_PEEK?
1461 */
1462 nread = ssl_recv(ssl, bufp, remaining, errbuf, errbuflen);
1463 if (nread == -2) return -1;
1464 }
1465 else
1466 nread = recv(sock, bufp, remaining, recv_flags);
1467 #else
1468 nread = recv(sock, bufp, remaining, recv_flags);
1469 #endif
1470
1471 if (nread == -1)
1472 {
1473 #ifndef _WIN32
1474 if (errno == EINTR)
1475 return -3;
1476 #endif
1477 sock_geterrmsg(errbuf, errbuflen, "recv() failed");
1478 return -1;
1479 }
1480
1481 if (nread == 0)
1482 {
1483 if ((flags & SOCK_EOF_IS_ERROR) ||
1484 (remaining != (int) size))
1485 {
1486 /*
1487 * Either we've already read some data,
1488 * or we're always supposed to return
1489 * an error on EOF.
1490 */
1491 if (errbuf)
1492 {
1493 snprintf(errbuf, errbuflen,
1494 "The other host terminated the connection.");
1495 }
1496 return -1;
1497 }
1498 else
1499 return 0;
1500 }
1501
1502 /*
1503 * Do we want to read the amount requested, or just return
1504 * what we got?
1505 */
1506 if (!(flags & SOCK_RECEIVEALL_YES))
1507 {
1508 /*
1509 * Just return what we got.
1510 */
1511 return (int) nread;
1512 }
1513
1514 bufp += nread;
1515 remaining -= nread;
1516
1517 if (remaining == 0)
1518 return (int) size;
1519 }
1520 }
1521
1522 /*
1523 * Receives a datagram from a socket.
1524 *
1525 * Returns the size of the datagram on success or -1 on error.
1526 */
1527 int sock_recv_dgram(PCAP_SOCKET sock, SSL *ssl _U_NOSSL_, void *buffer,
1528 size_t size, char *errbuf, int errbuflen)
1529 {
1530 ssize_t nread;
1531 #ifndef _WIN32
1532 struct msghdr message;
1533 struct iovec iov;
1534 #endif
1535
1536 if (size == 0)
1537 {
1538 return 0;
1539 }
1540 if (size > INT_MAX)
1541 {
1542 if (errbuf)
1543 {
1544 snprintf(errbuf, errbuflen,
1545 "Can't read more than %u bytes with sock_recv_dgram",
1546 INT_MAX);
1547 }
1548 return -1;
1549 }
1550
1551 #ifdef HAVE_OPENSSL
1552 // TODO: DTLS
1553 if (ssl)
1554 {
1555 snprintf(errbuf, errbuflen, "DTLS not implemented yet");
1556 return -1;
1557 }
1558 #endif
1559
1560 /*
1561 * This should be a datagram socket, so we should get the
1562 * entire datagram in one recv() or recvmsg() call, and
1563 * don't need to loop.
1564 */
1565 #ifdef _WIN32
1566 nread = recv(sock, buffer, (int)size, 0);
1567 if (nread == SOCKET_ERROR)
1568 {
1569 /*
1570 * To quote the MSDN documentation for recv(),
1571 * "If the datagram or message is larger than
1572 * the buffer specified, the buffer is filled
1573 * with the first part of the datagram, and recv
1574 * generates the error WSAEMSGSIZE. For unreliable
1575 * protocols (for example, UDP) the excess data is
1576 * lost..."
1577 *
1578 * So if the message is bigger than the buffer
1579 * supplied to us, the excess data is discarded,
1580 * and we'll report an error.
1581 */
1582 sock_fmterrmsg(errbuf, errbuflen, sock_geterrcode(),
1583 "recv() failed");
1584 return -1;
1585 }
1586 #else /* _WIN32 */
1587 /*
1588 * The Single UNIX Specification says that a recv() on
1589 * a socket for a message-oriented protocol will discard
1590 * the excess data. It does *not* indicate that the
1591 * receive will fail with, for example, EMSGSIZE.
1592 *
1593 * Therefore, we use recvmsg(), which appears to be
1594 * the only way to get a "message truncated" indication
1595 * when receiving a message for a message-oriented
1596 * protocol.
1597 */
1598 message.msg_name = NULL; /* we don't care who it's from */
1599 message.msg_namelen = 0;
1600 iov.iov_base = buffer;
1601 iov.iov_len = size;
1602 message.msg_iov = &iov;
1603 message.msg_iovlen = 1;
1604 #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
1605 message.msg_control = NULL; /* we don't care about control information */
1606 message.msg_controllen = 0;
1607 #endif
1608 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1609 message.msg_flags = 0;
1610 #endif
1611 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1612 nread = fuzz_recv(buffer, size);
1613 #else
1614 nread = recvmsg(sock, &message, 0);
1615 #endif
1616 if (nread == -1)
1617 {
1618 if (errno == EINTR)
1619 return -3;
1620 sock_geterrmsg(errbuf, errbuflen, "recv() failed");
1621 return -1;
1622 }
1623 #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
1624 /*
1625 * XXX - Solaris supports this, but only if you ask for the
1626 * X/Open version of recvmsg(); should we use that, or will
1627 * that cause other problems?
1628 */
1629 if (message.msg_flags & MSG_TRUNC)
1630 {
1631 /*
1632 * Message was bigger than the specified buffer size.
1633 *
1634 * Report this as an error, as the Microsoft documentation
1635 * implies we'd do in a similar case on Windows.
1636 */
1637 snprintf(errbuf, errbuflen, "recv(): Message too long");
1638 return -1;
1639 }
1640 #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
1641 #endif /* _WIN32 */
1642
1643 /*
1644 * The size we're reading fits in an int, so the return value
1645 * will fit in an int.
1646 */
1647 return (int)nread;
1648 }
1649
1650 /*
1651 * \brief It discards N bytes that are currently waiting to be read on the current socket.
1652 *
1653 * This function is useful in case we receive a message we cannot understand (e.g.
1654 * wrong version number when receiving a network packet), so that we have to discard all
1655 * data before reading a new message.
1656 *
1657 * This function will read 'size' bytes from the socket and discard them.
1658 * It defines an internal buffer in which data will be copied; however, in case
1659 * this buffer is not large enough, it will cycle in order to read everything as well.
1660 *
1661 * \param sock: the connected socket currently opened.
1662 *
1663 * \param size: number of bytes that have to be discarded.
1664 *
1665 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1666 * error message. This buffer has to be at least 'errbuflen' in length.
1667 * It can be NULL; in this case the error cannot be printed.
1668 *
1669 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1670 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1671 *
1672 * \return '0' if everything is fine, '-1' if some errors occurred.
1673 * The error message is returned in the 'errbuf' variable.
1674 */
1675 int sock_discard(PCAP_SOCKET sock, SSL *ssl, int size, char *errbuf,
1676 int errbuflen)
1677 {
1678 #define TEMP_BUF_SIZE 32768
1679
1680 char buffer[TEMP_BUF_SIZE]; /* network buffer, to be used when the message is discarded */
1681
1682 /*
1683 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
1684 * Our feeling is that a buffer if 32KB is enough for most of the application;
1685 * in case this is not enough, the "while" loop discards the message by calling the
1686 * sockrecv() several times.
1687 * We do not want to create a bigger variable because this causes the program to exit on
1688 * some platforms (e.g. BSD)
1689 */
1690 while (size > TEMP_BUF_SIZE)
1691 {
1692 if (sock_recv(sock, ssl, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1693 return -1;
1694
1695 size -= TEMP_BUF_SIZE;
1696 }
1697
1698 /*
1699 * If there is still data to be discarded
1700 * In this case, the data can fit into the temporary buffer
1701 */
1702 if (size)
1703 {
1704 if (sock_recv(sock, ssl, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
1705 return -1;
1706 }
1707
1708 return 0;
1709 }
1710
1711 /*
1712 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
1713 *
1714 * This function is useful after an accept() call in order to check if the connecting
1715 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
1716 * allowed host; this function checks the sockaddr_storage structure of the connecting host
1717 * against this host list, and it returns '0' is the host is included in this list.
1718 *
1719 * \param hostlist: pointer to a string that contains the list of the allowed host.
1720 *
1721 * \param sep: a string that keeps the separators used between the hosts (for example the
1722 * space character) in the host list.
1723 *
1724 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
1725 *
1726 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1727 * error message. This buffer has to be at least 'errbuflen' in length.
1728 * It can be NULL; in this case the error cannot be printed.
1729 *
1730 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1731 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1732 *
1733 * \return It returns:
1734 * - '1' if the host list is empty
1735 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
1736 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
1737 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
1738 */
1739 int sock_check_hostlist(const char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
1740 {
1741 /* checks if the connecting host is among the ones allowed */
1742 if ((hostlist) && (hostlist[0]))
1743 {
1744 char *token; /* temp, needed to separate items into the hostlist */
1745 struct addrinfo *addrinfo, *ai_next;
1746 char *temphostlist;
1747 char *lasts;
1748 int getaddrinfo_failed = 0;
1749
1750 /*
1751 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
1752 * So, we have to create a new temporary string in which the original content is kept
1753 */
1754 temphostlist = strdup(hostlist);
1755 if (temphostlist == NULL)
1756 {
1757 sock_geterrmsg(errbuf, errbuflen,
1758 "sock_check_hostlist(), malloc() failed");
1759 return -2;
1760 }
1761
1762 token = pcapint_strtok_r(temphostlist, sep, &lasts);
1763
1764 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
1765 addrinfo = NULL;
1766
1767 while (token != NULL)
1768 {
1769 struct addrinfo hints;
1770 int retval;
1771
1772 addrinfo = NULL;
1773 memset(&hints, 0, sizeof(struct addrinfo));
1774 hints.ai_family = PF_UNSPEC;
1775 hints.ai_socktype = SOCK_STREAM;
1776
1777 retval = getaddrinfo(token, NULL, &hints, &addrinfo);
1778 if (retval != 0)
1779 {
1780 if (errbuf)
1781 get_gai_errstring(errbuf, errbuflen,
1782 "Allowed host list error: ",
1783 retval, token, NULL);
1784
1785 /*
1786 * Note that at least one call to getaddrinfo()
1787 * failed.
1788 */
1789 getaddrinfo_failed = 1;
1790
1791 /* Get next token */
1792 token = pcapint_strtok_r(NULL, sep, &lasts);
1793 continue;
1794 }
1795
1796 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
1797 ai_next = addrinfo;
1798 while (ai_next)
1799 {
1800 if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1801 {
1802 free(temphostlist);
1803 freeaddrinfo(addrinfo);
1804 return 0;
1805 }
1806
1807 /*
1808 * If we are here, it means that the current address does not matches
1809 * Let's try with the next one in the header chain
1810 */
1811 ai_next = ai_next->ai_next;
1812 }
1813
1814 freeaddrinfo(addrinfo);
1815 addrinfo = NULL;
1816
1817 /* Get next token */
1818 token = pcapint_strtok_r(NULL, sep, &lasts);
1819 }
1820
1821 if (addrinfo)
1822 {
1823 freeaddrinfo(addrinfo);
1824 addrinfo = NULL;
1825 }
1826
1827 free(temphostlist);
1828
1829 if (getaddrinfo_failed) {
1830 /*
1831 * At least one getaddrinfo() call failed;
1832 * treat that as an error, so rpcapd knows
1833 * that it should log it locally as well
1834 * as telling the client about it.
1835 */
1836 return -2;
1837 } else {
1838 /*
1839 * All getaddrinfo() calls succeeded, but
1840 * the host wasn't in the list.
1841 */
1842 if (errbuf)
1843 snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
1844 return -1;
1845 }
1846 }
1847
1848 /* No hostlist, so we have to return 'empty list' */
1849 return 1;
1850 }
1851
1852 /*
1853 * \brief Compares two addresses contained into two sockaddr_storage structures.
1854 *
1855 * This function is useful to compare two addresses, given their internal representation,
1856 * i.e. an sockaddr_storage structure.
1857 *
1858 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
1859 * sockaddr_in6, properly casted in order to be compliant to the function interface.
1860 *
1861 * This function will return '0' if the two addresses matches, '-1' if not.
1862 *
1863 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
1864 * accept() call), containing the first address to compare.
1865 *
1866 * \param second: a sockaddr_storage structure containing the second address to compare.
1867 *
1868 * \return '0' if the addresses are equal, '-1' if they are different.
1869 */
1870 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
1871 {
1872 if (first->ss_family == second->ss_family)
1873 {
1874 if (first->ss_family == AF_INET)
1875 {
1876 if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
1877 &(((struct sockaddr_in *) second)->sin_addr),
1878 sizeof(struct in_addr)) == 0)
1879 return 0;
1880 }
1881 else /* address family is AF_INET6 */
1882 {
1883 if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
1884 &(((struct sockaddr_in6 *) second)->sin6_addr),
1885 sizeof(struct in6_addr)) == 0)
1886 return 0;
1887 }
1888 }
1889
1890 return -1;
1891 }
1892
1893 /*
1894 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1895 *
1896 * It is used to return the address and port the server picked for our socket on the local machine.
1897 * It works only on:
1898 * - connected sockets
1899 * - server sockets
1900 *
1901 * On unconnected client sockets it does not work because the system dynamically chooses a port
1902 * only when the socket calls a send() call.
1903 *
1904 * \param sock: the connected socket currently opened.
1905 *
1906 * \param address: it contains the address that will be returned by the function. This buffer
1907 * must be properly allocated by the user. The address can be either literal or numeric depending
1908 * on the value of 'Flags'.
1909 *
1910 * \param addrlen: the length of the 'address' buffer.
1911 *
1912 * \param port: it contains the port that will be returned by the function. This buffer
1913 * must be properly allocated by the user.
1914 *
1915 * \param portlen: the length of the 'port' buffer.
1916 *
1917 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1918 * that determine if the resulting address must be in numeric / literal form, and so on.
1919 *
1920 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1921 * error message. This buffer has to be at least 'errbuflen' in length.
1922 * It can be NULL; in this case the error cannot be printed.
1923 *
1924 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1925 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1926 *
1927 * \return It returns '-1' if this function succeeds, '0' otherwise.
1928 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1929 * In any case, the returned strings are '0' terminated.
1930 *
1931 * \warning If the socket is using a connectionless protocol, the address may not be available
1932 * until I/O occurs on the socket.
1933 */
1934 int sock_getmyinfo(PCAP_SOCKET sock, char *address, int addrlen, char *port,
1935 int portlen, int flags, char *errbuf, int errbuflen)
1936 {
1937 struct sockaddr_storage mysockaddr;
1938 socklen_t sockaddrlen;
1939
1940
1941 sockaddrlen = sizeof(struct sockaddr_storage);
1942
1943 if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1944 {
1945 sock_geterrmsg(errbuf, errbuflen, "getsockname() failed");
1946 return 0;
1947 }
1948
1949 /* Returns the numeric address of the host that triggered the error */
1950 return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1951 }
1952
1953 /*
1954 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1955 *
1956 * This function is basically an extended version of the inet_ntop(), which does not exist in
1957 * Winsock because the same result can be obtained by using the getnameinfo().
1958 * However, differently from inet_ntop(), this function is able to return also literal names
1959 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1960 *
1961 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1962 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1963 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1964 * a standard IPv6 address like "::1".
1965 *
1966 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1967 * are the ones allowed in the standard getnameinfo() socket function.
1968 *
1969 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1970 * need to be translated from network form into the presentation form. This structure must be
1971 * zero-ed prior using it, and the address family field must be filled with the proper value.
1972 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1973 * calling this function.
1974 *
1975 * \param address: it contains the address that will be returned by the function. This buffer
1976 * must be properly allocated by the user. The address can be either literal or numeric depending
1977 * on the value of 'Flags'.
1978 *
1979 * \param addrlen: the length of the 'address' buffer.
1980 *
1981 * \param port: it contains the port that will be returned by the function. This buffer
1982 * must be properly allocated by the user.
1983 *
1984 * \param portlen: the length of the 'port' buffer.
1985 *
1986 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1987 * that determine if the resulting address must be in numeric / literal form, and so on.
1988 *
1989 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1990 * error message. This buffer has to be at least 'errbuflen' in length.
1991 * It can be NULL; in this case the error cannot be printed.
1992 *
1993 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1994 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1995 *
1996 * \return It returns '-1' if this function succeeds, '0' otherwise.
1997 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1998 * and 'port'.
1999 * In any case, the returned strings are '0' terminated.
2000 */
2001 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, size_t errbuflen)
2002 {
2003 socklen_t sockaddrlen;
2004 int retval; /* Variable that keeps the return value; */
2005
2006 retval = -1;
2007
2008 #ifdef _WIN32
2009 if (sockaddr->ss_family == AF_INET)
2010 sockaddrlen = sizeof(struct sockaddr_in);
2011 else
2012 sockaddrlen = sizeof(struct sockaddr_in6);
2013 #else
2014 sockaddrlen = sizeof(struct sockaddr_storage);
2015 #endif
2016
2017 if ((flags & NI_NUMERICHOST) == 0) /* Check that we want literal names */
2018 {
2019 if ((sockaddr->ss_family == AF_INET6) &&
2020 (memcmp(&((struct sockaddr_in6 *) sockaddr)->sin6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(struct in6_addr)) == 0))
2021 {
2022 if (address)
2023 pcapint_strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
2024 return retval;
2025 }
2026 }
2027
2028 if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
2029 {
2030 /* If the user wants to receive an error message */
2031 if (errbuf)
2032 {
2033 sock_geterrmsg(errbuf, errbuflen,
2034 "getnameinfo() failed");
2035 errbuf[errbuflen - 1] = 0;
2036 }
2037
2038 if (address)
2039 {
2040 pcapint_strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
2041 address[addrlen - 1] = 0;
2042 }
2043
2044 if (port)
2045 {
2046 pcapint_strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
2047 port[portlen - 1] = 0;
2048 }
2049
2050 retval = 0;
2051 }
2052
2053 return retval;
2054 }
2055
2056 /*
2057 * \brief It translates an address from the 'presentation' form into the 'network' form.
2058 *
2059 * This function basically replaces inet_pton(), which does not exist in Winsock because
2060 * the same result can be obtained by using the getaddrinfo().
2061 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
2062 * like in inet_pton() ) and a literal name (e.g. 'localhost').
2063 *
2064 * This function does the reverse job of sock_getascii_addrport().
2065 *
2066 * \param address: a zero-terminated string which contains the name you have to
2067 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
2068 *
2069 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
2070 * 'network' form of the requested address.
2071 *
2072 * \param addr_family: a constant which can assume the following values:
2073 * - 'AF_INET' if we want to ping an IPv4 host
2074 * - 'AF_INET6' if we want to ping an IPv6 host
2075 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
2076 *
2077 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
2078 * error message. This buffer has to be at least 'errbuflen' in length.
2079 * It can be NULL; in this case the error cannot be printed.
2080 *
2081 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
2082 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
2083 *
2084 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
2085 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
2086 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
2087 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
2088 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
2089 *
2090 * \warning The sockaddr_storage structure MUST be allocated by the user.
2091 */
2092 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
2093 {
2094 struct addrinfo *addrinfo;
2095 struct addrinfo hints;
2096
2097 memset(&hints, 0, sizeof(hints));
2098
2099 hints.ai_family = addr_family;
2100
2101 addrinfo = sock_initaddress(address, "22222" /* fake port */, &hints,
2102 errbuf, errbuflen);
2103 if (addrinfo == NULL)
2104 return 0;
2105
2106 if (addrinfo->ai_family == PF_INET)
2107 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
2108 else
2109 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
2110
2111 if (addrinfo->ai_next != NULL)
2112 {
2113 freeaddrinfo(addrinfo);
2114
2115 if (errbuf)
2116 snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
2117 return -2;
2118 }
2119
2120 freeaddrinfo(addrinfo);
2121 return -1;
2122 }