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