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