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