1 /*
   2  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 #include "net_util.h"
  26 
  27 #include "java_net_InetAddress.h"
  28 #include "java_net_SocketOptions.h"
  29 
  30 // Taken from mstcpip.h in Windows SDK 8.0 or newer.
  31 #define SIO_LOOPBACK_FAST_PATH              _WSAIOW(IOC_VENDOR,16)
  32 
  33 #ifndef IPTOS_TOS_MASK
  34 #define IPTOS_TOS_MASK 0x1e
  35 #endif
  36 #ifndef IPTOS_PREC_MASK
  37 #define IPTOS_PREC_MASK 0xe0
  38 #endif
  39 
  40 /* true if SO_RCVTIMEO is supported */
  41 jboolean isRcvTimeoutSupported = JNI_TRUE;
  42 
  43 /*
  44  * Table of Windows Sockets errors, the specific exception we
  45  * throw for the error, and the error text.
  46  *
  47  * Note that this table excludes OS dependent errors.
  48  *
  49  * Latest list of Windows Sockets errors can be found at :-
  50  * http://msdn.microsoft.com/library/psdk/winsock/errors_3wc2.htm
  51  */
  52 static struct {
  53     int errCode;
  54     const char *exc;
  55     const char *errString;
  56 } const winsock_errors[] = {
  57     { WSAEACCES,                0,      "Permission denied" },
  58     { WSAEADDRINUSE,            "BindException",        "Address already in use" },
  59     { WSAEADDRNOTAVAIL,         "BindException",        "Cannot assign requested address" },
  60     { WSAEAFNOSUPPORT,          0,      "Address family not supported by protocol family" },
  61     { WSAEALREADY,              0,      "Operation already in progress" },
  62     { WSAECONNABORTED,          0,      "Software caused connection abort" },
  63     { WSAECONNREFUSED,          "ConnectException",     "Connection refused" },
  64     { WSAECONNRESET,            0,      "Connection reset by peer" },
  65     { WSAEDESTADDRREQ,          0,      "Destination address required" },
  66     { WSAEFAULT,                0,      "Bad address" },
  67     { WSAEHOSTDOWN,             0,      "Host is down" },
  68     { WSAEHOSTUNREACH,          "NoRouteToHostException",       "No route to host" },
  69     { WSAEINPROGRESS,           0,      "Operation now in progress" },
  70     { WSAEINTR,                 0,      "Interrupted function call" },
  71     { WSAEINVAL,                0,      "Invalid argument" },
  72     { WSAEISCONN,               0,      "Socket is already connected" },
  73     { WSAEMFILE,                0,      "Too many open files" },
  74     { WSAEMSGSIZE,              0,      "The message is larger than the maximum supported by the underlying transport" },
  75     { WSAENETDOWN,              0,      "Network is down" },
  76     { WSAENETRESET,             0,      "Network dropped connection on reset" },
  77     { WSAENETUNREACH,           0,      "Network is unreachable" },
  78     { WSAENOBUFS,               0,      "No buffer space available (maximum connections reached?)" },
  79     { WSAENOPROTOOPT,           0,      "Bad protocol option" },
  80     { WSAENOTCONN,              0,      "Socket is not connected" },
  81     { WSAENOTSOCK,              0,      "Socket operation on nonsocket" },
  82     { WSAEOPNOTSUPP,            0,      "Operation not supported" },
  83     { WSAEPFNOSUPPORT,          0,      "Protocol family not supported" },
  84     { WSAEPROCLIM,              0,      "Too many processes" },
  85     { WSAEPROTONOSUPPORT,       0,      "Protocol not supported" },
  86     { WSAEPROTOTYPE,            0,      "Protocol wrong type for socket" },
  87     { WSAESHUTDOWN,             0,      "Cannot send after socket shutdown" },
  88     { WSAESOCKTNOSUPPORT,       0,      "Socket type not supported" },
  89     { WSAETIMEDOUT,             "ConnectException",     "Connection timed out" },
  90     { WSATYPE_NOT_FOUND,        0,      "Class type not found" },
  91     { WSAEWOULDBLOCK,           0,      "Resource temporarily unavailable" },
  92     { WSAHOST_NOT_FOUND,        0,      "Host not found" },
  93     { WSA_NOT_ENOUGH_MEMORY,    0,      "Insufficient memory available" },
  94     { WSANOTINITIALISED,        0,      "Successful WSAStartup not yet performed" },
  95     { WSANO_DATA,               0,      "Valid name, no data record of requested type" },
  96     { WSANO_RECOVERY,           0,      "This is a nonrecoverable error" },
  97     { WSASYSNOTREADY,           0,      "Network subsystem is unavailable" },
  98     { WSATRY_AGAIN,             0,      "Nonauthoritative host not found" },
  99     { WSAVERNOTSUPPORTED,       0,      "Winsock.dll version out of range" },
 100     { WSAEDISCON,               0,      "Graceful shutdown in progress" },
 101     { WSA_OPERATION_ABORTED,    0,      "Overlapped operation aborted" },
 102 };
 103 
 104 /*
 105  * Initialize Windows Sockets API support
 106  */
 107 BOOL WINAPI
 108 DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved)
 109 {
 110     WSADATA wsadata;
 111 
 112     switch (reason) {
 113         case DLL_PROCESS_ATTACH:
 114             if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {
 115                 return FALSE;
 116             }
 117             break;
 118 
 119         case DLL_PROCESS_DETACH:
 120             WSACleanup();
 121             break;
 122 
 123         default:
 124             break;
 125     }
 126     return TRUE;
 127 }
 128 
 129 void platformInit() {}
 130 
 131 /*
 132  * Since winsock doesn't have the equivalent of strerror(errno)
 133  * use table to lookup error text for the error.
 134  */
 135 JNIEXPORT void JNICALL
 136 NET_ThrowNew(JNIEnv *env, int errorNum, char *msg)
 137 {
 138     int i;
 139     int table_size = sizeof(winsock_errors) /
 140                      sizeof(winsock_errors[0]);
 141     char exc[256];
 142     char fullMsg[256];
 143     char *excP = NULL;
 144 
 145     /*
 146      * If exception already throw then don't overwrite it.
 147      */
 148     if ((*env)->ExceptionOccurred(env)) {
 149         return;
 150     }
 151 
 152     /*
 153      * Default message text if not provided
 154      */
 155     if (!msg) {
 156         msg = "no further information";
 157     }
 158 
 159     /*
 160      * Check table for known winsock errors
 161      */
 162     i=0;
 163     while (i < table_size) {
 164         if (errorNum == winsock_errors[i].errCode) {
 165             break;
 166         }
 167         i++;
 168     }
 169 
 170     /*
 171      * If found get pick the specific exception and error
 172      * message corresponding to this error.
 173      */
 174     if (i < table_size) {
 175         excP = (char *)winsock_errors[i].exc;
 176         jio_snprintf(fullMsg, sizeof(fullMsg), "%s: %s",
 177                      (char *)winsock_errors[i].errString, msg);
 178     } else {
 179         jio_snprintf(fullMsg, sizeof(fullMsg),
 180                      "Unrecognized Windows Sockets error: %d: %s",
 181                      errorNum, msg);
 182 
 183     }
 184 
 185     /*
 186      * Throw SocketException if no specific exception for this
 187      * error.
 188      */
 189     if (excP == NULL) {
 190         excP = "SocketException";
 191     }
 192     sprintf(exc, "%s%s", JNU_JAVANETPKG, excP);
 193     JNU_ThrowByName(env, exc, fullMsg);
 194 }
 195 
 196 void
 197 NET_ThrowCurrent(JNIEnv *env, char *msg)
 198 {
 199     NET_ThrowNew(env, WSAGetLastError(), msg);
 200 }
 201 
 202 void
 203 NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
 204                    const char *defaultDetail) {
 205     JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);
 206 }
 207 
 208 jfieldID
 209 NET_GetFileDescriptorID(JNIEnv *env)
 210 {
 211     jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
 212     CHECK_NULL_RETURN(cls, NULL);
 213     return (*env)->GetFieldID(env, cls, "fd", "I");
 214 }
 215 
 216 jint  IPv4_supported()
 217 {
 218     /* TODO: properly check for IPv4 support on Windows */
 219     return JNI_TRUE;
 220 }
 221 
 222 jint  IPv6_supported()
 223 {
 224     SOCKET s = socket(AF_INET6, SOCK_STREAM, 0) ;
 225     if (s == INVALID_SOCKET) {
 226         return JNI_FALSE;
 227     }
 228     closesocket(s);
 229 
 230     return JNI_TRUE;
 231 }
 232 
 233 jint reuseport_supported()
 234 {
 235     /* SO_REUSEPORT is not supported on Windows */
 236     return JNI_FALSE;
 237 }
 238 
 239 /* call NET_MapSocketOptionV6 for the IPv6 fd only
 240  * and NET_MapSocketOption for the IPv4 fd
 241  */
 242 JNIEXPORT int JNICALL
 243 NET_MapSocketOptionV6(jint cmd, int *level, int *optname) {
 244 
 245     switch (cmd) {
 246         case java_net_SocketOptions_IP_MULTICAST_IF:
 247         case java_net_SocketOptions_IP_MULTICAST_IF2:
 248             *level = IPPROTO_IPV6;
 249             *optname = IPV6_MULTICAST_IF;
 250             return 0;
 251 
 252         case java_net_SocketOptions_IP_MULTICAST_LOOP:
 253             *level = IPPROTO_IPV6;
 254             *optname = IPV6_MULTICAST_LOOP;
 255             return 0;
 256     }
 257     return NET_MapSocketOption (cmd, level, optname);
 258 }
 259 
 260 /*
 261  * Map the Java level socket option to the platform specific
 262  * level and option name.
 263  */
 264 
 265 JNIEXPORT int JNICALL
 266 NET_MapSocketOption(jint cmd, int *level, int *optname) {
 267 
 268     typedef struct {
 269         jint cmd;
 270         int level;
 271         int optname;
 272     } sockopts;
 273 
 274     static sockopts opts[] = {
 275         { java_net_SocketOptions_TCP_NODELAY,   IPPROTO_TCP,    TCP_NODELAY },
 276         { java_net_SocketOptions_SO_OOBINLINE,  SOL_SOCKET,     SO_OOBINLINE },
 277         { java_net_SocketOptions_SO_LINGER,     SOL_SOCKET,     SO_LINGER },
 278         { java_net_SocketOptions_SO_SNDBUF,     SOL_SOCKET,     SO_SNDBUF },
 279         { java_net_SocketOptions_SO_RCVBUF,     SOL_SOCKET,     SO_RCVBUF },
 280         { java_net_SocketOptions_SO_KEEPALIVE,  SOL_SOCKET,     SO_KEEPALIVE },
 281         { java_net_SocketOptions_SO_REUSEADDR,  SOL_SOCKET,     SO_REUSEADDR },
 282         { java_net_SocketOptions_SO_BROADCAST,  SOL_SOCKET,     SO_BROADCAST },
 283         { java_net_SocketOptions_IP_MULTICAST_IF,   IPPROTO_IP, IP_MULTICAST_IF },
 284         { java_net_SocketOptions_IP_MULTICAST_LOOP, IPPROTO_IP, IP_MULTICAST_LOOP },
 285         { java_net_SocketOptions_IP_TOS,            IPPROTO_IP, IP_TOS },
 286 
 287     };
 288 
 289 
 290     int i;
 291 
 292     /*
 293      * Map the Java level option to the native level
 294      */
 295     for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
 296         if (cmd == opts[i].cmd) {
 297             *level = opts[i].level;
 298             *optname = opts[i].optname;
 299             return 0;
 300         }
 301     }
 302 
 303     /* not found */
 304     return -1;
 305 }
 306 
 307 
 308 /*
 309  * Wrapper for setsockopt dealing with Windows specific issues :-
 310  *
 311  * IP_TOS and IP_MULTICAST_LOOP can't be set on some Windows
 312  * editions.
 313  *
 314  * The value for the type-of-service (TOS) needs to be masked
 315  * to get consistent behaviour with other operating systems.
 316  */
 317 JNIEXPORT int JNICALL
 318 NET_SetSockOpt(int s, int level, int optname, const void *optval,
 319                int optlen)
 320 {
 321     int rv = 0;
 322     int parg = 0;
 323     int plen = sizeof(parg);
 324 
 325     if (level == IPPROTO_IP && optname == IP_TOS) {
 326         int *tos = (int *)optval;
 327         *tos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
 328     }
 329 
 330     if (optname == SO_REUSEADDR) {
 331         /*
 332          * Do not set SO_REUSEADDE if SO_EXCLUSIVEADDUSE is already set
 333          */
 334         rv = NET_GetSockOpt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&parg, &plen);
 335         if (rv == 0 && parg == 1) {
 336             return rv;
 337         }
 338     }
 339 
 340     rv = setsockopt(s, level, optname, optval, optlen);
 341 
 342     if (rv == SOCKET_ERROR) {
 343         /*
 344          * IP_TOS & IP_MULTICAST_LOOP can't be set on some versions
 345          * of Windows.
 346          */
 347         if ((WSAGetLastError() == WSAENOPROTOOPT) &&
 348             (level == IPPROTO_IP) &&
 349             (optname == IP_TOS || optname == IP_MULTICAST_LOOP)) {
 350             rv = 0;
 351         }
 352 
 353         /*
 354          * IP_TOS can't be set on unbound UDP sockets.
 355          */
 356         if ((WSAGetLastError() == WSAEINVAL) &&
 357             (level == IPPROTO_IP) &&
 358             (optname == IP_TOS)) {
 359             rv = 0;
 360         }
 361     }
 362 
 363     return rv;
 364 }
 365 
 366 /*
 367  * Wrapper for setsockopt dealing with Windows specific issues :-
 368  *
 369  * IP_TOS is not supported on some versions of Windows so
 370  * instead return the default value for the OS.
 371  */
 372 JNIEXPORT int JNICALL
 373 NET_GetSockOpt(int s, int level, int optname, void *optval,
 374                int *optlen)
 375 {
 376     int rv;
 377 
 378     if (level == IPPROTO_IPV6 && optname == IPV6_TCLASS) {
 379         int *intopt = (int *)optval;
 380         *intopt = 0;
 381         *optlen = sizeof(*intopt);
 382         return 0;
 383     }
 384 
 385     rv = getsockopt(s, level, optname, optval, optlen);
 386 
 387 
 388     /*
 389      * IPPROTO_IP/IP_TOS is not supported on some Windows
 390      * editions so return the default type-of-service
 391      * value.
 392      */
 393     if (rv == SOCKET_ERROR) {
 394 
 395         if (WSAGetLastError() == WSAENOPROTOOPT &&
 396             level == IPPROTO_IP && optname == IP_TOS) {
 397 
 398             *((int *)optval) = 0;
 399             rv = 0;
 400         }
 401     }
 402 
 403     return rv;
 404 }
 405 
 406 JNIEXPORT int JNICALL
 407 NET_SocketAvailable(int s, int *pbytes) {
 408     u_long arg;
 409     if (ioctlsocket((SOCKET)s, FIONREAD, &arg) == SOCKET_ERROR) {
 410         return -1;
 411     } else {
 412         *pbytes = (int) arg;
 413         return 0;
 414     }
 415 }
 416 
 417 /*
 418  * Sets SO_ECLUSIVEADDRUSE if SO_REUSEADDR is not already set.
 419  */
 420 void setExclusiveBind(int fd) {
 421     int parg = 0;
 422     int plen = sizeof(parg);
 423     int rv = 0;
 424     rv = NET_GetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&parg, &plen);
 425     if (rv == 0 && parg == 0) {
 426         parg = 1;
 427         rv = NET_SetSockOpt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&parg, plen);
 428     }
 429 }
 430 
 431 /*
 432  * Wrapper for bind winsock call - transparent converts an
 433  * error related to binding to a port that has exclusive access
 434  * into an error indicating the port is in use (facilitates
 435  * better error reporting).
 436  *
 437  * Should be only called by the wrapper method NET_WinBind
 438  */
 439 JNIEXPORT int JNICALL
 440 NET_Bind(int s, SOCKETADDRESS *sa, int len)
 441 {
 442     int rv = 0;
 443     rv = bind(s, &sa->sa, len);
 444 
 445     if (rv == SOCKET_ERROR) {
 446         /*
 447          * If bind fails with WSAEACCES it means that a privileged
 448          * process has done an exclusive bind (NT SP4/2000/XP only).
 449          */
 450         if (WSAGetLastError() == WSAEACCES) {
 451             WSASetLastError(WSAEADDRINUSE);
 452         }
 453     }
 454 
 455     return rv;
 456 }
 457 
 458 /*
 459  * Wrapper for NET_Bind call. Sets SO_EXCLUSIVEADDRUSE
 460  * if required, and then calls NET_BIND
 461  */
 462 JNIEXPORT int JNICALL
 463 NET_WinBind(int s, SOCKETADDRESS *sa, int len, jboolean exclBind)
 464 {
 465     if (exclBind == JNI_TRUE)
 466         setExclusiveBind(s);
 467     return NET_Bind(s, sa, len);
 468 }
 469 
 470 JNIEXPORT int JNICALL
 471 NET_SocketClose(int fd) {
 472     struct linger l = {0, 0};
 473     int ret = 0;
 474     int len = sizeof (l);
 475     if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, &len) == 0) {
 476         if (l.l_onoff == 0) {
 477             shutdown(fd, SD_SEND);
 478         }
 479     }
 480     ret = closesocket (fd);
 481     return ret;
 482 }
 483 
 484 JNIEXPORT int JNICALL
 485 NET_Timeout(int fd, long timeout) {
 486     int ret;
 487     fd_set tbl;
 488     struct timeval t;
 489     t.tv_sec = timeout / 1000;
 490     t.tv_usec = (timeout % 1000) * 1000;
 491     FD_ZERO(&tbl);
 492     FD_SET(fd, &tbl);
 493     ret = select (fd + 1, &tbl, 0, 0, &t);
 494     return ret;
 495 }
 496 
 497 
 498 /*
 499  * differs from NET_Timeout() as follows:
 500  *
 501  * If timeout = -1, it blocks forever.
 502  *
 503  * returns 1 or 2 depending if only one or both sockets
 504  * fire at same time.
 505  *
 506  * *fdret is (one of) the active fds. If both sockets
 507  * fire at same time, *fdret = fd always.
 508  */
 509 JNIEXPORT int JNICALL
 510 NET_Timeout2(int fd, int fd1, long timeout, int *fdret) {
 511     int ret;
 512     fd_set tbl;
 513     struct timeval t, *tP = &t;
 514     if (timeout == -1) {
 515         tP = 0;
 516     } else {
 517         t.tv_sec = timeout / 1000;
 518         t.tv_usec = (timeout % 1000) * 1000;
 519     }
 520     FD_ZERO(&tbl);
 521     FD_SET(fd, &tbl);
 522     FD_SET(fd1, &tbl);
 523     ret = select (0, &tbl, 0, 0, tP);
 524     switch (ret) {
 525     case 0:
 526         return 0; /* timeout */
 527     case 1:
 528         if (FD_ISSET (fd, &tbl)) {
 529             *fdret= fd;
 530         } else {
 531             *fdret= fd1;
 532         }
 533         return 1;
 534     case 2:
 535         *fdret= fd;
 536         return 2;
 537     }
 538     return -1;
 539 }
 540 
 541 
 542 void dumpAddr (char *str, void *addr) {
 543     struct sockaddr_in6 *a = (struct sockaddr_in6 *)addr;
 544     int family = a->sin6_family;
 545     printf ("%s\n", str);
 546     if (family == AF_INET) {
 547         struct sockaddr_in *him = (struct sockaddr_in *)addr;
 548         printf ("AF_INET: port %d: %x\n", ntohs(him->sin_port),
 549                                           ntohl(him->sin_addr.s_addr));
 550     } else {
 551         int i;
 552         struct in6_addr *in = &a->sin6_addr;
 553         printf ("AF_INET6 ");
 554         printf ("port %d ", ntohs (a->sin6_port));
 555         printf ("flow %d ", a->sin6_flowinfo);
 556         printf ("addr ");
 557         for (i=0; i<7; i++) {
 558             printf ("%04x:", ntohs(in->s6_words[i]));
 559         }
 560         printf ("%04x", ntohs(in->s6_words[7]));
 561         printf (" scope %d\n", a->sin6_scope_id);
 562     }
 563 }
 564 
 565 /* Macro, which cleans-up the iv6bind structure,
 566  * closes the two sockets (if open),
 567  * and returns SOCKET_ERROR. Used in NET_BindV6 only.
 568  */
 569 
 570 #define CLOSE_SOCKETS_AND_RETURN do {   \
 571     if (fd != -1) {                     \
 572         closesocket (fd);               \
 573         fd = -1;                        \
 574     }                                   \
 575     if (ofd != -1) {                    \
 576         closesocket (ofd);              \
 577         ofd = -1;                       \
 578     }                                   \
 579     if (close_fd != -1) {               \
 580         closesocket (close_fd);         \
 581         close_fd = -1;                  \
 582     }                                   \
 583     if (close_ofd != -1) {              \
 584         closesocket (close_ofd);        \
 585         close_ofd = -1;                 \
 586     }                                   \
 587     b->ipv4_fd = b->ipv6_fd = -1;       \
 588     return SOCKET_ERROR;                \
 589 } while(0)
 590 
 591 /*
 592  * if ipv6 is available, call NET_BindV6 to bind to the required address/port.
 593  * Because the same port number may need to be reserved in both v4 and v6 space,
 594  * this may require socket(s) to be re-opened. Therefore, all of this information
 595  * is passed in and returned through the ipv6bind structure.
 596  *
 597  * If the request is to bind to a specific address, then this (by definition) means
 598  * only bind in either v4 or v6, and this is just the same as normal. ie. a single
 599  * call to bind() will suffice. The other socket is closed in this case.
 600  *
 601  * The more complicated case is when the requested address is ::0 or 0.0.0.0.
 602  *
 603  * Two further cases:
 604  * 2. If the requested port is 0 (ie. any port) then we try to bind in v4 space
 605  *    first with a wild-card port argument. We then try to bind in v6 space
 606  *    using the returned port number. If this fails, we repeat the process
 607  *    until a free port common to both spaces becomes available.
 608  *
 609  * 3. If the requested port is a specific port, then we just try to get that
 610  *    port in both spaces, and if it is not free in both, then the bind fails.
 611  *
 612  * On failure, sockets are closed and an error returned with CLOSE_SOCKETS_AND_RETURN
 613  */
 614 
 615 JNIEXPORT int JNICALL
 616 NET_BindV6(struct ipv6bind *b, jboolean exclBind) {
 617     int fd=-1, ofd=-1, rv, len;
 618     /* need to defer close until new sockets created */
 619     int close_fd=-1, close_ofd=-1;
 620     SOCKETADDRESS oaddr; /* other address to bind */
 621     int family = b->addr->sa.sa_family;
 622     int ofamily;
 623     u_short port; /* requested port parameter */
 624     u_short bound_port;
 625 
 626     if (family == AF_INET && (b->addr->sa4.sin_addr.s_addr != INADDR_ANY)) {
 627         /* bind to v4 only */
 628         int ret;
 629         ret = NET_WinBind((int)b->ipv4_fd, b->addr,
 630                           sizeof(SOCKETADDRESS), exclBind);
 631         if (ret == SOCKET_ERROR) {
 632             CLOSE_SOCKETS_AND_RETURN;
 633         }
 634         closesocket (b->ipv6_fd);
 635         b->ipv6_fd = -1;
 636         return 0;
 637     }
 638     if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->sa6.sin6_addr))) {
 639         /* bind to v6 only */
 640         int ret;
 641         ret = NET_WinBind((int)b->ipv6_fd, b->addr,
 642                           sizeof(SOCKETADDRESS), exclBind);
 643         if (ret == SOCKET_ERROR) {
 644             CLOSE_SOCKETS_AND_RETURN;
 645         }
 646         closesocket (b->ipv4_fd);
 647         b->ipv4_fd = -1;
 648         return 0;
 649     }
 650 
 651     /* We need to bind on both stacks, with the same port number */
 652 
 653     memset (&oaddr, 0, sizeof(oaddr));
 654     if (family == AF_INET) {
 655         ofamily = AF_INET6;
 656         fd = (int)b->ipv4_fd;
 657         ofd = (int)b->ipv6_fd;
 658         port = (u_short)GET_PORT (b->addr);
 659         IN6ADDR_SETANY(&oaddr.sa6);
 660         oaddr.sa6.sin6_port = port;
 661     } else {
 662         ofamily = AF_INET;
 663         ofd = (int)b->ipv4_fd;
 664         fd = (int)b->ipv6_fd;
 665         port = (u_short)GET_PORT (b->addr);
 666         oaddr.sa4.sin_family = AF_INET;
 667         oaddr.sa4.sin_port = port;
 668         oaddr.sa4.sin_addr.s_addr = INADDR_ANY;
 669     }
 670 
 671     rv = NET_WinBind(fd, b->addr, sizeof(SOCKETADDRESS), exclBind);
 672     if (rv == SOCKET_ERROR) {
 673         CLOSE_SOCKETS_AND_RETURN;
 674     }
 675 
 676     /* get the port and set it in the other address */
 677     len = sizeof(SOCKETADDRESS);
 678     if (getsockname(fd, (struct sockaddr *)b->addr, &len) == -1) {
 679         CLOSE_SOCKETS_AND_RETURN;
 680     }
 681     bound_port = GET_PORT (b->addr);
 682     SET_PORT (&oaddr, bound_port);
 683     if ((rv = NET_WinBind(ofd, &oaddr,
 684                           sizeof(SOCKETADDRESS), exclBind)) == SOCKET_ERROR) {
 685         int retries;
 686         int sotype, arglen=sizeof(sotype);
 687 
 688         /* no retries unless, the request was for any free port */
 689 
 690         if (port != 0) {
 691             CLOSE_SOCKETS_AND_RETURN;
 692         }
 693 
 694         getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen);
 695 
 696 #define SOCK_RETRIES 50
 697         /* 50 is an arbitrary limit, just to ensure that this
 698          * cannot be an endless loop. Would expect socket creation to
 699          * succeed sooner.
 700          */
 701         for (retries = 0; retries < SOCK_RETRIES; retries ++) {
 702             int len;
 703             close_fd = fd; fd = -1;
 704             close_ofd = ofd; ofd = -1;
 705             b->ipv4_fd = SOCKET_ERROR;
 706             b->ipv6_fd = SOCKET_ERROR;
 707 
 708             /* create two new sockets */
 709             fd = (int)socket (family, sotype, 0);
 710             if (fd == SOCKET_ERROR) {
 711                 CLOSE_SOCKETS_AND_RETURN;
 712             }
 713             ofd = (int)socket (ofamily, sotype, 0);
 714             if (ofd == SOCKET_ERROR) {
 715                 CLOSE_SOCKETS_AND_RETURN;
 716             }
 717 
 718             /* bind random port on first socket */
 719             SET_PORT (&oaddr, 0);
 720             rv = NET_WinBind(ofd, &oaddr, sizeof(SOCKETADDRESS), exclBind);
 721             if (rv == SOCKET_ERROR) {
 722                 CLOSE_SOCKETS_AND_RETURN;
 723             }
 724             /* close the original pair of sockets before continuing */
 725             closesocket (close_fd);
 726             closesocket (close_ofd);
 727             close_fd = close_ofd = -1;
 728 
 729             /* bind new port on second socket */
 730             len = sizeof(SOCKETADDRESS);
 731             if (getsockname(ofd, &oaddr.sa, &len) == -1) {
 732                 CLOSE_SOCKETS_AND_RETURN;
 733             }
 734             bound_port = GET_PORT (&oaddr);
 735             SET_PORT (b->addr, bound_port);
 736             rv = NET_WinBind(fd, b->addr, sizeof(SOCKETADDRESS), exclBind);
 737 
 738             if (rv != SOCKET_ERROR) {
 739                 if (family == AF_INET) {
 740                     b->ipv4_fd = fd;
 741                     b->ipv6_fd = ofd;
 742                 } else {
 743                     b->ipv4_fd = ofd;
 744                     b->ipv6_fd = fd;
 745                 }
 746                 return 0;
 747             }
 748         }
 749         CLOSE_SOCKETS_AND_RETURN;
 750     }
 751     return 0;
 752 }
 753 
 754 /**
 755  * Enables SIO_LOOPBACK_FAST_PATH
 756  */
 757 JNIEXPORT jint JNICALL
 758 NET_EnableFastTcpLoopback(int fd) {
 759     int enabled = 1;
 760     DWORD result_byte_count = -1;
 761     int result = WSAIoctl(fd,
 762                           SIO_LOOPBACK_FAST_PATH,
 763                           &enabled,
 764                           sizeof(enabled),
 765                           NULL,
 766                           0,
 767                           &result_byte_count,
 768                           NULL,
 769                           NULL);
 770     return result == SOCKET_ERROR ? WSAGetLastError() : 0;
 771 }
 772 
 773 /**
 774  * See net_util.h for documentation
 775  */
 776 JNIEXPORT int JNICALL
 777 NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,
 778                           SOCKETADDRESS *sa, int *len,
 779                           jboolean v4MappedAddress)
 780 {
 781     jint family = getInetAddress_family(env, iaObj);
 782     JNU_CHECK_EXCEPTION_RETURN(env, -1);
 783     memset((char *)sa, 0, sizeof(SOCKETADDRESS));
 784 
 785     if (ipv6_available() &&
 786         !(family == java_net_InetAddress_IPv4 &&
 787           v4MappedAddress == JNI_FALSE))
 788     {
 789         jbyte caddr[16];
 790         jint address;
 791         unsigned int scopeid = 0;
 792 
 793         if (family == java_net_InetAddress_IPv4) {
 794             // convert to IPv4-mapped address
 795             memset((char *)caddr, 0, 16);
 796             address = getInetAddress_addr(env, iaObj);
 797             JNU_CHECK_EXCEPTION_RETURN(env, -1);
 798             if (address == INADDR_ANY) {
 799                 /* we would always prefer IPv6 wildcard address
 800                  * caddr[10] = 0xff;
 801                  * caddr[11] = 0xff; */
 802             } else {
 803                 caddr[10] = 0xff;
 804                 caddr[11] = 0xff;
 805                 caddr[12] = ((address >> 24) & 0xff);
 806                 caddr[13] = ((address >> 16) & 0xff);
 807                 caddr[14] = ((address >> 8) & 0xff);
 808                 caddr[15] = (address & 0xff);
 809             }
 810         } else {
 811             getInet6Address_ipaddress(env, iaObj, (char *)caddr);
 812             scopeid = getInet6Address_scopeid(env, iaObj);
 813         }
 814         sa->sa6.sin6_port = (u_short)htons((u_short)port);
 815         memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));
 816         sa->sa6.sin6_family = AF_INET6;
 817         sa->sa6.sin6_scope_id = scopeid;
 818         if (len != NULL) {
 819             *len = sizeof(struct sockaddr_in6);
 820         }
 821     } else {
 822         jint address;
 823         if (family != java_net_InetAddress_IPv4) {
 824             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
 825             return -1;
 826         }
 827         address = getInetAddress_addr(env, iaObj);
 828         JNU_CHECK_EXCEPTION_RETURN(env, -1);
 829         sa->sa4.sin_port = htons((short)port);
 830         sa->sa4.sin_addr.s_addr = (u_long)htonl(address);
 831         sa->sa4.sin_family = AF_INET;
 832         if (len != NULL) {
 833             *len = sizeof(struct sockaddr_in);
 834         }
 835     }
 836     return 0;
 837 }
 838 
 839 int
 840 NET_IsIPv4Mapped(jbyte* caddr) {
 841     int i;
 842     for (i = 0; i < 10; i++) {
 843         if (caddr[i] != 0x00) {
 844             return 0; /* false */
 845         }
 846     }
 847 
 848     if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
 849         return 1; /* true */
 850     }
 851     return 0; /* false */
 852 }
 853 
 854 int
 855 NET_IPv4MappedToIPv4(jbyte* caddr) {
 856     return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
 857         | (caddr[15] & 0xff);
 858 }
 859 
 860 int
 861 NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
 862     int i;
 863     for (i = 0; i < 16; i++) {
 864         if (caddr1[i] != caddr2[i]) {
 865             return 0; /* false */
 866         }
 867     }
 868     return 1;
 869 }
 870 
 871 /**
 872  * Wrapper for select/poll with timeout on a single file descriptor.
 873  *
 874  * flags (defined in net_util_md.h can be any combination of
 875  * NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
 876  *
 877  * The function will return when either the socket is ready for one
 878  * of the specified operation or the timeout expired.
 879  *
 880  * It returns the time left from the timeout, or -1 if it expired.
 881  */
 882 
 883 jint
 884 NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
 885 {
 886     jlong prevTime = JVM_CurrentTimeMillis(env, 0);
 887     jint read_rv;
 888 
 889     while (1) {
 890         jlong newTime;
 891         fd_set rd, wr, ex;
 892         struct timeval t;
 893 
 894         t.tv_sec = timeout / 1000;
 895         t.tv_usec = (timeout % 1000) * 1000;
 896 
 897         FD_ZERO(&rd);
 898         FD_ZERO(&wr);
 899         FD_ZERO(&ex);
 900         if (flags & NET_WAIT_READ) {
 901           FD_SET(fd, &rd);
 902         }
 903         if (flags & NET_WAIT_WRITE) {
 904           FD_SET(fd, &wr);
 905         }
 906         if (flags & NET_WAIT_CONNECT) {
 907           FD_SET(fd, &wr);
 908           FD_SET(fd, &ex);
 909         }
 910 
 911         errno = 0;
 912         read_rv = select(fd+1, &rd, &wr, &ex, &t);
 913 
 914         newTime = JVM_CurrentTimeMillis(env, 0);
 915         timeout -= (jint)(newTime - prevTime);
 916         if (timeout <= 0) {
 917           return read_rv > 0 ? 0 : -1;
 918         }
 919         newTime = prevTime;
 920 
 921         if (read_rv > 0) {
 922           break;
 923         }
 924 
 925 
 926       } /* while */
 927 
 928     return timeout;
 929 }
 930 
 931 int NET_Socket (int domain, int type, int protocol) {
 932     SOCKET sock;
 933     sock = socket (domain, type, protocol);
 934     if (sock != INVALID_SOCKET) {
 935         SetHandleInformation((HANDLE)(uintptr_t)sock, HANDLE_FLAG_INHERIT, FALSE);
 936     }
 937     return (int)sock;
 938 }