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