1 /*
   2  * Copyright (c) 1997, 2019, 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 <dlfcn.h>
  26 #include <errno.h>
  27 #include <net/if.h>
  28 #include <netinet/tcp.h> // defines TCP_NODELAY
  29 #include <stdlib.h>
  30 #include <string.h>
  31 #include <sys/ioctl.h>
  32 #include <sys/time.h>
  33 
  34 #if defined(__linux__)
  35 #include <arpa/inet.h>
  36 #include <net/route.h>
  37 #include <sys/utsname.h>
  38 #endif
  39 
  40 #if defined(__solaris__)
  41 #include <inet/nd.h>
  42 #include <limits.h>
  43 #include <stropts.h>
  44 #include <sys/filio.h>
  45 #include <sys/sockio.h>
  46 #endif
  47 
  48 #if defined(MACOSX)
  49 #include <sys/sysctl.h>
  50 #endif
  51 
  52 #include "jvm.h"
  53 #include "net_util.h"
  54 
  55 #include "java_net_SocketOptions.h"
  56 #include "java_net_InetAddress.h"
  57 
  58 #if defined(__linux__) && !defined(IPV6_FLOWINFO_SEND)
  59 #define IPV6_FLOWINFO_SEND      33
  60 #endif
  61 
  62 #if defined(__solaris__) && !defined(MAXINT)
  63 #define MAXINT INT_MAX
  64 #endif
  65 
  66 /*
  67  * EXCLBIND socket options only on Solaris
  68  */
  69 #if defined(__solaris__) && !defined(TCP_EXCLBIND)
  70 #define TCP_EXCLBIND            0x21
  71 #endif
  72 #if defined(__solaris__) && !defined(UDP_EXCLBIND)
  73 #define UDP_EXCLBIND            0x0101
  74 #endif
  75 
  76 void setDefaultScopeID(JNIEnv *env, struct sockaddr *him)
  77 {
  78 #ifdef MACOSX
  79     static jclass ni_class = NULL;
  80     static jfieldID ni_defaultIndexID;
  81     if (ni_class == NULL) {
  82         jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
  83         CHECK_NULL(c);
  84         c = (*env)->NewGlobalRef(env, c);
  85         CHECK_NULL(c);
  86         ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
  87         CHECK_NULL(ni_defaultIndexID);
  88         ni_class = c;
  89     }
  90     int defaultIndex;
  91     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)him;
  92     if (sin6->sin6_family == AF_INET6 && (sin6->sin6_scope_id == 0) &&
  93         (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
  94          IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))) {
  95         defaultIndex = (*env)->GetStaticIntField(env, ni_class,
  96                                                  ni_defaultIndexID);
  97         sin6->sin6_scope_id = defaultIndex;
  98     }
  99 #endif
 100 }
 101 
 102 int getDefaultScopeID(JNIEnv *env) {
 103     int defaultIndex = 0;
 104     static jclass ni_class = NULL;
 105     static jfieldID ni_defaultIndexID;
 106     if (ni_class == NULL) {
 107         jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
 108         CHECK_NULL_RETURN(c, 0);
 109         c = (*env)->NewGlobalRef(env, c);
 110         CHECK_NULL_RETURN(c, 0);
 111         ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
 112         CHECK_NULL_RETURN(ni_defaultIndexID, 0);
 113         ni_class = c;
 114     }
 115     defaultIndex = (*env)->GetStaticIntField(env, ni_class,
 116                                              ni_defaultIndexID);
 117     return defaultIndex;
 118 }
 119 
 120 #define RESTARTABLE(_cmd, _result) do { \
 121     do { \
 122         _result = _cmd; \
 123     } while((_result == -1) && (errno == EINTR)); \
 124 } while(0)
 125 
 126 int NET_SocketAvailable(int s, int *pbytes) {
 127     int result;
 128     RESTARTABLE(ioctl(s, FIONREAD, pbytes), result);
 129     return result;
 130 }
 131 
 132 #ifdef __solaris__
 133 static int init_tcp_max_buf, init_udp_max_buf;
 134 static int tcp_max_buf;
 135 static int udp_max_buf;
 136 static int useExclBind = 0;
 137 
 138 /*
 139  * Get the specified parameter from the specified driver. The value
 140  * of the parameter is assumed to be an 'int'. If the parameter
 141  * cannot be obtained return -1
 142  */
 143 int net_getParam(char *driver, char *param)
 144 {
 145     struct strioctl stri;
 146     char buf [64];
 147     int s;
 148     int value;
 149 
 150     s = open (driver, O_RDWR);
 151     if (s < 0) {
 152         return -1;
 153     }
 154     strncpy (buf, param, sizeof(buf));
 155     stri.ic_cmd = ND_GET;
 156     stri.ic_timout = 0;
 157     stri.ic_dp = buf;
 158     stri.ic_len = sizeof(buf);
 159     if (ioctl (s, I_STR, &stri) < 0) {
 160         value = -1;
 161     } else {
 162         value = atoi(buf);
 163     }
 164     close (s);
 165     return value;
 166 }
 167 
 168 /*
 169  * Iterative way to find the max value that SO_SNDBUF or SO_RCVBUF
 170  * for Solaris versions that do not support the ioctl() in net_getParam().
 171  * Ugly, but only called once (for each sotype).
 172  *
 173  * As an optimization, we make a guess using the default values for Solaris
 174  * assuming they haven't been modified with ndd.
 175  */
 176 
 177 #define MAX_TCP_GUESS 1024 * 1024
 178 #define MAX_UDP_GUESS 2 * 1024 * 1024
 179 
 180 #define FAIL_IF_NOT_ENOBUFS if (errno != ENOBUFS) return -1
 181 
 182 static int findMaxBuf(int fd, int opt, int sotype) {
 183     int a = 0;
 184     int b = MAXINT;
 185     int initial_guess;
 186     int limit = -1;
 187 
 188     if (sotype == SOCK_DGRAM) {
 189         initial_guess = MAX_UDP_GUESS;
 190     } else {
 191         initial_guess = MAX_TCP_GUESS;
 192     }
 193 
 194     if (setsockopt(fd, SOL_SOCKET, opt, &initial_guess, sizeof(int)) == 0) {
 195         initial_guess++;
 196         if (setsockopt(fd, SOL_SOCKET, opt, &initial_guess,sizeof(int)) < 0) {
 197             FAIL_IF_NOT_ENOBUFS;
 198             return initial_guess - 1;
 199         }
 200         a = initial_guess;
 201     } else {
 202         FAIL_IF_NOT_ENOBUFS;
 203         b = initial_guess - 1;
 204     }
 205     do {
 206         int mid = a + (b-a)/2;
 207         if (setsockopt(fd, SOL_SOCKET, opt, &mid, sizeof(int)) == 0) {
 208             limit = mid;
 209             a = mid + 1;
 210         } else {
 211             FAIL_IF_NOT_ENOBUFS;
 212             b = mid - 1;
 213         }
 214     } while (b >= a);
 215 
 216     return limit;
 217 }
 218 #endif
 219 
 220 #ifdef __linux__
 221 static int vinit = 0;
 222 static int kernelV24 = 0;
 223 static int vinit24 = 0;
 224 
 225 int kernelIsV24 () {
 226     if (!vinit24) {
 227         struct utsname sysinfo;
 228         if (uname(&sysinfo) == 0) {
 229             sysinfo.release[3] = '\0';
 230             if (strcmp(sysinfo.release, "2.4") == 0) {
 231                 kernelV24 = JNI_TRUE;
 232             }
 233         }
 234         vinit24 = 1;
 235     }
 236     return kernelV24;
 237 }
 238 #endif
 239 
 240 void
 241 NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
 242                    const char *defaultDetail) {
 243     JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);
 244 }
 245 
 246 void
 247 NET_ThrowCurrent(JNIEnv *env, char *msg) {
 248     NET_ThrowNew(env, errno, msg);
 249 }
 250 
 251 void
 252 NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {
 253     char fullMsg[512];
 254     if (!msg) {
 255         msg = "no further information";
 256     }
 257     switch(errorNumber) {
 258     case EBADF:
 259         jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);
 260         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
 261         break;
 262     case EINTR:
 263         JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException", msg);
 264         break;
 265     default:
 266         errno = errorNumber;
 267         JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", msg);
 268         break;
 269     }
 270 }
 271 
 272 
 273 jfieldID
 274 NET_GetFileDescriptorID(JNIEnv *env)
 275 {
 276     jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
 277     CHECK_NULL_RETURN(cls, NULL);
 278     return (*env)->GetFieldID(env, cls, "fd", "I");
 279 }
 280 
 281 jint  IPv4_supported()
 282 {
 283     return JNI_FALSE;
 284 }
 285 
 286 #if defined(DONT_ENABLE_IPV6)
 287 jint  IPv6_supported()
 288 {
 289     return JNI_FALSE;
 290 }
 291 
 292 #else /* !DONT_ENABLE_IPV6 */
 293 
 294 jint  IPv6_supported()
 295 {
 296     int fd;
 297     void *ipv6_fn;
 298     SOCKETADDRESS sa;
 299     socklen_t sa_len = sizeof(SOCKETADDRESS);
 300 
 301     fd = socket(AF_INET6, SOCK_STREAM, 0) ;
 302     if (fd < 0) {
 303         /*
 304          *  TODO: We really cant tell since it may be an unrelated error
 305          *  for now we will assume that AF_INET6 is not available
 306          */
 307         return JNI_FALSE;
 308     }
 309 
 310     /*
 311      * If fd 0 is a socket it means we may have been launched from inetd or
 312      * xinetd. If it's a socket then check the family - if it's an
 313      * IPv4 socket then we need to disable IPv6.
 314      */
 315     if (getsockname(0, &sa.sa, &sa_len) == 0) {
 316         if (sa.sa.sa_family == AF_INET) {
 317             close(fd);
 318             return JNI_FALSE;
 319         }
 320     }
 321 
 322     /**
 323      * Linux - check if any interface has an IPv6 address.
 324      * Don't need to parse the line - we just need an indication.
 325      */
 326 #ifdef __linux__
 327     {
 328         FILE *fP = fopen("/proc/net/if_inet6", "r");
 329         char buf[255];
 330         char *bufP;
 331 
 332         if (fP == NULL) {
 333             close(fd);
 334             return JNI_FALSE;
 335         }
 336         bufP = fgets(buf, sizeof(buf), fP);
 337         fclose(fP);
 338         if (bufP == NULL) {
 339             close(fd);
 340             return JNI_FALSE;
 341         }
 342     }
 343 #endif
 344 
 345     /**
 346      * On Solaris 8 it's possible to create INET6 sockets even
 347      * though IPv6 is not enabled on all interfaces. Thus we
 348      * query the number of IPv6 addresses to verify that IPv6
 349      * has been configured on at least one interface.
 350      *
 351      * On Linux it doesn't matter - if IPv6 is built-in the
 352      * kernel then IPv6 addresses will be bound automatically
 353      * to all interfaces.
 354      */
 355 #ifdef __solaris__
 356 
 357 #ifdef SIOCGLIFNUM
 358     {
 359         struct lifnum numifs;
 360 
 361         numifs.lifn_family = AF_INET6;
 362         numifs.lifn_flags = 0;
 363         if (ioctl(fd, SIOCGLIFNUM, (char *)&numifs) < 0) {
 364             /**
 365              * SIOCGLIFNUM failed - assume IPv6 not configured
 366              */
 367             close(fd);
 368             return JNI_FALSE;
 369         }
 370         /**
 371          * If no IPv6 addresses then return false. If count > 0
 372          * it's possible that all IPv6 addresses are "down" but
 373          * that's okay as they may be brought "up" while the
 374          * VM is running.
 375          */
 376         if (numifs.lifn_count == 0) {
 377             close(fd);
 378             return JNI_FALSE;
 379         }
 380     }
 381 #else
 382     /* SIOCGLIFNUM not defined in build environment ??? */
 383     close(fd);
 384     return JNI_FALSE;
 385 #endif
 386 
 387 #endif /* __solaris */
 388 
 389     /*
 390      *  OK we may have the stack available in the kernel,
 391      *  we should also check if the APIs are available.
 392      */
 393     ipv6_fn = JVM_FindLibraryEntry(RTLD_DEFAULT, "inet_pton");
 394     close(fd);
 395     if (ipv6_fn == NULL ) {
 396         return JNI_FALSE;
 397     } else {
 398         return JNI_TRUE;
 399     }
 400 }
 401 #endif /* DONT_ENABLE_IPV6 */
 402 
 403 jint reuseport_supported()
 404 {
 405     /* Do a simple dummy call, and try to figure out from that */
 406     int one = 1;
 407     int rv, s;
 408     s = socket(PF_INET, SOCK_STREAM, 0);
 409     if (s < 0) {
 410         return JNI_FALSE;
 411     }
 412     rv = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void *)&one, sizeof(one));
 413     if (rv != 0) {
 414         rv = JNI_FALSE;
 415     } else {
 416         rv = JNI_TRUE;
 417     }
 418     close(s);
 419     return rv;
 420 }
 421 
 422 void NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv *env,
 423                                                const char* hostname,
 424                                                int gai_error)
 425 {
 426     int size;
 427     char *buf;
 428     const char *format = "%s: %s";
 429     const char *error_string = gai_strerror(gai_error);
 430     if (error_string == NULL)
 431         error_string = "unknown error";
 432 
 433     size = strlen(format) + strlen(hostname) + strlen(error_string) + 2;
 434     buf = (char *) malloc(size);
 435     if (buf) {
 436         jstring s;
 437         sprintf(buf, format, hostname, error_string);
 438         s = JNU_NewStringPlatform(env, buf);
 439         if (s != NULL) {
 440             jobject x = JNU_NewObjectByName(env,
 441                                             "java/net/UnknownHostException",
 442                                             "(Ljava/lang/String;)V", s);
 443             if (x != NULL)
 444                 (*env)->Throw(env, x);
 445         }
 446         free(buf);
 447     }
 448 }
 449 
 450 #if defined(__linux__)
 451 
 452 /* following code creates a list of addresses from the kernel
 453  * routing table that are routed via the loopback address.
 454  * We check all destination addresses against this table
 455  * and override the scope_id field to use the relevant value for "lo"
 456  * in order to work-around the Linux bug that prevents packets destined
 457  * for certain local addresses from being sent via a physical interface.
 458  */
 459 
 460 struct loopback_route {
 461     struct in6_addr addr; /* destination address */
 462     int plen; /* prefix length */
 463 };
 464 
 465 static struct loopback_route *loRoutes = 0;
 466 static int nRoutes = 0; /* number of routes */
 467 static int loRoutes_size = 16; /* initial size */
 468 static int lo_scope_id = 0;
 469 
 470 static void initLoopbackRoutes();
 471 
 472 void printAddr (struct in6_addr *addr) {
 473     int i;
 474     for (i=0; i<16; i++) {
 475         printf ("%02x", addr->s6_addr[i]);
 476     }
 477     printf ("\n");
 478 }
 479 
 480 static jboolean needsLoopbackRoute (struct in6_addr* dest_addr) {
 481     int byte_count;
 482     int extra_bits, i;
 483     struct loopback_route *ptr;
 484 
 485     if (loRoutes == 0) {
 486         initLoopbackRoutes();
 487     }
 488 
 489     for (ptr = loRoutes, i=0; i<nRoutes; i++, ptr++) {
 490         struct in6_addr *target_addr=&ptr->addr;
 491         int dest_plen = ptr->plen;
 492         byte_count = dest_plen >> 3;
 493         extra_bits = dest_plen & 0x3;
 494 
 495         if (byte_count > 0) {
 496             if (memcmp(target_addr, dest_addr, byte_count)) {
 497                 continue;  /* no match */
 498             }
 499         }
 500 
 501         if (extra_bits > 0) {
 502             unsigned char c1 = ((unsigned char *)target_addr)[byte_count];
 503             unsigned char c2 = ((unsigned char *)&dest_addr)[byte_count];
 504             unsigned char mask = 0xff << (8 - extra_bits);
 505             if ((c1 & mask) != (c2 & mask)) {
 506                 continue;
 507             }
 508         }
 509         return JNI_TRUE;
 510     }
 511     return JNI_FALSE;
 512 }
 513 
 514 
 515 static void initLoopbackRoutes() {
 516     FILE *f;
 517     char srcp[8][5];
 518     char hopp[8][5];
 519     int dest_plen, src_plen, use, refcnt, metric;
 520     unsigned long flags;
 521     char dest_str[40];
 522     struct in6_addr dest_addr;
 523     char device[16];
 524     struct loopback_route *loRoutesTemp;
 525 
 526     if (loRoutes != 0) {
 527         free (loRoutes);
 528     }
 529     loRoutes = calloc (loRoutes_size, sizeof(struct loopback_route));
 530     if (loRoutes == 0) {
 531         return;
 532     }
 533     /*
 534      * Scan /proc/net/ipv6_route looking for a matching
 535      * route.
 536      */
 537     if ((f = fopen("/proc/net/ipv6_route", "r")) == NULL) {
 538         return ;
 539     }
 540     while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
 541                      "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
 542                      "%4s%4s%4s%4s%4s%4s%4s%4s "
 543                      "%08x %08x %08x %08lx %8s",
 544                      dest_str, &dest_str[5], &dest_str[10], &dest_str[15],
 545                      &dest_str[20], &dest_str[25], &dest_str[30], &dest_str[35],
 546                      &dest_plen,
 547                      srcp[0], srcp[1], srcp[2], srcp[3],
 548                      srcp[4], srcp[5], srcp[6], srcp[7],
 549                      &src_plen,
 550                      hopp[0], hopp[1], hopp[2], hopp[3],
 551                      hopp[4], hopp[5], hopp[6], hopp[7],
 552                      &metric, &use, &refcnt, &flags, device) == 31) {
 553 
 554         /*
 555          * Some routes should be ignored
 556          */
 557         if ( (dest_plen < 0 || dest_plen > 128)  ||
 558              (src_plen != 0) ||
 559              (flags & (RTF_POLICY | RTF_FLOW)) ||
 560              ((flags & RTF_REJECT) && dest_plen == 0) ) {
 561             continue;
 562         }
 563 
 564         /*
 565          * Convert the destination address
 566          */
 567         dest_str[4] = ':';
 568         dest_str[9] = ':';
 569         dest_str[14] = ':';
 570         dest_str[19] = ':';
 571         dest_str[24] = ':';
 572         dest_str[29] = ':';
 573         dest_str[34] = ':';
 574         dest_str[39] = '\0';
 575 
 576         if (inet_pton(AF_INET6, dest_str, &dest_addr) < 0) {
 577             /* not an Ipv6 address */
 578             continue;
 579         }
 580         if (strcmp(device, "lo") != 0) {
 581             /* Not a loopback route */
 582             continue;
 583         } else {
 584             if (nRoutes == loRoutes_size) {
 585                 loRoutesTemp = realloc (loRoutes, loRoutes_size *
 586                                         sizeof (struct loopback_route) * 2);
 587 
 588                 if (loRoutesTemp == 0) {
 589                     free(loRoutes);
 590                     loRoutes = NULL;
 591                     nRoutes = 0;
 592                     fclose (f);
 593                     return;
 594                 }
 595                 loRoutes=loRoutesTemp;
 596                 loRoutes_size *= 2;
 597             }
 598             memcpy (&loRoutes[nRoutes].addr,&dest_addr,sizeof(struct in6_addr));
 599             loRoutes[nRoutes].plen = dest_plen;
 600             nRoutes ++;
 601         }
 602     }
 603 
 604     fclose (f);
 605     {
 606         /* now find the scope_id for "lo" */
 607 
 608         char devname[21];
 609         char addr6p[8][5];
 610         int plen, scope, dad_status, if_idx;
 611 
 612         if ((f = fopen("/proc/net/if_inet6", "r")) != NULL) {
 613             while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
 614                       addr6p[0], addr6p[1], addr6p[2], addr6p[3],
 615                       addr6p[4], addr6p[5], addr6p[6], addr6p[7],
 616                   &if_idx, &plen, &scope, &dad_status, devname) == 13) {
 617 
 618                 if (strcmp(devname, "lo") == 0) {
 619                     /*
 620                      * Found - so just return the index
 621                      */
 622                     fclose(f);
 623                     lo_scope_id = if_idx;
 624                     return;
 625                 }
 626             }
 627             fclose(f);
 628         }
 629     }
 630 }
 631 
 632 /*
 633  * Following is used for binding to local addresses. Equivalent
 634  * to code above, for bind().
 635  */
 636 
 637 struct localinterface {
 638     int index;
 639     char localaddr [16];
 640 };
 641 
 642 static struct localinterface *localifs = 0;
 643 static int localifsSize = 0;    /* size of array */
 644 static int nifs = 0;            /* number of entries used in array */
 645 
 646 /* not thread safe: make sure called once from one thread */
 647 
 648 static void initLocalIfs () {
 649     FILE *f;
 650     unsigned char staddr [16];
 651     char ifname [33];
 652     struct localinterface *lif=0;
 653     struct localinterface *localifsTemp;
 654     int index, x1, x2, x3;
 655     unsigned int u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,ua,ub,uc,ud,ue,uf;
 656 
 657     if ((f = fopen("/proc/net/if_inet6", "r")) == NULL) {
 658         return ;
 659     }
 660     while (fscanf (f, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x "
 661                 "%d %x %x %x %32s",&u0,&u1,&u2,&u3,&u4,&u5,&u6,&u7,
 662                 &u8,&u9,&ua,&ub,&uc,&ud,&ue,&uf,
 663                 &index, &x1, &x2, &x3, ifname) == 21) {
 664         staddr[0] = (unsigned char)u0;
 665         staddr[1] = (unsigned char)u1;
 666         staddr[2] = (unsigned char)u2;
 667         staddr[3] = (unsigned char)u3;
 668         staddr[4] = (unsigned char)u4;
 669         staddr[5] = (unsigned char)u5;
 670         staddr[6] = (unsigned char)u6;
 671         staddr[7] = (unsigned char)u7;
 672         staddr[8] = (unsigned char)u8;
 673         staddr[9] = (unsigned char)u9;
 674         staddr[10] = (unsigned char)ua;
 675         staddr[11] = (unsigned char)ub;
 676         staddr[12] = (unsigned char)uc;
 677         staddr[13] = (unsigned char)ud;
 678         staddr[14] = (unsigned char)ue;
 679         staddr[15] = (unsigned char)uf;
 680         nifs ++;
 681         if (nifs > localifsSize) {
 682             localifsTemp = (struct localinterface *) realloc(
 683                         localifs, sizeof (struct localinterface)* (localifsSize+5));
 684             if (localifsTemp == 0) {
 685                 free(localifs);
 686                 localifs = 0;
 687                 localifsSize = 0;
 688                 nifs = 0;
 689                 fclose(f);
 690                 return;
 691             }
 692             localifs = localifsTemp;
 693             lif = localifs + localifsSize;
 694             localifsSize += 5;
 695         } else {
 696             lif ++;
 697         }
 698         memcpy (lif->localaddr, staddr, 16);
 699         lif->index = index;
 700     }
 701     fclose (f);
 702 }
 703 
 704 /* return the scope_id (interface index) of the
 705  * interface corresponding to the given address
 706  * returns 0 if no match found
 707  */
 708 
 709 static int getLocalScopeID (char *addr) {
 710     struct localinterface *lif;
 711     int i;
 712     if (localifs == 0) {
 713         initLocalIfs();
 714     }
 715     for (i=0, lif=localifs; i<nifs; i++, lif++) {
 716         if (memcmp (addr, lif->localaddr, 16) == 0) {
 717             return lif->index;
 718         }
 719     }
 720     return 0;
 721 }
 722 
 723 void platformInit () {
 724     initLoopbackRoutes();
 725     initLocalIfs();
 726 }
 727 
 728 #elif defined(_AIX)
 729 
 730 /* Initialize stubs for blocking I/O workarounds (see src/solaris/native/java/net/linux_close.c) */
 731 extern void aix_close_init();
 732 
 733 void platformInit () {
 734     aix_close_init();
 735 }
 736 
 737 #else
 738 
 739 void platformInit () {}
 740 
 741 #endif
 742 
 743 void parseExclusiveBindProperty(JNIEnv *env) {
 744 #ifdef __solaris__
 745     jstring s, flagSet;
 746     jclass iCls;
 747     jmethodID mid;
 748 
 749     s = (*env)->NewStringUTF(env, "sun.net.useExclusiveBind");
 750     CHECK_NULL(s);
 751     iCls = (*env)->FindClass(env, "java/lang/System");
 752     CHECK_NULL(iCls);
 753     mid = (*env)->GetStaticMethodID(env, iCls, "getProperty",
 754                 "(Ljava/lang/String;)Ljava/lang/String;");
 755     CHECK_NULL(mid);
 756     flagSet = (*env)->CallStaticObjectMethod(env, iCls, mid, s);
 757     if (flagSet != NULL) {
 758         useExclBind = 1;
 759     }
 760 #endif
 761 }
 762 
 763 JNIEXPORT jint JNICALL
 764 NET_EnableFastTcpLoopback(int fd) {
 765     return 0;
 766 }
 767 
 768 /**
 769  * See net_util.h for documentation
 770  */
 771 JNIEXPORT int JNICALL
 772 NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,
 773                           SOCKETADDRESS *sa, int *len,
 774                           jboolean v4MappedAddress)
 775 {
 776     jint family = getInetAddress_family(env, iaObj);
 777     JNU_CHECK_EXCEPTION_RETURN(env, -1);
 778     memset((char *)sa, 0, sizeof(SOCKETADDRESS));
 779 
 780     if (ipv6_available() &&
 781         !(family == java_net_InetAddress_IPv4 &&
 782           v4MappedAddress == JNI_FALSE))
 783     {
 784         jbyte caddr[16];
 785         jint address;
 786 
 787         if (family == java_net_InetAddress_IPv4) {
 788             // convert to IPv4-mapped address
 789             memset((char *)caddr, 0, 16);
 790             address = getInetAddress_addr(env, iaObj);
 791             JNU_CHECK_EXCEPTION_RETURN(env, -1);
 792             if (address == INADDR_ANY) {
 793                 /* we would always prefer IPv6 wildcard address
 794                  * caddr[10] = 0xff;
 795                  * caddr[11] = 0xff; */
 796             } else {
 797                 caddr[10] = 0xff;
 798                 caddr[11] = 0xff;
 799                 caddr[12] = ((address >> 24) & 0xff);
 800                 caddr[13] = ((address >> 16) & 0xff);
 801                 caddr[14] = ((address >> 8) & 0xff);
 802                 caddr[15] = (address & 0xff);
 803             }
 804         } else {
 805             getInet6Address_ipaddress(env, iaObj, (char *)caddr);
 806         }
 807         sa->sa6.sin6_port = htons(port);
 808         memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));
 809         sa->sa6.sin6_family = AF_INET6;
 810         if (len != NULL) {
 811             *len = sizeof(struct sockaddr_in6);
 812         }
 813 
 814 #ifdef __linux__
 815         /*
 816          * On Linux if we are connecting to a link-local address
 817          * we need to specify the interface in the scope_id (2.4 kernel only)
 818          *
 819          * If the scope was cached then we use the cached value. If not cached but
 820          * specified in the Inet6Address we use that, but we first check if the
 821          * address needs to be routed via the loopback interface. In this case,
 822          * we override the specified value with that of the loopback interface.
 823          * If no cached value exists and no value was specified by user, then
 824          * we try to determine a value from the routing table. In all these
 825          * cases the used value is cached for further use.
 826          */
 827         if (IN6_IS_ADDR_LINKLOCAL(&sa->sa6.sin6_addr)) {
 828             unsigned int cached_scope_id = 0, scope_id = 0;
 829 
 830             if (ia6_cachedscopeidID) {
 831                 cached_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);
 832                 /* if cached value exists then use it. Otherwise, check
 833                  * if scope is set in the address.
 834                  */
 835                 if (!cached_scope_id) {
 836                     if (ia6_scopeidID) {
 837                         scope_id = getInet6Address_scopeid(env, iaObj);
 838                     }
 839                     if (scope_id != 0) {
 840                         /* check user-specified value for loopback case
 841                          * that needs to be overridden
 842                          */
 843                         if (kernelIsV24() && needsLoopbackRoute(&sa->sa6.sin6_addr)) {
 844                             cached_scope_id = lo_scope_id;
 845                             (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
 846                         }
 847                     } else {
 848                         /*
 849                          * Otherwise consult the IPv6 routing tables to
 850                          * try determine the appropriate interface.
 851                          */
 852                         if (kernelIsV24()) {
 853                             cached_scope_id = getDefaultIPv6Interface(&sa->sa6.sin6_addr);
 854                         } else {
 855                             cached_scope_id = getLocalScopeID((char *)&(sa->sa6.sin6_addr));
 856                             if (cached_scope_id == 0) {
 857                                 cached_scope_id = getDefaultIPv6Interface(&sa->sa6.sin6_addr);
 858                             }
 859                         }
 860                         (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
 861                     }
 862                 }
 863             }
 864 
 865             /*
 866              * If we have a scope_id use the extended form
 867              * of sockaddr_in6.
 868              */
 869             sa->sa6.sin6_scope_id = cached_scope_id == 0 ? scope_id : cached_scope_id;
 870         }
 871 #else
 872         /* handle scope_id */
 873         if (family != java_net_InetAddress_IPv4) {
 874             if (ia6_scopeidID) {
 875                 sa->sa6.sin6_scope_id = getInet6Address_scopeid(env, iaObj);
 876             }
 877         }
 878 #endif
 879     } else {
 880         jint address;
 881         if (family != java_net_InetAddress_IPv4) {
 882             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
 883             return -1;
 884         }
 885         address = getInetAddress_addr(env, iaObj);
 886         JNU_CHECK_EXCEPTION_RETURN(env, -1);
 887         sa->sa4.sin_port = htons(port);
 888         sa->sa4.sin_addr.s_addr = htonl(address);
 889         sa->sa4.sin_family = AF_INET;
 890         if (len != NULL) {
 891             *len = sizeof(struct sockaddr_in);
 892         }
 893     }
 894     return 0;
 895 }
 896 
 897 void
 898 NET_SetTrafficClass(SOCKETADDRESS *sa, int trafficClass) {
 899     if (sa->sa.sa_family == AF_INET6) {
 900         sa->sa6.sin6_flowinfo = htonl((trafficClass & 0xff) << 20);
 901     }
 902 }
 903 
 904 int
 905 NET_IsIPv4Mapped(jbyte* caddr) {
 906     int i;
 907     for (i = 0; i < 10; i++) {
 908         if (caddr[i] != 0x00) {
 909             return 0; /* false */
 910         }
 911     }
 912 
 913     if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
 914         return 1; /* true */
 915     }
 916     return 0; /* false */
 917 }
 918 
 919 int
 920 NET_IPv4MappedToIPv4(jbyte* caddr) {
 921     return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
 922         | (caddr[15] & 0xff);
 923 }
 924 
 925 int
 926 NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
 927     int i;
 928     for (i = 0; i < 16; i++) {
 929         if (caddr1[i] != caddr2[i]) {
 930             return 0; /* false */
 931         }
 932     }
 933     return 1;
 934 }
 935 
 936 int NET_IsZeroAddr(jbyte* caddr) {
 937     int i;
 938     for (i = 0; i < 16; i++) {
 939         if (caddr[i] != 0) {
 940             return 0;
 941         }
 942     }
 943     return 1;
 944 }
 945 
 946 /*
 947  * Map the Java level socket option to the platform specific
 948  * level and option name.
 949  */
 950 int
 951 NET_MapSocketOption(jint cmd, int *level, int *optname) {
 952     static struct {
 953         jint cmd;
 954         int level;
 955         int optname;
 956     } const opts[] = {
 957         { java_net_SocketOptions_TCP_NODELAY,           IPPROTO_TCP,    TCP_NODELAY },
 958         { java_net_SocketOptions_SO_OOBINLINE,          SOL_SOCKET,     SO_OOBINLINE },
 959         { java_net_SocketOptions_SO_LINGER,             SOL_SOCKET,     SO_LINGER },
 960         { java_net_SocketOptions_SO_SNDBUF,             SOL_SOCKET,     SO_SNDBUF },
 961         { java_net_SocketOptions_SO_RCVBUF,             SOL_SOCKET,     SO_RCVBUF },
 962         { java_net_SocketOptions_SO_KEEPALIVE,          SOL_SOCKET,     SO_KEEPALIVE },
 963         { java_net_SocketOptions_SO_REUSEADDR,          SOL_SOCKET,     SO_REUSEADDR },
 964         { java_net_SocketOptions_SO_REUSEPORT,          SOL_SOCKET,     SO_REUSEPORT },
 965         { java_net_SocketOptions_SO_BROADCAST,          SOL_SOCKET,     SO_BROADCAST },
 966         { java_net_SocketOptions_IP_TOS,                IPPROTO_IP,     IP_TOS },
 967         { java_net_SocketOptions_IP_MULTICAST_IF,       IPPROTO_IP,     IP_MULTICAST_IF },
 968         { java_net_SocketOptions_IP_MULTICAST_IF2,      IPPROTO_IP,     IP_MULTICAST_IF },
 969         { java_net_SocketOptions_IP_MULTICAST_LOOP,     IPPROTO_IP,     IP_MULTICAST_LOOP },
 970     };
 971 
 972     int i;
 973 
 974     if (ipv6_available()) {
 975         switch (cmd) {
 976             // Different multicast options if IPv6 is enabled
 977             case java_net_SocketOptions_IP_MULTICAST_IF:
 978             case java_net_SocketOptions_IP_MULTICAST_IF2:
 979                 *level = IPPROTO_IPV6;
 980                 *optname = IPV6_MULTICAST_IF;
 981                 return 0;
 982 
 983             case java_net_SocketOptions_IP_MULTICAST_LOOP:
 984                 *level = IPPROTO_IPV6;
 985                 *optname = IPV6_MULTICAST_LOOP;
 986                 return 0;
 987 #if (defined(__solaris__) || defined(MACOSX))
 988             // Map IP_TOS request to IPV6_TCLASS
 989             case java_net_SocketOptions_IP_TOS:
 990                 *level = IPPROTO_IPV6;
 991                 *optname = IPV6_TCLASS;
 992                 return 0;
 993 #endif
 994         }
 995     }
 996 
 997     /*
 998      * Map the Java level option to the native level
 999      */
1000     for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
1001         if (cmd == opts[i].cmd) {
1002             *level = opts[i].level;
1003             *optname = opts[i].optname;
1004             return 0;
1005         }
1006     }
1007 
1008     /* not found */
1009     return -1;
1010 }
1011 
1012 /*
1013  * Determine the default interface for an IPv6 address.
1014  *
1015  * 1. Scans /proc/net/ipv6_route for a matching route
1016  *    (eg: fe80::/10 or a route for the specific address).
1017  *    This will tell us the interface to use (eg: "eth0").
1018  *
1019  * 2. Lookup /proc/net/if_inet6 to map the interface
1020  *    name to an interface index.
1021  *
1022  * Returns :-
1023  *      -1 if error
1024  *       0 if no matching interface
1025  *      >1 interface index to use for the link-local address.
1026  */
1027 #if defined(__linux__)
1028 int getDefaultIPv6Interface(struct in6_addr *target_addr) {
1029     FILE *f;
1030     char srcp[8][5];
1031     char hopp[8][5];
1032     int dest_plen, src_plen, use, refcnt, metric;
1033     unsigned long flags;
1034     char dest_str[40];
1035     struct in6_addr dest_addr;
1036     char device[16];
1037     jboolean match = JNI_FALSE;
1038 
1039     /*
1040      * Scan /proc/net/ipv6_route looking for a matching
1041      * route.
1042      */
1043     if ((f = fopen("/proc/net/ipv6_route", "r")) == NULL) {
1044         return -1;
1045     }
1046     while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
1047                      "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
1048                      "%4s%4s%4s%4s%4s%4s%4s%4s "
1049                      "%08x %08x %08x %08lx %8s",
1050                      dest_str, &dest_str[5], &dest_str[10], &dest_str[15],
1051                      &dest_str[20], &dest_str[25], &dest_str[30], &dest_str[35],
1052                      &dest_plen,
1053                      srcp[0], srcp[1], srcp[2], srcp[3],
1054                      srcp[4], srcp[5], srcp[6], srcp[7],
1055                      &src_plen,
1056                      hopp[0], hopp[1], hopp[2], hopp[3],
1057                      hopp[4], hopp[5], hopp[6], hopp[7],
1058                      &metric, &use, &refcnt, &flags, device) == 31) {
1059 
1060         /*
1061          * Some routes should be ignored
1062          */
1063         if ( (dest_plen < 0 || dest_plen > 128)  ||
1064              (src_plen != 0) ||
1065              (flags & (RTF_POLICY | RTF_FLOW)) ||
1066              ((flags & RTF_REJECT) && dest_plen == 0) ) {
1067             continue;
1068         }
1069 
1070         /*
1071          * Convert the destination address
1072          */
1073         dest_str[4] = ':';
1074         dest_str[9] = ':';
1075         dest_str[14] = ':';
1076         dest_str[19] = ':';
1077         dest_str[24] = ':';
1078         dest_str[29] = ':';
1079         dest_str[34] = ':';
1080         dest_str[39] = '\0';
1081 
1082         if (inet_pton(AF_INET6, dest_str, &dest_addr) < 0) {
1083             /* not an Ipv6 address */
1084             continue;
1085         } else {
1086             /*
1087              * The prefix len (dest_plen) indicates the number of bits we
1088              * need to match on.
1089              *
1090              * dest_plen / 8    => number of bytes to match
1091              * dest_plen % 8    => number of additional bits to match
1092              *
1093              * eg: fe80::/10 => match 1 byte + 2 additional bits in the
1094              *                  next byte.
1095              */
1096             int byte_count = dest_plen >> 3;
1097             int extra_bits = dest_plen & 0x3;
1098 
1099             if (byte_count > 0) {
1100                 if (memcmp(target_addr, &dest_addr, byte_count)) {
1101                     continue;  /* no match */
1102                 }
1103             }
1104 
1105             if (extra_bits > 0) {
1106                 unsigned char c1 = ((unsigned char *)target_addr)[byte_count];
1107                 unsigned char c2 = ((unsigned char *)&dest_addr)[byte_count];
1108                 unsigned char mask = 0xff << (8 - extra_bits);
1109                 if ((c1 & mask) != (c2 & mask)) {
1110                     continue;
1111                 }
1112             }
1113 
1114             /*
1115              * We have a match
1116              */
1117             match = JNI_TRUE;
1118             break;
1119         }
1120     }
1121     fclose(f);
1122 
1123     /*
1124      * If there's a match then we lookup the interface
1125      * index.
1126      */
1127     if (match) {
1128         char devname[21];
1129         char addr6p[8][5];
1130         int plen, scope, dad_status, if_idx;
1131 
1132         if ((f = fopen("/proc/net/if_inet6", "r")) != NULL) {
1133             while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
1134                       addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1135                       addr6p[4], addr6p[5], addr6p[6], addr6p[7],
1136                   &if_idx, &plen, &scope, &dad_status, devname) == 13) {
1137 
1138                 if (strcmp(devname, device) == 0) {
1139                     /*
1140                      * Found - so just return the index
1141                      */
1142                     fclose(f);
1143                     return if_idx;
1144                 }
1145             }
1146             fclose(f);
1147         } else {
1148             /*
1149              * Couldn't open /proc/net/if_inet6
1150              */
1151             return -1;
1152         }
1153     }
1154 
1155     /*
1156      * If we get here it means we didn't there wasn't any
1157      * route or we couldn't get the index of the interface.
1158      */
1159     return 0;
1160 }
1161 #endif
1162 
1163 
1164 /*
1165  * Wrapper for getsockopt system routine - does any necessary
1166  * pre/post processing to deal with OS specific oddities :-
1167  *
1168  * On Linux the SO_SNDBUF/SO_RCVBUF values must be post-processed
1169  * to compensate for an incorrect value returned by the kernel.
1170  */
1171 int
1172 NET_GetSockOpt(int fd, int level, int opt, void *result,
1173                int *len)
1174 {
1175     int rv;
1176     socklen_t socklen = *len;
1177 
1178     rv = getsockopt(fd, level, opt, result, &socklen);
1179     *len = socklen;
1180 
1181     if (rv < 0) {
1182         return rv;
1183     }
1184 
1185 #ifdef __linux__
1186     /*
1187      * On Linux SO_SNDBUF/SO_RCVBUF aren't symmetric. This
1188      * stems from additional socket structures in the send
1189      * and receive buffers.
1190      */
1191     if ((level == SOL_SOCKET) && ((opt == SO_SNDBUF)
1192                                   || (opt == SO_RCVBUF))) {
1193         int n = *((int *)result);
1194         n /= 2;
1195         *((int *)result) = n;
1196     }
1197 #endif
1198 
1199 /* Workaround for Mac OS treating linger value as
1200  *  signed integer
1201  */
1202 #ifdef MACOSX
1203     if (level == SOL_SOCKET && opt == SO_LINGER) {
1204         struct linger* to_cast = (struct linger*)result;
1205         to_cast->l_linger = (unsigned short)to_cast->l_linger;
1206     }
1207 #endif
1208     return rv;
1209 }
1210 
1211 /*
1212  * Wrapper for setsockopt system routine - performs any
1213  * necessary pre/post processing to deal with OS specific
1214  * issue :-
1215  *
1216  * On Solaris need to limit the suggested value for SO_SNDBUF
1217  * and SO_RCVBUF to the kernel configured limit
1218  *
1219  * For IP_TOS socket option need to mask off bits as this
1220  * aren't automatically masked by the kernel and results in
1221  * an error.
1222  */
1223 int
1224 NET_SetSockOpt(int fd, int level, int  opt, const void *arg,
1225                int len)
1226 {
1227 
1228 #ifndef IPTOS_TOS_MASK
1229 #define IPTOS_TOS_MASK 0x1e
1230 #endif
1231 #ifndef IPTOS_PREC_MASK
1232 #define IPTOS_PREC_MASK 0xe0
1233 #endif
1234 
1235 #if defined(_ALLBSD_SOURCE)
1236 #if defined(KIPC_MAXSOCKBUF)
1237     int mib[3];
1238     size_t rlen;
1239 #endif
1240 
1241     int *bufsize;
1242 
1243 #ifdef __APPLE__
1244     static int maxsockbuf = -1;
1245 #else
1246     static long maxsockbuf = -1;
1247 #endif
1248 #endif
1249 
1250     /*
1251      * IPPROTO/IP_TOS :-
1252      * 1. IPv6 on Solaris/Mac OS:
1253      *    Set the TOS OR Traffic Class value to cater for
1254      *    IPv6 and IPv4 scenarios.
1255      * 2. IPv6 on Linux: By default Linux ignores flowinfo
1256      *    field so enable IPV6_FLOWINFO_SEND so that flowinfo
1257      *    will be examined. We also set the IPv4 TOS option in this case.
1258      * 3. IPv4: set socket option based on ToS and Precedence
1259      *    fields (otherwise get invalid argument)
1260      */
1261     if (level == IPPROTO_IP && opt == IP_TOS) {
1262         int *iptos;
1263 
1264 #if defined(__linux__)
1265         if (ipv6_available()) {
1266             int optval = 1;
1267             if (setsockopt(fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
1268                            (void *)&optval, sizeof(optval)) < 0) {
1269                 return -1;
1270             }
1271            /*
1272             * Let's also set the IPV6_TCLASS flag.
1273             * Linux appears to allow both IP_TOS and IPV6_TCLASS to be set
1274             * This helps in mixed environments where IPv4 and IPv6 sockets
1275             * are connecting.
1276             */
1277            if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
1278                            arg, len) < 0) {
1279                 return -1;
1280             }
1281         }
1282 #endif
1283 
1284         iptos = (int *)arg;
1285         *iptos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
1286     }
1287 
1288     /*
1289      * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On Solaris we may need to clamp
1290      * the value when it exceeds the system limit.
1291      */
1292 #ifdef __solaris__
1293     if (level == SOL_SOCKET) {
1294         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
1295             int sotype=0;
1296             socklen_t arglen;
1297             int *bufsize, maxbuf;
1298             int ret;
1299 
1300             /* Attempt with the original size */
1301             ret = setsockopt(fd, level, opt, arg, len);
1302             if ((ret == 0) || (ret == -1 && errno != ENOBUFS))
1303                 return ret;
1304 
1305             /* Exceeded system limit so clamp and retry */
1306 
1307             arglen = sizeof(sotype);
1308             if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype,
1309                            &arglen) < 0) {
1310                 return -1;
1311             }
1312 
1313             /*
1314              * We try to get tcp_maxbuf (and udp_max_buf) using
1315              * an ioctl() that isn't available on all versions of Solaris.
1316              * If that fails, we use the search algorithm in findMaxBuf()
1317              */
1318             if (!init_tcp_max_buf && sotype == SOCK_STREAM) {
1319                 tcp_max_buf = net_getParam("/dev/tcp", "tcp_max_buf");
1320                 if (tcp_max_buf == -1) {
1321                     tcp_max_buf = findMaxBuf(fd, opt, SOCK_STREAM);
1322                     if (tcp_max_buf == -1) {
1323                         return -1;
1324                     }
1325                 }
1326                 init_tcp_max_buf = 1;
1327             } else if (!init_udp_max_buf && sotype == SOCK_DGRAM) {
1328                 udp_max_buf = net_getParam("/dev/udp", "udp_max_buf");
1329                 if (udp_max_buf == -1) {
1330                     udp_max_buf = findMaxBuf(fd, opt, SOCK_DGRAM);
1331                     if (udp_max_buf == -1) {
1332                         return -1;
1333                     }
1334                 }
1335                 init_udp_max_buf = 1;
1336             }
1337 
1338             maxbuf = (sotype == SOCK_STREAM) ? tcp_max_buf : udp_max_buf;
1339             bufsize = (int *)arg;
1340             if (*bufsize > maxbuf) {
1341                 *bufsize = maxbuf;
1342             }
1343         }
1344     }
1345 #endif
1346 
1347 #ifdef _AIX
1348     if (level == SOL_SOCKET) {
1349         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
1350             /*
1351              * Just try to set the requested size. If it fails we will leave the
1352              * socket option as is. Setting the buffer size means only a hint in
1353              * the jse2/java software layer, see javadoc. In the previous
1354              * solution the buffer has always been truncated to a length of
1355              * 0x100000 Byte, even if the technical limit has not been reached.
1356              * This kind of absolute truncation was unexpected in the jck tests.
1357              */
1358             int ret = setsockopt(fd, level, opt, arg, len);
1359             if ((ret == 0) || (ret == -1 && errno == ENOBUFS)) {
1360                 // Accept failure because of insufficient buffer memory resources.
1361                 return 0;
1362             } else {
1363                 // Deliver all other kinds of errors.
1364                 return ret;
1365             }
1366         }
1367     }
1368 #endif
1369 
1370     /*
1371      * On Linux the receive buffer is used for both socket
1372      * structures and the packet payload. The implication
1373      * is that if SO_RCVBUF is too small then small packets
1374      * must be discarded.
1375      */
1376 #ifdef __linux__
1377     if (level == SOL_SOCKET && opt == SO_RCVBUF) {
1378         int *bufsize = (int *)arg;
1379         if (*bufsize < 1024) {
1380             *bufsize = 1024;
1381         }
1382     }
1383 #endif
1384 
1385 #if defined(_ALLBSD_SOURCE)
1386     /*
1387      * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On FreeBSD need to
1388      * ensure that value is <= kern.ipc.maxsockbuf as otherwise we get
1389      * an ENOBUFS error.
1390      */
1391     if (level == SOL_SOCKET) {
1392         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
1393 #ifdef KIPC_MAXSOCKBUF
1394             if (maxsockbuf == -1) {
1395                mib[0] = CTL_KERN;
1396                mib[1] = KERN_IPC;
1397                mib[2] = KIPC_MAXSOCKBUF;
1398                rlen = sizeof(maxsockbuf);
1399                if (sysctl(mib, 3, &maxsockbuf, &rlen, NULL, 0) == -1)
1400                    maxsockbuf = 1024;
1401 
1402 #if 1
1403                /* XXXBSD: This is a hack to workaround mb_max/mb_max_adj
1404                   problem.  It should be removed when kern.ipc.maxsockbuf
1405                   will be real value. */
1406                maxsockbuf = (maxsockbuf/5)*4;
1407 #endif
1408            }
1409 #elif defined(__OpenBSD__)
1410            maxsockbuf = SB_MAX;
1411 #else
1412            maxsockbuf = 64 * 1024;      /* XXX: NetBSD */
1413 #endif
1414 
1415            bufsize = (int *)arg;
1416            if (*bufsize > maxsockbuf) {
1417                *bufsize = maxsockbuf;
1418            }
1419 
1420            if (opt == SO_RCVBUF && *bufsize < 1024) {
1421                 *bufsize = 1024;
1422            }
1423 
1424         }
1425     }
1426 #endif
1427 
1428 #if defined(_ALLBSD_SOURCE) || defined(_AIX)
1429     /*
1430      * On Solaris, SO_REUSEADDR will allow multiple datagram
1431      * sockets to bind to the same port. The network jck tests check
1432      * for this "feature", so we need to emulate it by turning on
1433      * SO_REUSEPORT as well for that combination.
1434      */
1435     if (level == SOL_SOCKET && opt == SO_REUSEADDR) {
1436         int sotype;
1437         socklen_t arglen;
1438 
1439         arglen = sizeof(sotype);
1440         if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) < 0) {
1441             return -1;
1442         }
1443 
1444         if (sotype == SOCK_DGRAM) {
1445             setsockopt(fd, level, SO_REUSEPORT, arg, len);
1446         }
1447     }
1448 #endif
1449 
1450     return setsockopt(fd, level, opt, arg, len);
1451 }
1452 
1453 /*
1454  * Wrapper for bind system call - performs any necessary pre/post
1455  * processing to deal with OS specific issues :-
1456  *
1457  * Linux allows a socket to bind to 127.0.0.255 which must be
1458  * caught.
1459  *
1460  * On Solaris with IPv6 enabled we must use an exclusive
1461  * bind to guarantee a unique port number across the IPv4 and
1462  * IPv6 port spaces.
1463  *
1464  */
1465 int
1466 NET_Bind(int fd, SOCKETADDRESS *sa, int len)
1467 {
1468 #if defined(__solaris__)
1469     int level = -1;
1470     int exclbind = -1;
1471 #endif
1472     int rv;
1473     int arg, alen;
1474 
1475 #ifdef __linux__
1476     /*
1477      * ## get bugId for this issue - goes back to 1.2.2 port ##
1478      * ## When IPv6 is enabled this will be an IPv4-mapped
1479      * ## with family set to AF_INET6
1480      */
1481     if (sa->sa.sa_family == AF_INET) {
1482         if ((ntohl(sa->sa4.sin_addr.s_addr) & 0x7f0000ff) == 0x7f0000ff) {
1483             errno = EADDRNOTAVAIL;
1484             return -1;
1485         }
1486     }
1487 #endif
1488 
1489 #if defined(__solaris__)
1490     /*
1491      * Solaris has separate IPv4 and IPv6 port spaces so we
1492      * use an exclusive bind when SO_REUSEADDR is not used to
1493      * give the illusion of a unified port space.
1494      * This also avoids problems with IPv6 sockets connecting
1495      * to IPv4 mapped addresses whereby the socket conversion
1496      * results in a late bind that fails because the
1497      * corresponding IPv4 port is in use.
1498      */
1499     alen = sizeof(arg);
1500 
1501     if (useExclBind ||
1502         getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&arg, &alen) == 0)
1503     {
1504         if (useExclBind || arg == 0) {
1505             /*
1506              * SO_REUSEADDR is disabled or sun.net.useExclusiveBind
1507              * property is true so enable TCP_EXCLBIND or
1508              * UDP_EXCLBIND
1509              */
1510             alen = sizeof(arg);
1511             if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&arg, &alen) == 0)
1512             {
1513                 if (arg == SOCK_STREAM) {
1514                     level = IPPROTO_TCP;
1515                     exclbind = TCP_EXCLBIND;
1516                 } else {
1517                     level = IPPROTO_UDP;
1518                     exclbind = UDP_EXCLBIND;
1519                 }
1520             }
1521 
1522             arg = 1;
1523             setsockopt(fd, level, exclbind, (char *)&arg, sizeof(arg));
1524         }
1525     }
1526 
1527 #endif
1528 
1529     rv = bind(fd, &sa->sa, len);
1530 
1531 #if defined(__solaris__)
1532     if (rv < 0) {
1533         int en = errno;
1534         /* Restore *_EXCLBIND if the bind fails */
1535         if (exclbind != -1) {
1536             int arg = 0;
1537             setsockopt(fd, level, exclbind, (char *)&arg,
1538                        sizeof(arg));
1539         }
1540         errno = en;
1541     }
1542 #endif
1543 
1544     return rv;
1545 }
1546 
1547 /**
1548  * Wrapper for poll with timeout on a single file descriptor.
1549  *
1550  * flags (defined in net_util_md.h can be any combination of
1551  * NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
1552  *
1553  * The function will return when either the socket is ready for one
1554  * of the specified operations or the timeout expired.
1555  *
1556  * It returns the time left from the timeout (possibly 0), or -1 if it expired.
1557  */
1558 
1559 jint
1560 NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
1561 {
1562     jlong prevNanoTime = JVM_NanoTime(env, 0);
1563     jlong nanoTimeout = (jlong) timeout * NET_NSEC_PER_MSEC;
1564     jint read_rv;
1565 
1566     while (1) {
1567         jlong newNanoTime;
1568         struct pollfd pfd;
1569         pfd.fd = fd;
1570         pfd.events = 0;
1571         if (flags & NET_WAIT_READ)
1572           pfd.events |= POLLIN;
1573         if (flags & NET_WAIT_WRITE)
1574           pfd.events |= POLLOUT;
1575         if (flags & NET_WAIT_CONNECT)
1576           pfd.events |= POLLOUT;
1577 
1578         errno = 0;
1579         read_rv = NET_Poll(&pfd, 1, nanoTimeout / NET_NSEC_PER_MSEC);
1580 
1581         newNanoTime = JVM_NanoTime(env, 0);
1582         nanoTimeout -= (newNanoTime - prevNanoTime);
1583         if (nanoTimeout < NET_NSEC_PER_MSEC) {
1584           return read_rv > 0 ? 0 : -1;
1585         }
1586         prevNanoTime = newNanoTime;
1587 
1588         if (read_rv > 0) {
1589           break;
1590         }
1591       } /* while */
1592     return (nanoTimeout / NET_NSEC_PER_MSEC);
1593 }