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