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