]> The Tcpdump Group git mirrors - libpcap/blob - sockutils.c
a19f1081e0883718c48c1ee42d88b2e0dc9bf26f
[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 <errno.h> /* for the errno variable */
54 #include <stdio.h> /* for the stderr file */
55 #include <stdlib.h> /* for malloc() and free() */
56 #ifdef HAVE_LIMITS_H
57 #include <limits.h>
58 #else
59 #define INT_MAX 2147483647
60 #endif
61
62 #include "portability.h" /* this includes <string.h> */
63 #include "sockutils.h"
64
65 #ifdef _WIN32
66 /*
67 * Winsock initialization.
68 *
69 * Ask for WinSock 2.2.
70 */
71 #define WINSOCK_MAJOR_VERSION 2
72 #define WINSOCK_MINOR_VERSION 2
73
74 static int sockcount = 0; /*!< Variable that allows calling the WSAStartup() only one time */
75 #endif
76
77 /* Some minor differences between UNIX and Win32 */
78 #ifdef _WIN32
79 #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
80 #endif
81
82 /* Size of the buffer that has to keep error messages */
83 #define SOCK_ERRBUF_SIZE 1024
84
85 /* Constants; used in order to keep strings here */
86 #define SOCKET_NO_NAME_AVAILABLE "No name available"
87 #define SOCKET_NO_PORT_AVAILABLE "No port available"
88 #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
89
90 /****************************************************
91 * *
92 * Locally defined functions *
93 * *
94 ****************************************************/
95
96 static int sock_ismcastaddr(const struct sockaddr *saddr);
97
98 /****************************************************
99 * *
100 * Function bodies *
101 * *
102 ****************************************************/
103
104 /*
105 * \brief It retrieves the error message after an error occurred in the socket interface.
106 *
107 * This function is defined because of the different way errors are returned in UNIX
108 * and Win32. This function provides a consistent way to retrieve the error message
109 * (after a socket error occurred) on all the platforms.
110 *
111 * \param caller: a pointer to a user-allocated string which contains a message that has
112 * to be printed *before* the true error message. It could be, for example, 'this error
113 * comes from the recv() call at line 31'. It may be NULL.
114 *
115 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
116 * error message. This buffer has to be at least 'errbuflen' in length.
117 * It can be NULL; in this case the error cannot be printed.
118 *
119 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
120 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
121 *
122 * \return No return values. The error message is returned in the 'string' parameter.
123 */
124 void sock_geterror(const char *caller, char *errbuf, int errbuflen)
125 {
126 #ifdef _WIN32
127 int retval;
128 int code;
129 TCHAR message[SOCK_ERRBUF_SIZE]; /* It will be char (if we're using ascii) or wchar_t (if we're using unicode) */
130
131 if (errbuf == NULL)
132 return;
133
134 code = GetLastError();
135
136 retval = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
137 FORMAT_MESSAGE_MAX_WIDTH_MASK,
138 NULL, code, 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 return;
148 }
149 else
150 {
151 if ((caller) && (*caller))
152 pcap_snprintf(errbuf, errbuflen, "%s%s (code %d)", caller, message, code);
153 else
154 pcap_snprintf(errbuf, errbuflen, "%s (code %d)", message, code);
155 }
156 #else
157 char *message;
158
159 if (errbuf == NULL)
160 return;
161
162 message = strerror(errno);
163
164 if ((caller) && (*caller))
165 pcap_snprintf(errbuf, errbuflen, "%s%s (code %d)", caller, message, errno);
166 else
167 pcap_snprintf(errbuf, errbuflen, "%s (code %d)", message, errno);
168 #endif
169 }
170
171 /*
172 * \brief It initializes sockets.
173 *
174 * This function is pretty useless on UNIX, since socket initialization is not required.
175 * However it is required on Win32. In UNIX, this function appears to be completely empty.
176 *
177 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
178 * error message. This buffer has to be at least 'errbuflen' in length.
179 * It can be NULL; in this case the error cannot be printed.
180 *
181 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
182 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
183 *
184 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
185 * in the 'errbuf' variable.
186 */
187 int sock_init(char *errbuf, int errbuflen)
188 {
189 #ifdef _WIN32
190 if (sockcount == 0)
191 {
192 WSADATA wsaData; /* helper variable needed to initialize Winsock */
193
194 if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
195 WINSOCK_MINOR_VERSION), &wsaData) != 0)
196 {
197 if (errbuf)
198 pcap_snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
199
200 WSACleanup();
201
202 return -1;
203 }
204 }
205
206 sockcount++;
207 #endif
208
209 return 0;
210 }
211
212 /*
213 * \brief It deallocates sockets.
214 *
215 * This function is pretty useless on UNIX, since socket deallocation is not required.
216 * However it is required on Win32. In UNIX, this function appears to be completely empty.
217 *
218 * \return No error values.
219 */
220 void sock_cleanup(void)
221 {
222 #ifdef _WIN32
223 sockcount--;
224
225 if (sockcount == 0)
226 WSACleanup();
227 #endif
228 }
229
230 /*
231 * \brief It checks if the sockaddr variable contains a multicast address.
232 *
233 * \return '0' if the address is multicast, '-1' if it is not.
234 */
235 static int sock_ismcastaddr(const struct sockaddr *saddr)
236 {
237 if (saddr->sa_family == PF_INET)
238 {
239 struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
240 if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
241 else return -1;
242 }
243 else
244 {
245 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
246 if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
247 else return -1;
248 }
249 }
250
251 /*
252 * \brief It initializes a network connection both from the client and the server side.
253 *
254 * In case of a client socket, this function calls socket() and connect().
255 * In the meanwhile, it checks for any socket error.
256 * If an error occurs, it writes the error message into 'errbuf'.
257 *
258 * In case of a server socket, the function calls socket(), bind() and listen().
259 *
260 * This function is usually preceeded by the sock_initaddress().
261 *
262 * \param addrinfo: pointer to an addrinfo variable which will be used to
263 * open the socket and such. This variable is the one returned by the previous call to
264 * sock_initaddress().
265 *
266 * \param server: '1' if this is a server socket, '0' otherwise.
267 *
268 * \param nconn: number of the connections that are allowed to wait into the listen() call.
269 * This value has no meanings in case of a client socket.
270 *
271 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
272 * error message. This buffer has to be at least 'errbuflen' in length.
273 * It can be NULL; in this case the error cannot be printed.
274 *
275 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
276 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
277 *
278 * \return the socket that has been opened (that has to be used in the following sockets calls)
279 * if everything is fine, '0' if some errors occurred. The error message is returned
280 * in the 'errbuf' variable.
281 */
282 SOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
283 {
284 SOCKET sock;
285
286 sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
287 if (sock == -1)
288 {
289 sock_geterror("socket(): ", errbuf, errbuflen);
290 return -1;
291 }
292
293
294 /* This is a server socket */
295 if (server)
296 {
297 #ifdef BSD
298 /*
299 * Force the use of IPv6-only addresses; in BSD you can accept both v4 and v6
300 * connections if you have a "NULL" pointer as the nodename in the getaddrinfo()
301 * This behavior is not clear in the RFC 2553, so each system implements the
302 * bind() differently from this point of view
303 */
304 if (addrinfo->ai_family == PF_INET6)
305 {
306 int on;
307
308 if (setsockopt(sock, IPPROTO_IPV6, IPV6_BINDV6ONLY, (char *)&on, sizeof (int)) == -1)
309 {
310 if (errbuf)
311 pcap_snprintf(errbuf, errbuflen, "setsockopt(IPV6_BINDV6ONLY)");
312 return -1;
313 }
314 }
315 #endif
316
317 /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
318 if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
319 {
320 sock_geterror("bind(): ", errbuf, errbuflen);
321 return -1;
322 }
323
324 if (addrinfo->ai_socktype == SOCK_STREAM)
325 if (listen(sock, nconn) == -1)
326 {
327 sock_geterror("listen(): ", errbuf, errbuflen);
328 return -1;
329 }
330
331 /* server side ended */
332 return sock;
333 }
334 else /* we're the client */
335 {
336 struct addrinfo *tempaddrinfo;
337 char *errbufptr;
338 size_t bufspaceleft;
339
340 tempaddrinfo = addrinfo;
341 errbufptr = errbuf;
342 bufspaceleft = errbuflen;
343 *errbufptr = 0;
344
345 /*
346 * We have to loop though all the addinfo returned.
347 * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
348 * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
349 */
350 while (tempaddrinfo)
351 {
352
353 if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
354 {
355 size_t msglen;
356 char TmpBuffer[100];
357 char SocketErrorMessage[SOCK_ERRBUF_SIZE];
358
359 /*
360 * We have to retrieve the error message before any other socket call completes, otherwise
361 * the error message is lost
362 */
363 sock_geterror(NULL, SocketErrorMessage, sizeof(SocketErrorMessage));
364
365 /* Returns the numeric address of the host that triggered the error */
366 sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
367
368 pcap_snprintf(errbufptr, bufspaceleft,
369 "Is the server properly installed on %s? connect() failed: %s", TmpBuffer, SocketErrorMessage);
370
371 /* In case more then one 'connect' fails, we manage to keep all the error messages */
372 msglen = strlen(errbufptr);
373
374 errbufptr[msglen] = ' ';
375 errbufptr[msglen + 1] = 0;
376
377 bufspaceleft = bufspaceleft - (msglen + 1);
378 errbufptr += (msglen + 1);
379
380 tempaddrinfo = tempaddrinfo->ai_next;
381 }
382 else
383 break;
384 }
385
386 /*
387 * Check how we exit from the previous loop
388 * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
389 */
390 if (tempaddrinfo == NULL)
391 {
392 closesocket(sock);
393 return -1;
394 }
395 else
396 return sock;
397 }
398 }
399
400 /*
401 * \brief Closes the present (TCP and UDP) socket connection.
402 *
403 * This function sends a shutdown() on the socket in order to disable send() calls
404 * (while recv() ones are still allowed). Then, it closes the socket.
405 *
406 * \param sock: the socket identifier of the connection that has to be closed.
407 *
408 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
409 * error message. This buffer has to be at least 'errbuflen' in length.
410 * It can be NULL; in this case the error cannot be printed.
411 *
412 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
413 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
414 *
415 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
416 * in the 'errbuf' variable.
417 */
418 int sock_close(SOCKET sock, char *errbuf, int errbuflen)
419 {
420 /*
421 * SHUT_WR: subsequent calls to the send function are disallowed.
422 * For TCP sockets, a FIN will be sent after all data is sent and
423 * acknowledged by the Server.
424 */
425 if (shutdown(sock, SHUT_WR))
426 {
427 sock_geterror("shutdown(): ", errbuf, errbuflen);
428 /* close the socket anyway */
429 closesocket(sock);
430 return -1;
431 }
432
433 closesocket(sock);
434 return 0;
435 }
436
437 /*
438 * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
439 *
440 * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
441 * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
442 * If an error occurs, it writes the error message into 'errbuf'.
443 *
444 * \param host: a pointer to a string identifying the host. It can be
445 * a host name, a numeric literal address, or NULL or "" (useful
446 * in case of a server socket which has to bind to all addresses).
447 *
448 * \param port: a pointer to a user-allocated buffer containing the network port to use.
449 *
450 * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
451 * addrinfo structure appropriately.
452 *
453 * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
454 * (passed by reference), which will be allocated by this function and returned back to the caller.
455 * This variable will be used in the next sockets calls.
456 *
457 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
458 * error message. This buffer has to be at least 'errbuflen' in length.
459 * It can be NULL; in this case the error cannot be printed.
460 *
461 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
462 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
463 *
464 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
465 * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
466 * returned into the addrinfo parameter.
467 *
468 * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
469 * it is no longer needed.
470 *
471 * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
472 * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
473 * the programmer to look at that function in order to set the 'hints' variable appropriately.
474 */
475 int sock_initaddress(const char *host, const char *port,
476 struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
477 {
478 int retval;
479
480 retval = getaddrinfo(host, port, hints, addrinfo);
481 if (retval != 0)
482 {
483 /*
484 * if the getaddrinfo() fails, you have to use gai_strerror(), instead of using the standard
485 * error routines (errno) in UNIX; Winsock suggests using the GetLastError() instead.
486 */
487 if (errbuf)
488 {
489 #ifdef _WIN32
490 sock_geterror("getaddrinfo(): ", errbuf, errbuflen);
491 #else
492 pcap_snprintf(errbuf, errbuflen, "getaddrinfo() %s", gai_strerror(retval));
493 #endif
494 }
495 return -1;
496 }
497 /*
498 * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
499 * addrinfo has more han one pointers
500 */
501
502 /*
503 * This software only supports PF_INET and PF_INET6.
504 *
505 * XXX - should we just check that at least *one* address is
506 * either PF_INET or PF_INET6, and, when using the list,
507 * ignore all addresses that are neither? (What, no IPX
508 * support? :-))
509 */
510 if (((*addrinfo)->ai_family != PF_INET) &&
511 ((*addrinfo)->ai_family != PF_INET6))
512 {
513 if (errbuf)
514 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
515 return -1;
516 }
517
518 /*
519 * You can't do multicast (or broadcast) TCP.
520 */
521 if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
522 (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
523 {
524 if (errbuf)
525 pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
526 return -1;
527 }
528
529 return 0;
530 }
531
532 /*
533 * \brief It sends the amount of data contained into 'buffer' on the given socket.
534 *
535 * This function basically calls the send() socket function and it checks that all
536 * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
537 * it writes the error message into 'errbuf'.
538 * In case the socket buffer does not have enough space, it loops until all data
539 * has been sent.
540 *
541 * \param socket: the connected socket currently opened.
542 *
543 * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
544 *
545 * \param size: number of bytes that have to be sent.
546 *
547 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
548 * error message. This buffer has to be at least 'errbuflen' in length.
549 * It can be NULL; in this case the error cannot be printed.
550 *
551 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
552 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
553 *
554 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
555 * in the 'errbuf' variable.
556 */
557 int sock_send(SOCKET socket, const char *buffer, int size, char *errbuf, int errbuflen)
558 {
559 int nsent;
560
561 send:
562 #ifdef linux
563 /*
564 * Another pain... in Linux there's this flag
565 * MSG_NOSIGNAL
566 * Requests not to send SIGPIPE on errors on stream-oriented
567 * sockets when the other end breaks the connection.
568 * The EPIPE error is still returned.
569 */
570 nsent = send(socket, buffer, size, MSG_NOSIGNAL);
571 #else
572 nsent = send(socket, buffer, size, 0);
573 #endif
574
575 if (nsent == -1)
576 {
577 sock_geterror("send(): ", errbuf, errbuflen);
578 return -1;
579 }
580
581 if (nsent != size)
582 {
583 size -= nsent;
584 buffer += nsent;
585 goto send;
586 }
587
588 return 0;
589 }
590
591 /*
592 * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
593 * and it checks for buffer overflows.
594 *
595 * This function basically copies 'size' bytes of data contained into 'buffer'
596 * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
597 * resulting buffer will not be larger than 'totsize'. Finally, it updates
598 * the 'offset' variable in order to point to the first empty location of the buffer.
599 *
600 * In case the function is called with 'checkonly' equal to 1, it does not copy
601 * the data into the buffer. It only checks for buffer overflows and it updates the
602 * 'offset' variable. This mode can be useful when the buffer already contains the
603 * data (maybe because the producer writes directly into the target buffer), so
604 * only the buffer overflow check has to be made.
605 * In this case, both 'buffer' and 'tempbuf' can be NULL values.
606 *
607 * This function is useful in case the userland application does not know immediately
608 * all the data it has to write into the socket. This function provides a way to create
609 * the "stream" step by step, appending the new data to the old one. Then, when all the
610 * data has been bufferized, the application can call the sock_send() function.
611 *
612 * \param buffer: a char pointer to a user-allocated buffer that keeps the data
613 * that has to be copied.
614 *
615 * \param size: number of bytes that have to be copied.
616 *
617 * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
618 * has to be copied.
619 *
620 * \param offset: an index into 'tempbuf' which keeps the location of its first
621 * empty location.
622 *
623 * \param totsize: total size of the buffer in which data is being copied.
624 *
625 * \param checkonly: '1' if we do not want to copy data into the buffer and we
626 * want just do a buffer ovreflow control, '0' if data has to be copied as well.
627 *
628 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
629 * error message. This buffer has to be at least 'errbuflen' in length.
630 * It can be NULL; in this case the error cannot be printed.
631 *
632 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
633 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
634 *
635 * \return '0' if everything is fine, '-1' if some errors occurred. The error message
636 * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
637 * have the new string appended, and 'offset' will keep the length of that buffer.
638 * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
639 *
640 * \warning This function assumes that the buffer in which data has to be stored is
641 * large 'totbuf' bytes.
642 *
643 * \warning In case of 'checkonly', be carefully to call this function *before* copying
644 * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
645 */
646 int sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
647 {
648 if ((*offset + size) > totsize)
649 {
650 if (errbuf)
651 pcap_snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
652 return -1;
653 }
654
655 if (!checkonly)
656 memcpy(tempbuf + (*offset), buffer, size);
657
658 (*offset) += size;
659
660 return 0;
661 }
662
663 /*
664 * \brief It waits on a connected socket and it manages to receive data.
665 *
666 * This function basically calls the recv() socket function and it checks that no
667 * error occurred. If that happens, it writes the error message into 'errbuf'.
668 *
669 * This function changes its behavior according to the 'receiveall' flag: if we
670 * want to receive exactly 'size' byte, it loops on the recv() until all the requested
671 * data is arrived. Otherwise, it returns the data currently available.
672 *
673 * In case the socket does not have enough data available, it cycles on the recv()
674 * until the requested data (of size 'size') is arrived.
675 * In this case, it blocks until the number of bytes read is equal to 'size'.
676 *
677 * \param sock: the connected socket currently opened.
678 *
679 * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
680 *
681 * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
682 * that we are expecting to be read.
683 *
684 * \param receiveall: if '0' (or SOCK_RECEIVEALL_NO), it returns as soon as some data
685 * is ready; otherwise, (or SOCK_RECEIVEALL_YES) it waits until 'size' data has been
686 * received (in case the socket does not have enough data available).
687 *
688 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
689 * error message. This buffer has to be at least 'errbuflen' in length.
690 * It can be NULL; in this case the error cannot be printed.
691 *
692 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
693 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
694 *
695 * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
696 * The error message is returned in the 'errbuf' variable.
697 */
698
699 /*
700 * On UN*X, recv() returns ssize_t.
701 * On Windows, there *is* no ssize_t, and it returns an int.
702 * Define ssize_t as int on Windows so we can use it as the return value
703 * from recv().
704 */
705 #ifdef _WIN32
706 typedef int ssize_t;
707 #endif
708
709 int sock_recv(SOCKET sock, void *buffer, size_t size, int receiveall,
710 char *errbuf, int errbuflen)
711 {
712 char *bufp = buffer;
713 int remaining;
714 ssize_t nread;
715
716 if (size == 0)
717 {
718 SOCK_ASSERT("I have been requested to read zero bytes", 1);
719 return 0;
720 }
721 if (size > INT_MAX)
722 {
723 pcap_snprintf(errbuf, errbuflen, "Can't read more than %u bytes with sock_recv",
724 INT_MAX);
725 return -1;
726 }
727
728 bufp = (char *) buffer;
729 remaining = (int) size;
730
731 /*
732 * We don't use MSG_WAITALL because it's not supported in
733 * Win32.
734 */
735 for (;;) {
736 nread = recv(sock, bufp, remaining, 0);
737
738 if (nread == -1)
739 {
740 #ifndef _WIN32
741 if (errno == EINTR)
742 return -3;
743 #endif
744 sock_geterror("recv(): ", errbuf, errbuflen);
745 return -1;
746 }
747
748 if (nread == 0)
749 {
750 if (errbuf)
751 {
752 pcap_snprintf(errbuf, errbuflen,
753 "The other host terminated the connection.");
754 }
755 return -1;
756 }
757
758 /*
759 * Do we want to read the amount requested, or just return
760 * what we got?
761 */
762 if (!receiveall)
763 {
764 /*
765 * Just return what we got.
766 */
767 return (int) nread;
768 }
769
770 bufp += nread;
771 remaining -= nread;
772
773 if (remaining == 0)
774 return (int) size;
775 }
776 }
777
778 /*
779 * \brief It discards N bytes that are currently waiting to be read on the current socket.
780 *
781 * This function is useful in case we receive a message we cannot understand (e.g.
782 * wrong version number when receiving a network packet), so that we have to discard all
783 * data before reading a new message.
784 *
785 * This function will read 'size' bytes from the socket and discard them.
786 * It defines an internal buffer in which data will be copied; however, in case
787 * this buffer is not large enough, it will cycle in order to read everything as well.
788 *
789 * \param sock: the connected socket currently opened.
790 *
791 * \param size: number of bytes that have to be discarded.
792 *
793 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
794 * error message. This buffer has to be at least 'errbuflen' in length.
795 * It can be NULL; in this case the error cannot be printed.
796 *
797 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
798 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
799 *
800 * \return '0' if everything is fine, '-1' if some errors occurred.
801 * The error message is returned in the 'errbuf' variable.
802 */
803 int sock_discard(SOCKET sock, int size, char *errbuf, int errbuflen)
804 {
805 #define TEMP_BUF_SIZE 32768
806
807 char buffer[TEMP_BUF_SIZE]; /* network buffer, to be used when the message is discarded */
808
809 /*
810 * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
811 * Our feeling is that a buffer if 32KB is enough for most of the application;
812 * in case this is not enough, the "while" loop discards the message by calling the
813 * sockrecv() several times.
814 * We do not want to create a bigger variable because this causes the program to exit on
815 * some platforms (e.g. BSD)
816 */
817 while (size > TEMP_BUF_SIZE)
818 {
819 if (sock_recv(sock, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
820 return -1;
821
822 size -= TEMP_BUF_SIZE;
823 }
824
825 /*
826 * If there is still data to be discarded
827 * In this case, the data can fit into the temporary buffer
828 */
829 if (size)
830 {
831 if (sock_recv(sock, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
832 return -1;
833 }
834
835 SOCK_ASSERT("I'm currently discarding data\n", 1);
836
837 return 0;
838 }
839
840 /*
841 * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
842 *
843 * This function is useful after an accept() call in order to check if the connecting
844 * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
845 * allowed host; this function checks the sockaddr_storage structure of the connecting host
846 * against this host list, and it returns '0' is the host is included in this list.
847 *
848 * \param hostlist: pointer to a string that contains the list of the allowed host.
849 *
850 * \param sep: a string that keeps the separators used between the hosts (for example the
851 * space character) in the host list.
852 *
853 * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
854 *
855 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
856 * error message. This buffer has to be at least 'errbuflen' in length.
857 * It can be NULL; in this case the error cannot be printed.
858 *
859 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
860 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
861 *
862 * \return It returns:
863 * - '1' if the host list is empty
864 * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
865 * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
866 * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
867 */
868 int sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
869 {
870 /* checks if the connecting host is among the ones allowed */
871 if ((hostlist) && (hostlist[0]))
872 {
873 char *token; /* temp, needed to separate items into the hostlist */
874 struct addrinfo *addrinfo, *ai_next;
875 char *temphostlist;
876 char *lasts;
877
878 /*
879 * The problem is that strtok modifies the original variable by putting '0' at the end of each token
880 * So, we have to create a new temporary string in which the original content is kept
881 */
882 temphostlist = strdup(hostlist);
883 if (temphostlist == NULL)
884 {
885 sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
886 return -2;
887 }
888
889 token = pcap_strtok_r(temphostlist, sep, &lasts);
890
891 /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
892 addrinfo = NULL;
893
894 while (token != NULL)
895 {
896 struct addrinfo hints;
897 int retval;
898
899 addrinfo = NULL;
900 memset(&hints, 0, sizeof(struct addrinfo));
901 hints.ai_family = PF_UNSPEC;
902 hints.ai_socktype = SOCK_STREAM;
903
904 retval = getaddrinfo(token, "0", &hints, &addrinfo);
905 if (retval != 0)
906 {
907 if (errbuf)
908 pcap_snprintf(errbuf, errbuflen, "getaddrinfo() %s", gai_strerror(retval));
909
910 SOCK_ASSERT(errbuf, 1);
911
912 /* Get next token */
913 token = pcap_strtok_r(NULL, sep, &lasts);
914 continue;
915 }
916
917 /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
918 ai_next = addrinfo;
919 while (ai_next)
920 {
921 if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
922 {
923 free(temphostlist);
924 return 0;
925 }
926
927 /*
928 * If we are here, it means that the current address does not matches
929 * Let's try with the next one in the header chain
930 */
931 ai_next = ai_next->ai_next;
932 }
933
934 freeaddrinfo(addrinfo);
935 addrinfo = NULL;
936
937 /* Get next token */
938 token = pcap_strtok_r(NULL, sep, &lasts);
939 }
940
941 if (addrinfo)
942 {
943 freeaddrinfo(addrinfo);
944 addrinfo = NULL;
945 }
946
947 if (errbuf)
948 pcap_snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
949
950 free(temphostlist);
951 return -1;
952 }
953
954 /* No hostlist, so we have to return 'empty list' */
955 return 1;
956 }
957
958 /*
959 * \brief Compares two addresses contained into two sockaddr_storage structures.
960 *
961 * This function is useful to compare two addresses, given their internal representation,
962 * i.e. an sockaddr_storage structure.
963 *
964 * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
965 * sockaddr_in6, properly acsted in order to be compliant to the function interface.
966 *
967 * This function will return '0' if the two addresses matches, '-1' if not.
968 *
969 * \param first: a sockaddr_storage structure, (for example the one that is returned by an
970 * accept() call), containing the first address to compare.
971 *
972 * \param second: a sockaddr_storage structure containing the second address to compare.
973 *
974 * \return '0' if the addresses are equal, '-1' if they are different.
975 */
976 int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
977 {
978 if (first->ss_family == second->ss_family)
979 {
980 if (first->ss_family == AF_INET)
981 {
982 if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
983 &(((struct sockaddr_in *) second)->sin_addr),
984 sizeof(struct in_addr)) == 0)
985 return 0;
986 }
987 else /* address family is AF_INET6 */
988 {
989 if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
990 &(((struct sockaddr_in6 *) second)->sin6_addr),
991 sizeof(struct in6_addr)) == 0)
992 return 0;
993 }
994 }
995
996 return -1;
997 }
998
999 /*
1000 * \brief It gets the address/port the system picked for this socket (on connected sockets).
1001 *
1002 * It is used to return the address and port the server picked for our socket on the local machine.
1003 * It works only on:
1004 * - connected sockets
1005 * - server sockets
1006 *
1007 * On unconnected client sockets it does not work because the system dynamically chooses a port
1008 * only when the socket calls a send() call.
1009 *
1010 * \param sock: the connected socket currently opened.
1011 *
1012 * \param address: it contains the address that will be returned by the function. This buffer
1013 * must be properly allocated by the user. The address can be either literal or numeric depending
1014 * on the value of 'Flags'.
1015 *
1016 * \param addrlen: the length of the 'address' buffer.
1017 *
1018 * \param port: it contains the port that will be returned by the function. This buffer
1019 * must be properly allocated by the user.
1020 *
1021 * \param portlen: the length of the 'port' buffer.
1022 *
1023 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1024 * that determine if the resulting address must be in numeric / literal form, and so on.
1025 *
1026 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1027 * error message. This buffer has to be at least 'errbuflen' in length.
1028 * It can be NULL; in this case the error cannot be printed.
1029 *
1030 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1031 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1032 *
1033 * \return It returns '-1' if this function succeeds, '0' otherwise.
1034 * The address and port corresponding are returned back in the buffers 'address' and 'port'.
1035 * In any case, the returned strings are '0' terminated.
1036 *
1037 * \warning If the socket is using a connectionless protocol, the address may not be available
1038 * until I/O occurs on the socket.
1039 */
1040 int sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1041 {
1042 struct sockaddr_storage mysockaddr;
1043 socklen_t sockaddrlen;
1044
1045
1046 sockaddrlen = sizeof(struct sockaddr_storage);
1047
1048 if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
1049 {
1050 sock_geterror("getsockname(): ", errbuf, errbuflen);
1051 return 0;
1052 }
1053
1054 /* Returns the numeric address of the host that triggered the error */
1055 return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
1056 }
1057
1058 /*
1059 * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
1060 *
1061 * This function is basically an extended version of the inet_ntop(), which does not exist in
1062 * Winsock because the same result can be obtained by using the getnameinfo().
1063 * However, differently from inet_ntop(), this function is able to return also literal names
1064 * (e.g. 'localhost') dependently from the 'Flags' parameter.
1065 *
1066 * The function accepts a sockaddr_storage variable (which can be returned by several functions
1067 * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
1068 * form. So, for instance, it is able to translate an hex address (stored in binary form) into
1069 * a standard IPv6 address like "::1".
1070 *
1071 * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
1072 * are the ones allowed in the standard getnameinfo() socket function.
1073 *
1074 * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
1075 * need to be translated from network form into the presentation form. This structure must be
1076 * zero-ed prior using it, and the address family field must be filled with the proper value.
1077 * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
1078 * calling this function.
1079 *
1080 * \param address: it contains the address that will be returned by the function. This buffer
1081 * must be properly allocated by the user. The address can be either literal or numeric depending
1082 * on the value of 'Flags'.
1083 *
1084 * \param addrlen: the length of the 'address' buffer.
1085 *
1086 * \param port: it contains the port that will be returned by the function. This buffer
1087 * must be properly allocated by the user.
1088 *
1089 * \param portlen: the length of the 'port' buffer.
1090 *
1091 * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
1092 * that determine if the resulting address must be in numeric / literal form, and so on.
1093 *
1094 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1095 * error message. This buffer has to be at least 'errbuflen' in length.
1096 * It can be NULL; in this case the error cannot be printed.
1097 *
1098 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1099 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1100 *
1101 * \return It returns '-1' if this function succeeds, '0' otherwise.
1102 * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
1103 * and 'port'.
1104 * In any case, the returned strings are '0' terminated.
1105 */
1106 int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
1107 {
1108 socklen_t sockaddrlen;
1109 int retval; /* Variable that keeps the return value; */
1110
1111 retval = -1;
1112
1113 #ifdef _WIN32
1114 if (sockaddr->ss_family == AF_INET)
1115 sockaddrlen = sizeof(struct sockaddr_in);
1116 else
1117 sockaddrlen = sizeof(struct sockaddr_in6);
1118 #else
1119 sockaddrlen = sizeof(struct sockaddr_storage);
1120 #endif
1121
1122 if ((flags & NI_NUMERICHOST) == 0) /* Check that we want literal names */
1123 {
1124 if ((sockaddr->ss_family == AF_INET6) &&
1125 (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))
1126 {
1127 if (address)
1128 strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
1129 return retval;
1130 }
1131 }
1132
1133 if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
1134 {
1135 /* If the user wants to receive an error message */
1136 if (errbuf)
1137 {
1138 sock_geterror("getnameinfo(): ", errbuf, errbuflen);
1139 errbuf[errbuflen - 1] = 0;
1140 }
1141
1142 if (address)
1143 {
1144 strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
1145 address[addrlen - 1] = 0;
1146 }
1147
1148 if (port)
1149 {
1150 strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
1151 port[portlen - 1] = 0;
1152 }
1153
1154 retval = 0;
1155 }
1156
1157 return retval;
1158 }
1159
1160 /*
1161 * \brief It translates an address from the 'presentation' form into the 'network' form.
1162 *
1163 * This function basically replaces inet_pton(), which does not exist in Winsock because
1164 * the same result can be obtained by using the getaddrinfo().
1165 * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
1166 * like in inet_pton() ) and a literal name (e.g. 'localhost').
1167 *
1168 * This function does the reverse job of sock_getascii_addrport().
1169 *
1170 * \param address: a zero-terminated string which contains the name you have to
1171 * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
1172 *
1173 * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
1174 * 'network' form of the requested address.
1175 *
1176 * \param addr_family: a constant which can assume the following values:
1177 * - 'AF_INET' if we want to ping an IPv4 host
1178 * - 'AF_INET6' if we want to ping an IPv6 host
1179 * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
1180 *
1181 * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
1182 * error message. This buffer has to be at least 'errbuflen' in length.
1183 * It can be NULL; in this case the error cannot be printed.
1184 *
1185 * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
1186 * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
1187 *
1188 * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
1189 * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
1190 * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
1191 * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
1192 * the content of the SockAddr parameter will be the address corresponding to the first mapping.
1193 *
1194 * \warning The sockaddr_storage structure MUST be allocated by the user.
1195 */
1196 int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
1197 {
1198 int retval;
1199 struct addrinfo *addrinfo;
1200 struct addrinfo hints;
1201
1202 memset(&hints, 0, sizeof(hints));
1203
1204 hints.ai_family = addr_family;
1205
1206 if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
1207 return 0;
1208
1209 if (addrinfo->ai_family == PF_INET)
1210 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
1211 else
1212 memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
1213
1214 if (addrinfo->ai_next != NULL)
1215 {
1216 freeaddrinfo(addrinfo);
1217
1218 if (errbuf)
1219 pcap_snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
1220 return -2;
1221 }
1222
1223 freeaddrinfo(addrinfo);
1224 return -1;
1225 }