sockets.c revision 4e024bb4f5c8aa8b07459f7fbd65c35122127fd1
1/* Copyright (C) 2007-2008 The Android Open Source Project 2** 3** This software is licensed under the terms of the GNU General Public 4** License version 2, as published by the Free Software Foundation, and 5** may be copied, distributed, and modified under those terms. 6** 7** This program is distributed in the hope that it will be useful, 8** but WITHOUT ANY WARRANTY; without even the implied warranty of 9** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10** GNU General Public License for more details. 11*/ 12#ifdef __linux__ /* Recent versions of glibc only define EAI_NODATA, which is an 13 extension to the POSIX standard, if _GNU_SOURCE is defined. */ 14# define _GNU_SOURCE 1 15#endif 16 17#include "sockets.h" 18#include "qemu-common.h" 19#include <fcntl.h> 20#include <stddef.h> 21#include "qemu_debug.h" 22#include "qemu-char.h" 23#include <stdlib.h> 24#include <string.h> 25#include "android/utils/path.h" 26#include "android/utils/debug.h" 27#include "android/utils/misc.h" 28 29#define D(...) VERBOSE_PRINT(socket,__VA_ARGS__) 30 31#ifdef _WIN32 32# define xxWIN32_LEAN_AND_MEAN 33# include <windows.h> 34# include <winsock2.h> 35# include <ws2tcpip.h> 36#else /* !_WIN32 */ 37# include <sys/ioctl.h> 38# include <sys/socket.h> 39# include <netinet/in.h> 40# include <netinet/tcp.h> 41# include <netdb.h> 42# if HAVE_UNIX_SOCKETS 43# include <sys/un.h> 44# ifndef UNIX_PATH_MAX 45# define UNIX_PATH_MAX (sizeof(((struct sockaddr_un*)0)->sun_path)-1) 46# endif 47# endif 48#endif /* !_WIN32 */ 49 50 51 52/* QSOCKET_CALL is used to deal with the fact that EINTR happens pretty 53 * easily in QEMU since we use SIGALRM to implement periodic timers 54 */ 55#ifdef _WIN32 56# define QSOCKET_CALL(_ret,_cmd) \ 57 do { _ret = (_cmd); } while ( _ret < 0 && WSAGetLastError() == WSAEINTR ) 58#else 59# define QSOCKET_CALL(_ret,_cmd) \ 60 do { \ 61 errno = 0; \ 62 do { _ret = (_cmd); } while ( _ret < 0 && errno == EINTR ); \ 63 } while (0); 64#endif 65 66#ifdef _WIN32 67 68#include <errno.h> 69 70static int winsock_error; 71 72#define WINSOCK_ERRORS_LIST \ 73 EE(WSA_INVALID_HANDLE,EINVAL,"invalid handle") \ 74 EE(WSA_NOT_ENOUGH_MEMORY,ENOMEM,"not enough memory") \ 75 EE(WSA_INVALID_PARAMETER,EINVAL,"invalid parameter") \ 76 EE(WSAEINTR,EINTR,"interrupted function call") \ 77 EE(WSAEALREADY,EALREADY,"operation already in progress") \ 78 EE(WSAEBADF,EBADF,"bad file descriptor") \ 79 EE(WSAEACCES,EACCES,"permission denied") \ 80 EE(WSAEFAULT,EFAULT,"bad address") \ 81 EE(WSAEINVAL,EINVAL,"invalid argument") \ 82 EE(WSAEMFILE,EMFILE,"too many opened files") \ 83 EE(WSAEWOULDBLOCK,EWOULDBLOCK,"resource temporarily unavailable") \ 84 EE(WSAEINPROGRESS,EINPROGRESS,"operation now in progress") \ 85 EE(WSAEALREADY,EAGAIN,"operation already in progress") \ 86 EE(WSAENOTSOCK,EBADF,"socket operation not on socket") \ 87 EE(WSAEDESTADDRREQ,EDESTADDRREQ,"destination address required") \ 88 EE(WSAEMSGSIZE,EMSGSIZE,"message too long") \ 89 EE(WSAEPROTOTYPE,EPROTOTYPE,"wrong protocol type for socket") \ 90 EE(WSAENOPROTOOPT,ENOPROTOOPT,"bad protocol option") \ 91 EE(WSAEADDRINUSE,EADDRINUSE,"address already in use") \ 92 EE(WSAEADDRNOTAVAIL,EADDRNOTAVAIL,"cannot assign requested address") \ 93 EE(WSAENETDOWN,ENETDOWN,"network is down") \ 94 EE(WSAENETUNREACH,ENETUNREACH,"network unreachable") \ 95 EE(WSAENETRESET,ENETRESET,"network dropped connection on reset") \ 96 EE(WSAECONNABORTED,ECONNABORTED,"software caused connection abort") \ 97 EE(WSAECONNRESET,ECONNRESET,"connection reset by peer") \ 98 EE(WSAENOBUFS,ENOBUFS,"no buffer space available") \ 99 EE(WSAEISCONN,EISCONN,"socket is already connected") \ 100 EE(WSAENOTCONN,ENOTCONN,"socket is not connected") \ 101 EE(WSAESHUTDOWN,ESHUTDOWN,"cannot send after socket shutdown") \ 102 EE(WSAETOOMANYREFS,ETOOMANYREFS,"too many references") \ 103 EE(WSAETIMEDOUT,ETIMEDOUT,"connection timed out") \ 104 EE(WSAECONNREFUSED,ECONNREFUSED,"connection refused") \ 105 EE(WSAELOOP,ELOOP,"cannot translate name") \ 106 EE(WSAENAMETOOLONG,ENAMETOOLONG,"name too long") \ 107 EE(WSAEHOSTDOWN,EHOSTDOWN,"host is down") \ 108 EE(WSAEHOSTUNREACH,EHOSTUNREACH,"no route to host") \ 109 110typedef struct { 111 int winsock; 112 int unix; 113 const char* string; 114} WinsockError; 115 116static const WinsockError _winsock_errors[] = { 117#define EE(w,u,s) { w, u, s }, 118 WINSOCK_ERRORS_LIST 119#undef EE 120 { -1, -1, NULL } 121}; 122 123/* this function reads the latest winsock error code and updates 124 * errno to a matching value. It also returns the new value of 125 * errno. 126 */ 127static int 128_fix_errno( void ) 129{ 130 const WinsockError* werr = _winsock_errors; 131 int unix = EINVAL; /* generic error code */ 132 133 winsock_error = WSAGetLastError(); 134 135 for ( ; werr->string != NULL; werr++ ) { 136 if (werr->winsock == winsock_error) { 137 unix = werr->unix; 138 break; 139 } 140 } 141 errno = unix; 142 return -1; 143} 144 145static int 146_set_errno( int code ) 147{ 148 winsock_error = -1; 149 errno = code; 150 return -1; 151} 152 153/* this function returns a string describing the latest Winsock error */ 154const char* 155_errno_str(void) 156{ 157 const WinsockError* werr = _winsock_errors; 158 const char* result = NULL; 159 160 for ( ; werr->string; werr++ ) { 161 if (werr->winsock == winsock_error) { 162 result = werr->string; 163 break; 164 } 165 } 166 167 if (result == NULL) { 168 result = tempstr_format( 169 "Unkown socket error (Winsock=0x%08x) errno=%d: %s", 170 winsock_error, errno, strerror(errno)); 171 } 172 return result; 173} 174#else 175static int 176_fix_errno( void ) 177{ 178 return -1; 179} 180 181static int 182_set_errno( int code ) 183{ 184 errno = code; 185 return -1; 186} 187#endif 188 189/* socket types */ 190 191static int 192socket_family_to_bsd( SocketFamily family ) 193{ 194 switch (family) { 195 case SOCKET_INET: return AF_INET; 196 case SOCKET_IN6: return AF_INET6; 197#if HAVE_UNIX_SOCKETS 198 case SOCKET_UNIX: return AF_LOCAL; 199#endif 200 default: return -1; 201 } 202} 203 204static int 205socket_type_to_bsd( SocketType type ) 206{ 207 switch (type) { 208 case SOCKET_DGRAM: return SOCK_DGRAM; 209 case SOCKET_STREAM: return SOCK_STREAM; 210 default: return 0; 211 } 212} 213 214static SocketType 215socket_type_from_bsd( int type ) 216{ 217 switch (type) { 218 case SOCK_DGRAM: return SOCKET_DGRAM; 219 case SOCK_STREAM: return SOCKET_STREAM; 220 default: return (SocketType) SOCKET_UNSPEC; 221 } 222} 223 224#if 0 225static int 226socket_type_check( SocketType type ) 227{ 228 return (type == SOCKET_DGRAM || type == SOCKET_STREAM); 229} 230#endif 231 232typedef union { 233 struct sockaddr sa[1]; 234 struct sockaddr_in in[1]; 235#if HAVE_IN6_SOCKETS 236 struct sockaddr_in6 in6[1]; 237#endif 238#if HAVE_UNIX_SOCKETS 239 struct sockaddr_un un[1]; 240#endif 241} sockaddr_storage; 242 243/* socket addresses */ 244 245void 246sock_address_init_inet( SockAddress* a, uint32_t ip, uint16_t port ) 247{ 248 a->family = SOCKET_INET; 249 a->u.inet.port = port; 250 a->u.inet.address = ip; 251} 252 253void 254sock_address_init_in6 ( SockAddress* a, const uint8_t* ip6[16], uint16_t port ) 255{ 256 a->family = SOCKET_IN6; 257 a->u.in6.port = port; 258 memcpy( a->u.in6.address, ip6, sizeof(a->u.in6.address) ); 259} 260 261void 262sock_address_init_unix( SockAddress* a, const char* path ) 263{ 264 a->family = SOCKET_UNIX; 265 a->u._unix.path = strdup(path ? path : ""); 266 a->u._unix.owner = 1; 267} 268 269void sock_address_done( SockAddress* a ) 270{ 271 if (a->family == SOCKET_UNIX && a->u._unix.owner) { 272 a->u._unix.owner = 0; 273 free((char*)a->u._unix.path); 274 } 275} 276 277static char* 278format_char( char* buf, char* end, int c ) 279{ 280 if (buf < end) { 281 if (buf+1 == end) { 282 *buf++ = 0; 283 } else { 284 *buf++ = (char) c; 285 *buf = 0; 286 } 287 } 288 return buf; 289} 290 291static char* 292format_str( char* buf, char* end, const char* str ) 293{ 294 int len = strlen(str); 295 int avail = end - buf; 296 297 if (len > avail) 298 len = avail; 299 300 memcpy( buf, str, len ); 301 buf += len; 302 303 if (buf == end) 304 buf[-1] = 0; 305 else 306 buf[0] = 0; 307 308 return buf; 309} 310 311static char* 312format_unsigned( char* buf, char* end, unsigned val ) 313{ 314 char temp[16]; 315 int nn; 316 317 for ( nn = 0; val != 0; nn++ ) { 318 int rem = val % 10; 319 temp[nn] = '0'+rem; 320 val /= 10; 321 } 322 323 if (nn == 0) 324 temp[nn++] = '0'; 325 326 while (nn > 0) 327 buf = format_char(buf, end, temp[--nn]); 328 329 return buf; 330} 331 332static char* 333format_hex( char* buf, char* end, unsigned val, int ndigits ) 334{ 335 int shift = 4*ndigits; 336 static const char hex[16] = "0123456789abcdef"; 337 338 while (shift >= 0) { 339 buf = format_char(buf, end, hex[(val >> shift) & 15]); 340 shift -= 4; 341 } 342 return buf; 343} 344 345static char* 346format_ip4( char* buf, char* end, uint32_t ip ) 347{ 348 buf = format_unsigned( buf, end, (unsigned)(ip >> 24) ); 349 buf = format_char( buf, end, '.'); 350 buf = format_unsigned( buf, end, (unsigned)((ip >> 16) & 255)); 351 buf = format_char( buf, end, '.'); 352 buf = format_unsigned( buf, end, (unsigned)((ip >> 8) & 255)); 353 buf = format_char( buf, end, '.'); 354 buf = format_unsigned( buf, end, (unsigned)(ip & 255)); 355 return buf; 356} 357 358static char* 359format_ip6( char* buf, char* end, const uint8_t* ip6 ) 360{ 361 int nn; 362 for (nn = 0; nn < 8; nn++) { 363 int val = (ip6[0] << 16) | ip6[1]; 364 ip6 += 2; 365 if (nn > 0) 366 buf = format_char(buf, end, ':'); 367 if (val == 0) 368 continue; 369 buf = format_hex(buf, end, val, 4); 370 } 371 return buf; 372} 373 374const char* 375sock_address_to_string( const SockAddress* a ) 376{ 377 static char buf0[MAX_PATH]; 378 char *buf = buf0, *end = buf + sizeof(buf0); 379 380 switch (a->family) { 381 case SOCKET_INET: 382 buf = format_ip4( buf, end, a->u.inet.address ); 383 buf = format_char( buf, end, ':' ); 384 buf = format_unsigned( buf, end, (unsigned) a->u.inet.port ); 385 break; 386 387 case SOCKET_IN6: 388 buf = format_ip6( buf, end, a->u.in6.address ); 389 buf = format_char( buf, end, ':' ); 390 buf = format_unsigned( buf, end, (unsigned) a->u.in6.port ); 391 break; 392 393 case SOCKET_UNIX: 394 buf = format_str( buf, end, a->u._unix.path ); 395 break; 396 397 default: 398 return NULL; 399 } 400 401 return buf0; 402} 403 404int 405sock_address_equal( const SockAddress* a, const SockAddress* b ) 406{ 407 if (a->family != b->family) 408 return 0; 409 410 switch (a->family) { 411 case SOCKET_INET: 412 return (a->u.inet.address == b->u.inet.address && 413 a->u.inet.port == b->u.inet.port); 414 415 case SOCKET_IN6: 416 return (!memcmp(a->u.in6.address, b->u.in6.address, 16) && 417 a->u.in6.port == b->u.in6.port); 418 419 case SOCKET_UNIX: 420 return (!strcmp(a->u._unix.path, b->u._unix.path)); 421 422 default: 423 return 0; 424 } 425} 426 427int 428sock_address_get_port( const SockAddress* a ) 429{ 430 switch (a->family) { 431 case SOCKET_INET: 432 return a->u.inet.port; 433 case SOCKET_IN6: 434 return a->u.in6.port; 435 default: 436 return -1; 437 } 438} 439 440void 441sock_address_set_port( SockAddress* a, uint16_t port ) 442{ 443 switch (a->family) { 444 case SOCKET_INET: 445 a->u.inet.port = port; 446 break; 447 case SOCKET_IN6: 448 a->u.in6.port = port; 449 break; 450 default: 451 ; 452 } 453} 454 455const char* 456sock_address_get_path( const SockAddress* a ) 457{ 458 if (a->family == SOCKET_UNIX) 459 return a->u._unix.path; 460 else 461 return NULL; 462} 463 464int 465sock_address_get_ip( const SockAddress* a ) 466{ 467 if (a->family == SOCKET_INET) 468 return a->u.inet.address; 469 470 return -1; 471} 472 473#if 0 474char* 475bufprint_sock_address( char* p, char* end, const SockAddress* a ) 476{ 477 switch (a->family) { 478 case SOCKET_INET: 479 { 480 uint32_t ip = a->u.inet.address; 481 482 return bufprint( p, end, "%d.%d.%d.%d:%d", 483 (ip >> 24) & 255, (ip >> 16) & 255, 484 (ip >> 8) & 255, ip & 255, 485 a->u.inet.port ); 486 } 487 case SOCKET_IN6: 488 { 489 int nn = 0; 490 const char* column = ""; 491 const uint8_t* tab = a->u.in6.address; 492 for (nn = 0; nn < 16; nn += 2) { 493 p = bufprint(p, end, "%s%04x", column, (tab[n] << 8) | tab[n+1]); 494 column = ":"; 495 } 496 return bufprint(p, end, ":%d", a->u.in6.port); 497 } 498 case SOCKET_UNIX: 499 { 500 return bufprint(p, end, "%s", a->u._unix.path); 501 } 502 default: 503 return p; 504 } 505} 506#endif 507 508static int 509sock_address_to_bsd( const SockAddress* a, sockaddr_storage* paddress, socklen_t *psize ) 510{ 511 switch (a->family) { 512 case SOCKET_INET: 513 { 514 struct sockaddr_in* dst = paddress->in; 515 516 *psize = sizeof(*dst); 517 518 memset( paddress, 0, *psize ); 519 520 dst->sin_family = AF_INET; 521 dst->sin_port = htons(a->u.inet.port); 522 dst->sin_addr.s_addr = htonl(a->u.inet.address); 523 } 524 break; 525 526#if HAVE_IN6_SOCKETS 527 case SOCKET_IN6: 528 { 529 struct sockaddr_in6* dst = paddress->in6; 530 531 *psize = sizeof(*dst); 532 533 memset( paddress, 0, *psize ); 534 535 dst->sin6_family = AF_INET6; 536 dst->sin6_port = htons(a->u.in6.port); 537 memcpy( dst->sin6_addr.s6_addr, a->u.in6.address, 16 ); 538 } 539 break; 540#endif /* HAVE_IN6_SOCKETS */ 541 542#if HAVE_UNIX_SOCKETS 543 case SOCKET_UNIX: 544 { 545 int slen = strlen(a->u._unix.path); 546 struct sockaddr_un* dst = paddress->un; 547 548 if (slen >= UNIX_PATH_MAX) 549 return -1; 550 551 memset( dst, 0, sizeof(*dst) ); 552 553 dst->sun_family = AF_LOCAL; 554 memcpy( dst->sun_path, a->u._unix.path, slen ); 555 dst->sun_path[slen] = 0; 556 557 *psize = (char*)&dst->sun_path[slen+1] - (char*)dst; 558 } 559 break; 560#endif /* HAVE_UNIX_SOCKETS */ 561 562 default: 563 return _set_errno(EINVAL); 564 } 565 566 return 0; 567} 568 569static int 570sock_address_from_bsd( SockAddress* a, const void* from, size_t fromlen ) 571{ 572 switch (((struct sockaddr *)from)->sa_family) { 573 case AF_INET: 574 { 575 const struct sockaddr_in* src = from; 576 577 if (fromlen < sizeof(*src)) 578 return _set_errno(EINVAL); 579 580 a->family = SOCKET_INET; 581 a->u.inet.port = ntohs(src->sin_port); 582 a->u.inet.address = ntohl(src->sin_addr.s_addr); 583 } 584 break; 585 586#ifdef HAVE_IN6_SOCKETS 587 case AF_INET6: 588 { 589 const struct sockaddr_in6* src = from; 590 591 if (fromlen < sizeof(*src)) 592 return _set_errno(EINVAL); 593 594 a->family = SOCKET_IN6; 595 a->u.in6.port = ntohs(src->sin6_port); 596 memcpy(a->u.in6.address, src->sin6_addr.s6_addr, 16); 597 } 598 break; 599#endif 600 601#ifdef HAVE_UNIX_SOCKETS 602 case AF_LOCAL: 603 { 604 const struct sockaddr_un* src = from; 605 char* end; 606 607 if (fromlen < sizeof(*src)) 608 return _set_errno(EINVAL); 609 610 /* check that the path is zero-terminated */ 611 end = memchr(src->sun_path, 0, UNIX_PATH_MAX); 612 if (end == NULL) 613 return _set_errno(EINVAL); 614 615 a->family = SOCKET_UNIX; 616 a->u._unix.owner = 1; 617 a->u._unix.path = strdup(src->sun_path); 618 } 619 break; 620#endif 621 622 default: 623 return _set_errno(EINVAL); 624 } 625 return 0; 626} 627 628 629int 630sock_address_init_resolve( SockAddress* a, const char* hostname, uint16_t port, int preferIn6 ) 631{ 632 struct addrinfo hints[1]; 633 struct addrinfo* res; 634 int ret; 635 636 memset(hints, 0, sizeof(hints)); 637 hints->ai_family = preferIn6 ? AF_INET6 : AF_UNSPEC; 638 639 ret = getaddrinfo(hostname, NULL, hints, &res); 640 if (ret != 0) { 641 int err; 642 643 switch (ret) { 644 case EAI_AGAIN: /* server is down */ 645 case EAI_FAIL: /* server is sick */ 646 err = EHOSTDOWN; 647 break; 648 649#ifdef EAI_NODATA 650 case EAI_NODATA: 651#endif 652 case EAI_NONAME: 653 err = ENOENT; 654 break; 655 656 case EAI_MEMORY: 657 err = ENOMEM; 658 break; 659 660 default: 661 err = EINVAL; 662 } 663 return _set_errno(err); 664 } 665 666 /* Parse the returned list of addresses. */ 667 { 668 struct addrinfo* res_ipv4 = NULL; 669 struct addrinfo* res_ipv6 = NULL; 670 struct addrinfo* r; 671 672 /* If preferIn6 is false, we stop on the first IPv4 address, 673 * otherwise, we stop on the first IPv6 one 674 */ 675 for (r = res; r != NULL; r = r->ai_next) { 676 if (r->ai_family == AF_INET && res_ipv4 == NULL) { 677 res_ipv4 = r; 678 if (!preferIn6) 679 break; 680 } 681 else if (r->ai_family == AF_INET6 && res_ipv6 == NULL) { 682 res_ipv6 = r; 683 if (preferIn6) 684 break; 685 } 686 } 687 688 /* Select the best address in 'r', which will be NULL 689 * if there is no corresponding address. 690 */ 691 if (preferIn6) { 692 r = res_ipv6; 693 if (r == NULL) 694 r = res_ipv4; 695 } else { 696 r = res_ipv4; 697 if (r == NULL) 698 r = res_ipv6; 699 } 700 701 if (r == NULL) { 702 ret = _set_errno(ENOENT); 703 goto Exit; 704 } 705 706 /* Convert to a SockAddress */ 707 ret = sock_address_from_bsd( a, r->ai_addr, r->ai_addrlen ); 708 if (ret < 0) 709 goto Exit; 710 } 711 712 /* need to set the port */ 713 switch (a->family) { 714 case SOCKET_INET: a->u.inet.port = port; break; 715 case SOCKET_IN6: a->u.in6.port = port; break; 716 default: ; 717 } 718 719Exit: 720 freeaddrinfo(res); 721 return ret; 722} 723 724/* The Winsock headers for mingw lack some definitions */ 725#ifndef AI_ADDRCONFIG 726# define AI_ADDRCONFIG 0 727#endif 728 729SockAddress** 730sock_address_list_create( const char* hostname, 731 const char* port, 732 unsigned flags ) 733{ 734 SockAddress** list = NULL; 735 SockAddress* addr; 736 int nn, count, ret; 737 struct addrinfo ai, *res, *e; 738 739 memset(&ai, 0, sizeof(ai)); 740 ai.ai_flags |= AI_ADDRCONFIG; 741 ai.ai_family = PF_UNSPEC; 742 743 if (flags & SOCKET_LIST_FORCE_INET) 744 ai.ai_family = PF_INET; 745 else if (flags & SOCKET_LIST_FORCE_IN6) 746 ai.ai_family = PF_INET6; 747 748 if (flags & SOCKET_LIST_PASSIVE) 749 ai.ai_flags |= AI_PASSIVE; 750 else 751 ai.ai_flags |= AI_CANONNAME; 752 753 while (1) { 754 struct addrinfo hints = ai; 755 756 ret = getaddrinfo(hostname, port, &hints, &res); 757 if (ret == 0) 758 break; 759 760 switch (ret) { 761#ifdef EAI_ADDRFAMILY 762 case EAI_ADDRFAMILY: 763#endif 764 case EAI_NODATA: 765 _set_errno(ENOENT); 766 break; 767 case EAI_FAMILY: 768 _set_errno(EAFNOSUPPORT); 769 break; 770 case EAI_AGAIN: 771 _set_errno(EAGAIN); 772 break; 773#ifdef EAI_SYSTEM 774 case EAI_SYSTEM: 775 if (errno == EINTR) 776 continue; 777 break; 778#endif 779 default: 780 _set_errno(EINVAL); 781 } 782 return NULL; 783 } 784 785 /* allocate result list */ 786 for (count = 0, e = res; e != NULL; e = e->ai_next) 787 count += 1; 788 789 list = (SockAddress**) qemu_malloc((count+1)*sizeof(SockAddress*)); 790 addr = (SockAddress*) qemu_malloc(count*sizeof(SockAddress)); 791 792 for (nn = 0, e = res; e != NULL; e = e->ai_next) { 793 794 ret = sock_address_from_bsd(addr, e->ai_addr, e->ai_addrlen); 795 if (ret < 0) 796 continue; 797 798 list[nn++] = addr++; 799 } 800 list[nn] = NULL; 801 freeaddrinfo(res); 802 return list; 803} 804 805void 806sock_address_list_free( SockAddress** list ) 807{ 808 int nn; 809 SockAddress* addr; 810 811 if (list == NULL) 812 return; 813 814 addr = list[0]; 815 for (nn = 0; list[nn] != NULL; nn++) { 816 sock_address_done(list[nn]); 817 list[nn] = NULL; 818 } 819 qemu_free(addr); 820 qemu_free(list); 821} 822 823int 824sock_address_get_numeric_info( SockAddress* a, 825 char* host, 826 size_t hostlen, 827 char* serv, 828 size_t servlen ) 829{ 830 struct sockaddr* saddr; 831 socklen_t slen; 832 int ret; 833 834 switch (a->family) { 835 case SOCKET_INET: 836 saddr = (struct sockaddr*) &a->u.inet.address; 837 slen = sizeof(a->u.inet.address); 838 break; 839 840#if HAVE_IN6_SOCKET 841 case SOCKET_IN6: 842 saddr = (struct sockaddr*) &a->u.in6.address; 843 slen = sizeof(a->u.in6.address); 844 break; 845#endif 846 default: 847 return _set_errno(EINVAL); 848 } 849 850 ret = getnameinfo( saddr, slen, host, hostlen, serv, servlen, 851 NI_NUMERICHOST | NI_NUMERICSERV ); 852 853 switch (ret) { 854 case 0: 855 break; 856 case EAI_AGAIN: 857 ret = EAGAIN; 858 break; 859 default: 860 ret = EINVAL; 861 } 862 return ret; 863} 864 865int 866socket_create( SocketFamily family, SocketType type ) 867{ 868 int ret; 869 int sfamily = socket_family_to_bsd(family); 870 int stype = socket_type_to_bsd(type); 871 872 if (sfamily < 0 || stype < 0) { 873 return _set_errno(EINVAL); 874 } 875 876 QSOCKET_CALL(ret, socket(sfamily, stype, 0)); 877 if (ret < 0) 878 return _fix_errno(); 879 880 return ret; 881} 882 883 884int 885socket_create_inet( SocketType type ) 886{ 887 return socket_create( SOCKET_INET, type ); 888} 889 890#if HAVE_IN6_SOCKETS 891int 892socket_create_in6 ( SocketType type ) 893{ 894 return socket_create( SOCKET_IN6, type ); 895} 896#endif 897 898#if HAVE_UNIX_SOCKETS 899int 900socket_create_unix( SocketType type ) 901{ 902 return socket_create( SOCKET_UNIX, type ); 903} 904#endif 905 906int socket_can_read(int fd) 907{ 908#ifdef _WIN32 909 unsigned long opt; 910 911 if (ioctlsocket(fd, FIONREAD, &opt) < 0) 912 return 0; 913 914 return opt; 915#else 916 int opt; 917 918 if (ioctl(fd, FIONREAD, &opt) < 0) 919 return 0; 920 921 return opt; 922#endif 923} 924 925#define SOCKET_CALL(cmd) \ 926 int ret; \ 927 QSOCKET_CALL(ret, (cmd)); \ 928 if (ret < 0) \ 929 return _fix_errno(); \ 930 return ret; \ 931 932int 933socket_send(int fd, const void* buf, int buflen) 934{ 935 SOCKET_CALL(send(fd, buf, buflen, 0)) 936} 937 938int 939socket_send_oob( int fd, const void* buf, int buflen ) 940{ 941 SOCKET_CALL(send(fd, buf, buflen, MSG_OOB)); 942} 943 944int 945socket_sendto(int fd, const void* buf, int buflen, const SockAddress* to) 946{ 947 sockaddr_storage sa; 948 socklen_t salen; 949 950 if (sock_address_to_bsd(to, &sa, &salen) < 0) 951 return -1; 952 953 SOCKET_CALL(sendto(fd, buf, buflen, 0, sa.sa, salen)); 954} 955 956int 957socket_recv(int fd, void* buf, int len) 958{ 959 SOCKET_CALL(recv(fd, buf, len, 0)); 960} 961 962int 963socket_recvfrom(int fd, void* buf, int len, SockAddress* from) 964{ 965 sockaddr_storage sa; 966 socklen_t salen = sizeof(sa); 967 int ret; 968 969 QSOCKET_CALL(ret,recvfrom(fd,buf,len,0,sa.sa,&salen)); 970 if (ret < 0) 971 return _fix_errno(); 972 973 if (sock_address_from_bsd(from, &sa, salen) < 0) 974 return -1; 975 976 return ret; 977} 978 979int 980socket_connect( int fd, const SockAddress* address ) 981{ 982 sockaddr_storage addr; 983 socklen_t addrlen; 984 985 if (sock_address_to_bsd(address, &addr, &addrlen) < 0) 986 return -1; 987 988 SOCKET_CALL(connect(fd,addr.sa,addrlen)); 989} 990 991int 992socket_bind( int fd, const SockAddress* address ) 993{ 994 sockaddr_storage addr; 995 socklen_t addrlen; 996 997 if (sock_address_to_bsd(address, &addr, &addrlen) < 0) 998 return -1; 999 1000 SOCKET_CALL(bind(fd, addr.sa, addrlen)); 1001} 1002 1003int 1004socket_get_address( int fd, SockAddress* address ) 1005{ 1006 sockaddr_storage addr; 1007 socklen_t addrlen = sizeof(addr); 1008 int ret; 1009 1010 QSOCKET_CALL(ret, getsockname(fd, addr.sa, &addrlen)); 1011 if (ret < 0) 1012 return _fix_errno(); 1013 1014 return sock_address_from_bsd(address, &addr, addrlen); 1015} 1016 1017int 1018socket_get_peer_address( int fd, SockAddress* address ) 1019{ 1020 sockaddr_storage addr; 1021 socklen_t addrlen = sizeof(addr); 1022 int ret; 1023 1024 QSOCKET_CALL(ret, getpeername(fd, addr.sa, &addrlen)); 1025 if (ret < 0) 1026 return _fix_errno(); 1027 1028 return sock_address_from_bsd(address, &addr, addrlen); 1029} 1030 1031int 1032socket_listen( int fd, int backlog ) 1033{ 1034 SOCKET_CALL(listen(fd, backlog)); 1035} 1036 1037int 1038socket_accept( int fd, SockAddress* address ) 1039{ 1040 sockaddr_storage addr; 1041 socklen_t addrlen = sizeof(addr); 1042 int ret; 1043 1044 QSOCKET_CALL(ret, accept(fd, addr.sa, &addrlen)); 1045 if (ret < 0) 1046 return _fix_errno(); 1047 1048 if (address) { 1049 if (sock_address_from_bsd(address, &addr, addrlen) < 0) { 1050 socket_close(ret); 1051 return -1; 1052 } 1053 } 1054 return ret; 1055} 1056 1057static int 1058socket_getoption(int fd, int domain, int option, int defaut) 1059{ 1060 int ret; 1061 while (1) { 1062#ifdef _WIN32 1063 DWORD opt = (DWORD)-1; 1064#else 1065 int opt = -1; 1066#endif 1067 socklen_t optlen = sizeof(opt); 1068 ret = getsockopt(fd, domain, option, (char*)&opt, &optlen); 1069 if (ret == 0) 1070 return (int)opt; 1071 if (errno != EINTR) 1072 return defaut; 1073 } 1074#undef OPT_CAST 1075} 1076 1077 1078SocketType socket_get_type(int fd) 1079{ 1080 int so_type = socket_getoption(fd, SOL_SOCKET, SO_TYPE, -1); 1081 return socket_type_from_bsd(so_type); 1082} 1083 1084int socket_set_nonblock(int fd) 1085{ 1086#ifdef _WIN32 1087 unsigned long opt = 1; 1088 return ioctlsocket(fd, FIONBIO, &opt); 1089#else 1090 int flags = fcntl(fd, F_GETFL); 1091 return fcntl(fd, F_SETFL, flags | O_NONBLOCK); 1092#endif 1093} 1094 1095int socket_set_blocking(int fd) 1096{ 1097#ifdef _WIN32 1098 unsigned long opt = 0; 1099 return ioctlsocket(fd, FIONBIO, &opt); 1100#else 1101 int flags = fcntl(fd, F_GETFL); 1102 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); 1103#endif 1104} 1105 1106static int 1107socket_setoption(int fd, int domain, int option, int _flag) 1108{ 1109#ifdef _WIN32 1110 DWORD flag = (DWORD) _flag; 1111#else 1112 int flag = _flag; 1113#endif 1114 return setsockopt( fd, domain, option, (const char*)&flag, sizeof(flag) ); 1115} 1116 1117int socket_set_xreuseaddr(int fd) 1118{ 1119#ifdef _WIN32 1120 /* on Windows, SO_REUSEADDR is used to indicate that several programs can 1121 * bind to the same port. this is completely different from the Unix 1122 * semantics. instead of SO_EXCLUSIVEADDR to ensure that explicitely prevent 1123 * this. 1124 */ 1125 return socket_setoption(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1); 1126#else 1127 return socket_setoption(fd, SOL_SOCKET, SO_REUSEADDR, 1); 1128#endif 1129} 1130 1131 1132int socket_set_oobinline(int fd) 1133{ 1134 return socket_setoption(fd, SOL_SOCKET, SO_OOBINLINE, 1); 1135} 1136 1137 1138int socket_set_nodelay(int fd) 1139{ 1140 return socket_setoption(fd, IPPROTO_TCP, TCP_NODELAY, 1); 1141} 1142 1143int socket_set_ipv6only(int fd) 1144{ 1145/* IPV6_ONLY is only supported since Vista on Windows, 1146 * and the Mingw headers lack its definition anyway. 1147 */ 1148#if defined(_WIN32) && !defined(IPV6_V6ONLY) 1149 return 0; 1150#else 1151 return socket_setoption(fd, IPPROTO_IPV6, IPV6_V6ONLY, 1); 1152#endif 1153} 1154 1155 1156int socket_get_error(int fd) 1157{ 1158 return socket_getoption(fd, SOL_SOCKET, SO_ERROR, -1); 1159} 1160 1161#ifdef _WIN32 1162#include <stdlib.h> 1163 1164static void socket_cleanup(void) 1165{ 1166 WSACleanup(); 1167} 1168 1169int socket_init(void) 1170{ 1171 WSADATA Data; 1172 int ret, err; 1173 1174 ret = WSAStartup(MAKEWORD(2,2), &Data); 1175 if (ret != 0) { 1176 err = WSAGetLastError(); 1177 return -1; 1178 } 1179 atexit(socket_cleanup); 1180 return 0; 1181} 1182 1183#else /* !_WIN32 */ 1184 1185int socket_init(void) 1186{ 1187 return 0; /* nothing to do on Unix */ 1188} 1189 1190#endif /* !_WIN32 */ 1191 1192#ifdef _WIN32 1193 1194static void 1195socket_close_handler( void* _fd ) 1196{ 1197 int fd = (int)_fd; 1198 int ret; 1199 char buff[64]; 1200 1201 /* we want to drain the read side of the socket before closing it */ 1202 do { 1203 ret = recv( fd, buff, sizeof(buff), 0 ); 1204 } while (ret < 0 && WSAGetLastError() == WSAEINTR); 1205 1206 if (ret < 0 && WSAGetLastError() == EWOULDBLOCK) 1207 return; 1208 1209 qemu_set_fd_handler( fd, NULL, NULL, NULL ); 1210 closesocket( fd ); 1211} 1212 1213void 1214socket_close( int fd ) 1215{ 1216 int old_errno = errno; 1217 1218 shutdown( fd, SD_BOTH ); 1219 /* we want to drain the socket before closing it */ 1220 qemu_set_fd_handler( fd, socket_close_handler, NULL, (void*)fd ); 1221 1222 errno = old_errno; 1223} 1224 1225#else /* !_WIN32 */ 1226 1227#include <unistd.h> 1228 1229void 1230socket_close( int fd ) 1231{ 1232 int old_errno = errno; 1233 1234 shutdown( fd, SHUT_RDWR ); 1235 close( fd ); 1236 1237 errno = old_errno; 1238} 1239 1240#endif /* !_WIN32 */ 1241 1242 1243static int 1244socket_bind_server( int s, const SockAddress* to, SocketType type ) 1245{ 1246 socket_set_xreuseaddr(s); 1247 1248 if (socket_bind(s, to) < 0) { 1249 D("could not bind server socket address %s: %s", 1250 sock_address_to_string(to), errno_str); 1251 goto FAIL; 1252 } 1253 1254 if (type == SOCKET_STREAM) { 1255 if (socket_listen(s, 4) < 0) { 1256 D("could not listen server socket %s: %s", 1257 sock_address_to_string(to), errno_str); 1258 goto FAIL; 1259 } 1260 } 1261 return s; 1262 1263FAIL: 1264 socket_close(s); 1265 return -1; 1266} 1267 1268 1269static int 1270socket_connect_client( int s, const SockAddress* to ) 1271{ 1272 if (socket_connect(s, to) < 0) { 1273 D( "could not connect client socket to %s: %s\n", 1274 sock_address_to_string(to), errno_str ); 1275 socket_close(s); 1276 return -1; 1277 } 1278 1279 socket_set_nonblock( s ); 1280 return s; 1281} 1282 1283 1284static int 1285socket_in_server( int address, int port, SocketType type ) 1286{ 1287 SockAddress addr; 1288 int s; 1289 1290 sock_address_init_inet( &addr, address, port ); 1291 s = socket_create_inet( type ); 1292 if (s < 0) 1293 return -1; 1294 1295 return socket_bind_server( s, &addr, type ); 1296} 1297 1298 1299static int 1300socket_in_client( SockAddress* to, SocketType type ) 1301{ 1302 int s; 1303 1304 s = socket_create_inet( type ); 1305 if (s < 0) return -1; 1306 1307 return socket_connect_client( s, to ); 1308} 1309 1310 1311int 1312socket_loopback_server( int port, SocketType type ) 1313{ 1314 return socket_in_server( SOCK_ADDRESS_INET_LOOPBACK, port, type ); 1315} 1316 1317int 1318socket_loopback_client( int port, SocketType type ) 1319{ 1320 SockAddress addr; 1321 1322 sock_address_init_inet( &addr, SOCK_ADDRESS_INET_LOOPBACK, port ); 1323 return socket_in_client( &addr, type ); 1324} 1325 1326 1327int 1328socket_network_client( const char* host, int port, SocketType type ) 1329{ 1330 SockAddress addr; 1331 1332 if (sock_address_init_resolve( &addr, host, port, 0) < 0) 1333 return -1; 1334 1335 return socket_in_client( &addr, type ); 1336} 1337 1338 1339int 1340socket_anyaddr_server( int port, SocketType type ) 1341{ 1342 return socket_in_server( SOCK_ADDRESS_INET_ANY, port, type ); 1343} 1344 1345int 1346socket_accept_any( int server_fd ) 1347{ 1348 int fd; 1349 1350 QSOCKET_CALL(fd, accept( server_fd, NULL, 0 )); 1351 if (fd < 0) { 1352 D( "could not accept client connection from fd %d: %s", 1353 server_fd, errno_str ); 1354 return -1; 1355 } 1356 1357 /* set to non-blocking */ 1358 socket_set_nonblock( fd ); 1359 return fd; 1360} 1361 1362 1363#if HAVE_UNIX_SOCKETS 1364 1365int 1366socket_unix_server( const char* name, SocketType type ) 1367{ 1368 SockAddress addr; 1369 int s, ret; 1370 1371 s = socket_create_unix( type ); 1372 if (s < 0) 1373 return -1; 1374 1375 sock_address_init_unix( &addr, name ); 1376 1377 do { 1378 ret = unlink( name ); 1379 } while (ret < 0 && errno == EINTR); 1380 1381 ret = socket_bind_server( s, &addr, type ); 1382 1383 sock_address_done( &addr ); 1384 return ret; 1385} 1386 1387int 1388socket_unix_client( const char* name, SocketType type ) 1389{ 1390 SockAddress addr; 1391 int s, ret; 1392 1393 s = socket_create_unix(type); 1394 if (s < 0) 1395 return -1; 1396 1397 sock_address_init_unix( &addr, name ); 1398 1399 ret = socket_connect_client( s, &addr ); 1400 1401 sock_address_done( &addr ); 1402 return ret; 1403} 1404 1405#endif /* HAVE_UNIX_SOCKETS */ 1406 1407 1408 1409int 1410socket_pair(int *fd1, int *fd2) 1411{ 1412#ifndef _WIN32 1413 int fds[2]; 1414 int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds); 1415 1416 if (!ret) { 1417 socket_set_nonblock(fds[0]); 1418 socket_set_nonblock(fds[1]); 1419 *fd1 = fds[0]; 1420 *fd2 = fds[1]; 1421 } 1422 return ret; 1423#else /* _WIN32 */ 1424 /* on Windows, select() only works with network sockets, which 1425 * means we absolutely cannot use Win32 PIPEs to implement 1426 * socket pairs with the current event loop implementation. 1427 * We're going to do like Cygwin: create a random pair 1428 * of localhost TCP sockets and connect them together 1429 */ 1430 int s0, s1, s2, port; 1431 struct sockaddr_in sockin; 1432 socklen_t len; 1433 1434 /* first, create the 'server' socket. 1435 * a port number of 0 means 'any port between 1024 and 5000. 1436 * see Winsock bind() documentation for details */ 1437 s0 = socket_loopback_server( 0, SOCK_STREAM ); 1438 if (s0 < 0) 1439 return -1; 1440 1441 /* now connect a client socket to it, we first need to 1442 * extract the server socket's port number */ 1443 len = sizeof sockin; 1444 if (getsockname(s0, (struct sockaddr*) &sockin, &len) < 0) { 1445 closesocket (s0); 1446 return -1; 1447 } 1448 1449 port = ntohs(sockin.sin_port); 1450 s2 = socket_loopback_client( port, SOCK_STREAM ); 1451 if (s2 < 0) { 1452 closesocket(s0); 1453 return -1; 1454 } 1455 1456 /* we need to accept the connection on the server socket 1457 * this will create the second socket for the pair 1458 */ 1459 len = sizeof sockin; 1460 s1 = accept(s0, (struct sockaddr*) &sockin, &len); 1461 if (s1 == INVALID_SOCKET) { 1462 closesocket (s0); 1463 closesocket (s2); 1464 return -1; 1465 } 1466 socket_set_nonblock(s1); 1467 1468 /* close server socket */ 1469 closesocket(s0); 1470 *fd1 = s1; 1471 *fd2 = s2; 1472 return 0; 1473#endif /* _WIN32 */ 1474} 1475 1476 1477 1478int 1479socket_mcast_inet_add_membership( int s, uint32_t ip ) 1480{ 1481 struct ip_mreq imr; 1482 1483 imr.imr_multiaddr.s_addr = htonl(ip); 1484 imr.imr_interface.s_addr = htonl(INADDR_ANY); 1485 1486 if ( setsockopt( s, IPPROTO_IP, IP_ADD_MEMBERSHIP, 1487 (const char *)&imr, 1488 sizeof(struct ip_mreq)) < 0 ) 1489 { 1490 return _fix_errno(); 1491 } 1492 return 0; 1493} 1494 1495int 1496socket_mcast_inet_drop_membership( int s, uint32_t ip ) 1497{ 1498 struct ip_mreq imr; 1499 1500 imr.imr_multiaddr.s_addr = htonl(ip); 1501 imr.imr_interface.s_addr = htonl(INADDR_ANY); 1502 1503 if ( setsockopt( s, IPPROTO_IP, IP_DROP_MEMBERSHIP, 1504 (const char *)&imr, 1505 sizeof(struct ip_mreq)) < 0 ) 1506 { 1507 return _fix_errno(); 1508 } 1509 return 0; 1510} 1511 1512int 1513socket_mcast_inet_set_loop( int s, int enabled ) 1514{ 1515 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_LOOP, !!enabled ); 1516} 1517 1518int 1519socket_mcast_inet_set_ttl( int s, int ttl ) 1520{ 1521 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_TTL, ttl ); 1522} 1523 1524 1525char* 1526host_name( void ) 1527{ 1528 static char buf[256]; /* 255 is the max host name length supported by DNS */ 1529 int ret; 1530 1531 QSOCKET_CALL(ret, gethostname(buf, sizeof(buf))); 1532 1533 if (ret < 0) 1534 return "localhost"; 1535 else 1536 return buf; 1537} 1538