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