1 /*
   2  * Copyright (c) 2000, 2016, 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 <sys/time.h>
  28 #include <sys/types.h>
  29 #include <sys/socket.h>
  30 #include <netinet/in.h>
  31 #include <netdb.h>
  32 #include <string.h>
  33 #include <strings.h>
  34 #include <stdlib.h>
  35 #include <ctype.h>
  36 #ifdef MACOSX
  37 #include <ifaddrs.h>
  38 #include <net/if.h>
  39 #include <unistd.h> /* gethostname */
  40 #endif
  41 
  42 #include "jvm.h"
  43 #include "jni_util.h"
  44 #include "net_util.h"
  45 #ifndef IPV6_DEFS_H
  46 #include <netinet/icmp6.h>
  47 #endif
  48 
  49 #include "java_net_Inet4AddressImpl.h"
  50 #include "java_net_Inet6AddressImpl.h"
  51 #include "java_net_InetAddress.h"
  52 
  53 /* the initial size of our hostent buffers */
  54 #ifndef NI_MAXHOST
  55 #define NI_MAXHOST 1025
  56 #endif
  57 
  58 
  59 /************************************************************************
  60  * Inet6AddressImpl
  61  */
  62 
  63 /*
  64  * Class:     java_net_Inet6AddressImpl
  65  * Method:    getLocalHostName
  66  * Signature: ()Ljava/lang/String;
  67  */
  68 JNIEXPORT jstring JNICALL
  69 Java_java_net_Inet6AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
  70     int ret;
  71     char hostname[NI_MAXHOST+1];
  72 
  73     hostname[0] = '\0';
  74     ret = gethostname(hostname, NI_MAXHOST);
  75     if (ret == -1) {
  76         /* Something went wrong, maybe networking is not setup? */
  77         strcpy(hostname, "localhost");
  78     } else {
  79         // ensure null-terminated
  80         hostname[NI_MAXHOST] = '\0';
  81     }
  82 
  83 #if defined(__solaris__) && defined(AF_INET6)
  84     if (ret == 0) {
  85         /* Solaris doesn't want to give us a fully qualified domain name.
  86          * We do a reverse lookup to try and get one.  This works
  87          * if DNS occurs before NIS in /etc/resolv.conf, but fails
  88          * if NIS comes first (it still gets only a partial name).
  89          * We use thread-safe system calls.
  90          */
  91         struct addrinfo  hints, *res;
  92         int error;
  93 
  94         memset(&hints, 0, sizeof(hints));
  95         hints.ai_flags = AI_CANONNAME;
  96         hints.ai_family = AF_UNSPEC;
  97 
  98         error = getaddrinfo(hostname, NULL, &hints, &res);
  99 
 100         if (error == 0) {
 101             /* host is known to name service */
 102             error = getnameinfo(res->ai_addr,
 103                                 res->ai_addrlen,
 104                                 hostname,
 105                                 NI_MAXHOST,
 106                                 NULL,
 107                                 0,
 108                                 NI_NAMEREQD);
 109 
 110             /* if getnameinfo fails hostname is still the value
 111                from gethostname */
 112 
 113             freeaddrinfo(res);
 114         }
 115     }
 116 #endif
 117 
 118     return (*env)->NewStringUTF(env, hostname);
 119 }
 120 
 121 #ifdef MACOSX
 122 /* also called from Inet4AddressImpl.c */
 123 __private_extern__ jobjectArray
 124 lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6)
 125 {
 126     jobjectArray result = NULL;
 127     char myhostname[NI_MAXHOST+1];
 128     struct ifaddrs *ifa = NULL;
 129     int familyOrder = 0;
 130     int count = 0, i, j;
 131     int addrs4 = 0, addrs6 = 0, numV4Loopbacks = 0, numV6Loopbacks = 0;
 132     jboolean includeLoopback = JNI_FALSE;
 133     jobject name;
 134 
 135     initInetAddressIDs(env);
 136     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 137 
 138     /* If the requested name matches this host's hostname, return IP addresses
 139      * from all attached interfaces. (#2844683 et al) This prevents undesired
 140      * PPP dialup, but may return addresses that don't actually correspond to
 141      * the name (if the name actually matches something in DNS etc.
 142      */
 143     myhostname[0] = '\0';
 144     if (gethostname(myhostname, NI_MAXHOST) == -1) {
 145         /* Something went wrong, maybe networking is not setup? */
 146         return NULL;
 147     }
 148     myhostname[NI_MAXHOST] = '\0';
 149 
 150     if (strcmp(myhostname, hostname) != 0) {
 151         // Non-self lookup
 152         return NULL;
 153     }
 154 
 155     if (getifaddrs(&ifa) != 0) {
 156         NET_ThrowNew(env, errno, "Can't get local interface addresses");
 157         return NULL;
 158     }
 159 
 160     name = (*env)->NewStringUTF(env, hostname);
 161     CHECK_NULL_RETURN(name, NULL);
 162 
 163     /* Iterate over the interfaces, and total up the number of IPv4 and IPv6
 164      * addresses we have. Also keep a count of loopback addresses. We need to
 165      * exclude them in the normal case, but return them if we don't get an IP
 166      * address.
 167      */
 168     struct ifaddrs *iter = ifa;
 169     while (iter) {
 170         int family = iter->ifa_addr->sa_family;
 171         if (iter->ifa_name[0] != '\0'  &&  iter->ifa_addr)
 172         {
 173             jboolean isLoopback = iter->ifa_flags & IFF_LOOPBACK;
 174             if (family == AF_INET) {
 175                 addrs4++;
 176                 if (isLoopback) numV4Loopbacks++;
 177             } else if (family == AF_INET6 && includeV6) {
 178                 addrs6++;
 179                 if (isLoopback) numV6Loopbacks++;
 180             } else {
 181                 /* We don't care e.g. AF_LINK */
 182             }
 183         }
 184         iter = iter->ifa_next;
 185     }
 186 
 187     if (addrs4 == numV4Loopbacks && addrs6 == numV6Loopbacks) {
 188         // We don't have a real IP address, just loopback. We need to include
 189         // loopback in our results.
 190         includeLoopback = JNI_TRUE;
 191     }
 192 
 193     /* Create and fill the Java array. */
 194     int arraySize = addrs4 + addrs6 -
 195         (includeLoopback ? 0 : (numV4Loopbacks + numV6Loopbacks));
 196     result = (*env)->NewObjectArray(env, arraySize, ia_class, NULL);
 197     if (!result) goto done;
 198 
 199     if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) {
 200         i = includeLoopback ? addrs6 : (addrs6 - numV6Loopbacks);
 201         j = 0;
 202     } else {
 203         i = 0;
 204         j = includeLoopback ? addrs4 : (addrs4 - numV4Loopbacks);
 205     }
 206 
 207     // Now loop around the ifaddrs
 208     iter = ifa;
 209     while (iter != NULL) {
 210         jboolean isLoopback = iter->ifa_flags & IFF_LOOPBACK;
 211         int family = iter->ifa_addr->sa_family;
 212 
 213         if (iter->ifa_name[0] != '\0'  &&  iter->ifa_addr
 214             && (family == AF_INET || (family == AF_INET6 && includeV6))
 215             && (!isLoopback || includeLoopback))
 216         {
 217             int port;
 218             int index = (family == AF_INET) ? i++ : j++;
 219             jobject o = NET_SockaddrToInetAddress(env, iter->ifa_addr, &port);
 220             if (!o) {
 221                 freeifaddrs(ifa);
 222                 if (!(*env)->ExceptionCheck(env))
 223                     JNU_ThrowOutOfMemoryError(env, "Object allocation failed");
 224                 return NULL;
 225             }
 226             setInetAddress_hostName(env, o, name);
 227             (*env)->SetObjectArrayElement(env, result, index, o);
 228             (*env)->DeleteLocalRef(env, o);
 229         }
 230         iter = iter->ifa_next;
 231     }
 232 
 233   done:
 234     freeifaddrs(ifa);
 235 
 236     return result;
 237 }
 238 #endif
 239 
 240 /*
 241  * Find an internet address for a given hostname.  Note that this
 242  * code only works for addresses of type INET. The translation
 243  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
 244  * String "host" shouldn't *ever* be a %d.%d.%d.%d string
 245  *
 246  * Class:     java_net_Inet6AddressImpl
 247  * Method:    lookupAllHostAddr
 248  * Signature: (Ljava/lang/String;)[[B
 249  */
 250 
 251 JNIEXPORT jobjectArray JNICALL
 252 Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
 253                                                 jstring host) {
 254     const char *hostname;
 255     jobjectArray ret = 0;
 256     int retLen = 0;
 257 
 258     int getaddrinfo_error=0;
 259 #ifdef AF_INET6
 260     struct addrinfo hints, *res, *resNew = NULL;
 261 #endif /* AF_INET6 */
 262 
 263     initInetAddressIDs(env);
 264     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 265 
 266     if (IS_NULL(host)) {
 267         JNU_ThrowNullPointerException(env, "host is null");
 268         return 0;
 269     }
 270     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
 271     CHECK_NULL_RETURN(hostname, NULL);
 272 
 273 #ifdef AF_INET6
 274     /* Try once, with our static buffer. */
 275     memset(&hints, 0, sizeof(hints));
 276     hints.ai_flags = AI_CANONNAME;
 277     hints.ai_family = AF_UNSPEC;
 278 
 279 #ifdef __solaris__
 280     /*
 281      * Workaround for Solaris bug 4160367 - if a hostname contains a
 282      * white space then 0.0.0.0 is returned
 283      */
 284     if (isspace((unsigned char)hostname[0])) {
 285         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
 286                         hostname);
 287         JNU_ReleaseStringPlatformChars(env, host, hostname);
 288         return NULL;
 289     }
 290 #endif
 291 
 292     getaddrinfo_error = getaddrinfo(hostname, NULL, &hints, &res);
 293 
 294 #ifdef MACOSX
 295     if (getaddrinfo_error) {
 296         /*
 297          * If getaddrinfo fails looking up the local machine, attempt to get the
 298          * address from getifaddrs. This ensures we get an IPv6 address for the
 299          * local machine.
 300          */
 301         ret = lookupIfLocalhost(env, hostname, JNI_TRUE);
 302         if (ret != NULL || (*env)->ExceptionCheck(env)) {
 303             JNU_ReleaseStringPlatformChars(env, host, hostname);
 304             return ret;
 305         }
 306     }
 307 #endif
 308 
 309     if (getaddrinfo_error) {
 310         /* report error */
 311         NET_ThrowUnknownHostExceptionWithGaiError(
 312             env, hostname, getaddrinfo_error);
 313         JNU_ReleaseStringPlatformChars(env, host, hostname);
 314         return NULL;
 315     } else {
 316         int i = 0, addressPreference = -1;
 317         int inetCount = 0, inet6Count = 0, inetIndex = 0, inet6Index = 0, originalIndex = 0;
 318         struct addrinfo *itr, *last = NULL, *iterator = res;
 319         while (iterator != NULL) {
 320             int skip = 0;
 321             itr = resNew;
 322             while (itr != NULL) {
 323                 if (iterator->ai_family == itr->ai_family &&
 324                     iterator->ai_addrlen == itr->ai_addrlen) {
 325                     if (itr->ai_family == AF_INET) { /* AF_INET */
 326                         struct sockaddr_in *addr1, *addr2;
 327                         addr1 = (struct sockaddr_in *)iterator->ai_addr;
 328                         addr2 = (struct sockaddr_in *)itr->ai_addr;
 329                         if (addr1->sin_addr.s_addr ==
 330                             addr2->sin_addr.s_addr) {
 331                             skip = 1;
 332                             break;
 333                         }
 334                     } else {
 335                         int t;
 336                         struct sockaddr_in6 *addr1, *addr2;
 337                         addr1 = (struct sockaddr_in6 *)iterator->ai_addr;
 338                         addr2 = (struct sockaddr_in6 *)itr->ai_addr;
 339 
 340                         for (t = 0; t < 16; t++) {
 341                             if (addr1->sin6_addr.s6_addr[t] !=
 342                                 addr2->sin6_addr.s6_addr[t]) {
 343                                 break;
 344                             }
 345                         }
 346                         if (t < 16) {
 347                             itr = itr->ai_next;
 348                             continue;
 349                         } else {
 350                             skip = 1;
 351                             break;
 352                         }
 353                     }
 354                 } else if (iterator->ai_family != AF_INET &&
 355                            iterator->ai_family != AF_INET6) {
 356                     /* we can't handle other family types */
 357                     skip = 1;
 358                     break;
 359                 }
 360                 itr = itr->ai_next;
 361             }
 362 
 363             if (!skip) {
 364                 struct addrinfo *next
 365                     = (struct addrinfo*) malloc(sizeof(struct addrinfo));
 366                 if (!next) {
 367                     JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
 368                     ret = NULL;
 369                     goto cleanupAndReturn;
 370                 }
 371                 memcpy(next, iterator, sizeof(struct addrinfo));
 372                 next->ai_next = NULL;
 373                 if (resNew == NULL) {
 374                     resNew = next;
 375                 } else {
 376                     last->ai_next = next;
 377                 }
 378                 last = next;
 379                 i++;
 380                 if (iterator->ai_family == AF_INET) {
 381                     inetCount ++;
 382                 } else if (iterator->ai_family == AF_INET6) {
 383                     inet6Count ++;
 384                 }
 385             }
 386             iterator = iterator->ai_next;
 387         }
 388         retLen = i;
 389         iterator = resNew;
 390 
 391         ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
 392 
 393         if (IS_NULL(ret)) {
 394             /* we may have memory to free at the end of this */
 395             goto cleanupAndReturn;
 396         }
 397 
 398         addressPreference = (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
 399 
 400         if (addressPreference == java_net_InetAddress_PREFER_IPV6_VALUE) {
 401             /* AF_INET addresses will be offset by inet6Count */
 402             inetIndex = inet6Count;
 403             inet6Index = 0;
 404         } else if (addressPreference == java_net_InetAddress_PREFER_IPV4_VALUE) {
 405             /* AF_INET6 addresses will be offset by inetCount */
 406             inetIndex = 0;
 407             inet6Index = inetCount;
 408         } else if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
 409             inetIndex = inet6Index = originalIndex = 0;
 410         }
 411 
 412         while (iterator != NULL) {
 413             jboolean ret1;
 414             if (iterator->ai_family == AF_INET) {
 415                 jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 416                 if (IS_NULL(iaObj)) {
 417                     ret = NULL;
 418                     goto cleanupAndReturn;
 419                 }
 420                 setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
 421                 setInetAddress_hostName(env, iaObj, host);
 422                 (*env)->SetObjectArrayElement(env, ret, (inetIndex | originalIndex), iaObj);
 423                 inetIndex++;
 424             } else if (iterator->ai_family == AF_INET6) {
 425                 jint scope = 0;
 426 
 427                 jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
 428                 if (IS_NULL(iaObj)) {
 429                     ret = NULL;
 430                     goto cleanupAndReturn;
 431                 }
 432                 ret1 = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
 433                 if (ret1 == JNI_FALSE) {
 434                     ret = NULL;
 435                     goto cleanupAndReturn;
 436                 }
 437 
 438                 scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
 439                 if (scope != 0) { /* zero is default value, no need to set */
 440                     setInet6Address_scopeid(env, iaObj, scope);
 441                 }
 442                 setInetAddress_hostName(env, iaObj, host);
 443                 (*env)->SetObjectArrayElement(env, ret, (inet6Index | originalIndex), iaObj);
 444                 inet6Index++;
 445             }
 446             if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
 447                 originalIndex++;
 448                 inetIndex = inet6Index = 0;
 449             }
 450             iterator = iterator->ai_next;
 451         }
 452     }
 453 
 454  cleanupAndReturn:
 455     {
 456       struct addrinfo *iterator, *tmp;
 457         iterator = resNew;
 458         while (iterator != NULL) {
 459             tmp = iterator;
 460             iterator = iterator->ai_next;
 461             free(tmp);
 462         }
 463         JNU_ReleaseStringPlatformChars(env, host, hostname);
 464     }
 465 
 466     freeaddrinfo(res);
 467 #endif /* AF_INET6 */
 468 
 469     return ret;
 470 }
 471 
 472 /*
 473  * Class:     java_net_Inet6AddressImpl
 474  * Method:    getHostByAddr
 475  * Signature: (I)Ljava/lang/String;
 476  */
 477 JNIEXPORT jstring JNICALL
 478 Java_java_net_Inet6AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
 479                                             jbyteArray addrArray) {
 480 
 481     jstring ret = NULL;
 482 
 483 #ifdef AF_INET6
 484     char host[NI_MAXHOST+1];
 485     int error = 0;
 486     int len = 0;
 487     jbyte caddr[16];
 488 
 489     struct sockaddr_in him4;
 490     struct sockaddr_in6 him6;
 491     struct sockaddr *sa;
 492 
 493     /*
 494      * For IPv4 addresses construct a sockaddr_in structure.
 495      */
 496     if ((*env)->GetArrayLength(env, addrArray) == 4) {
 497         jint addr;
 498         (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 499         addr = ((caddr[0]<<24) & 0xff000000);
 500         addr |= ((caddr[1] <<16) & 0xff0000);
 501         addr |= ((caddr[2] <<8) & 0xff00);
 502         addr |= (caddr[3] & 0xff);
 503         memset((void *) &him4, 0, sizeof(him4));
 504         him4.sin_addr.s_addr = (uint32_t) htonl(addr);
 505         him4.sin_family = AF_INET;
 506         sa = (struct sockaddr *) &him4;
 507         len = sizeof(him4);
 508     } else {
 509         /*
 510          * For IPv6 address construct a sockaddr_in6 structure.
 511          */
 512         (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
 513         memset((void *) &him6, 0, sizeof(him6));
 514         memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
 515         him6.sin6_family = AF_INET6;
 516         sa = (struct sockaddr *) &him6 ;
 517         len = sizeof(him6) ;
 518     }
 519 
 520     error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0,
 521                         NI_NAMEREQD);
 522 
 523     if (!error) {
 524         ret = (*env)->NewStringUTF(env, host);
 525         CHECK_NULL_RETURN(ret, NULL);
 526     }
 527 #endif /* AF_INET6 */
 528 
 529     if (ret == NULL) {
 530         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
 531     }
 532 
 533     return ret;
 534 }
 535 
 536 #define SET_NONBLOCKING(fd) {           \
 537         int flags = fcntl(fd, F_GETFL); \
 538         flags |= O_NONBLOCK;            \
 539         fcntl(fd, F_SETFL, flags);      \
 540 }
 541 
 542 #ifdef AF_INET6
 543 static jboolean
 544 ping6(JNIEnv *env, jint fd, struct sockaddr_in6* him, jint timeout,
 545       struct sockaddr_in6* netif, jint ttl) {
 546     jint size;
 547     jint n;
 548     socklen_t len;
 549     char sendbuf[1500];
 550     unsigned char recvbuf[1500];
 551     struct icmp6_hdr *icmp6;
 552     struct sockaddr_in6 sa_recv;
 553     jbyte *caddr, *recv_caddr;
 554     jchar pid;
 555     jint tmout2, seq = 1;
 556     struct timeval tv;
 557     size_t plen;
 558 
 559 #ifdef __linux__
 560     {
 561     int csum_offset;
 562     /**
 563      * For some strange reason, the linux kernel won't calculate the
 564      * checksum of ICMPv6 packets unless you set this socket option
 565      */
 566     csum_offset = 2;
 567     setsockopt(fd, SOL_RAW, IPV6_CHECKSUM, &csum_offset, sizeof(int));
 568     }
 569 #endif
 570 
 571     caddr = (jbyte *)&(him->sin6_addr);
 572 
 573     /* icmp_id is a 16 bit data type, therefore down cast the pid */
 574     pid = (jchar)getpid();
 575     size = 60*1024;
 576     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
 577     if (ttl > 0) {
 578       setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
 579     }
 580     if (netif != NULL) {
 581       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) <0) {
 582         NET_ThrowNew(env, errno, "Can't bind socket");
 583         close(fd);
 584         return JNI_FALSE;
 585       }
 586     }
 587     SET_NONBLOCKING(fd);
 588 
 589     do {
 590       icmp6 = (struct icmp6_hdr *) sendbuf;
 591       icmp6->icmp6_type = ICMP6_ECHO_REQUEST;
 592       icmp6->icmp6_code = 0;
 593       /* let's tag the ECHO packet with our pid so we can identify it */
 594       icmp6->icmp6_id = htons(pid);
 595       icmp6->icmp6_seq = htons(seq);
 596       seq++;
 597       icmp6->icmp6_cksum = 0;
 598       gettimeofday(&tv, NULL);
 599       memcpy(sendbuf + sizeof(struct icmp6_hdr), &tv, sizeof(tv));
 600       plen = sizeof(struct icmp6_hdr) + sizeof(tv);
 601       n = sendto(fd, sendbuf, plen, 0, (struct sockaddr*) him, sizeof(struct sockaddr_in6));
 602       if (n < 0 && errno != EINPROGRESS) {
 603 #ifdef __linux__
 604         if (errno != EINVAL && errno != EHOSTUNREACH)
 605           /*
 606            * On some Linux versions, when a socket is  bound to the
 607            * loopback interface, sendto will fail and errno will be
 608            * set to EINVAL or EHOSTUNREACH.
 609            * When that happens, don't throw an exception, just return false.
 610            */
 611 #endif /*__linux__ */
 612         NET_ThrowNew(env, errno, "Can't send ICMP packet");
 613         close(fd);
 614         return JNI_FALSE;
 615       }
 616 
 617       tmout2 = timeout > 1000 ? 1000 : timeout;
 618       do {
 619         tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
 620 
 621         if (tmout2 >= 0) {
 622           len = sizeof(sa_recv);
 623           n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*) &sa_recv, &len);
 624           icmp6 = (struct icmp6_hdr *) (recvbuf);
 625           recv_caddr = (jbyte *)&(sa_recv.sin6_addr);
 626           /*
 627            * We did receive something, but is it what we were expecting?
 628            * I.E.: An ICMP6_ECHO_REPLY packet with the proper PID and
 629            *       from the host that we are trying to determine is reachable.
 630            */
 631           if (n >= 8 && icmp6->icmp6_type == ICMP6_ECHO_REPLY &&
 632               (ntohs(icmp6->icmp6_id) == pid)) {
 633             if (NET_IsEqual(caddr, recv_caddr)) {
 634               close(fd);
 635               return JNI_TRUE;
 636             }
 637             if (NET_IsZeroAddr(caddr)) {
 638               close(fd);
 639               return JNI_TRUE;
 640             }
 641           }
 642         }
 643       } while (tmout2 > 0);
 644       timeout -= 1000;
 645     } while (timeout > 0);
 646     close(fd);
 647     return JNI_FALSE;
 648 }
 649 #endif /* AF_INET6 */
 650 
 651 /*
 652  * Class:     java_net_Inet6AddressImpl
 653  * Method:    isReachable0
 654  * Signature: ([bII[bI)Z
 655  */
 656 JNIEXPORT jboolean JNICALL
 657 Java_java_net_Inet6AddressImpl_isReachable0(JNIEnv *env, jobject this,
 658                                            jbyteArray addrArray,
 659                                            jint scope,
 660                                            jint timeout,
 661                                            jbyteArray ifArray,
 662                                            jint ttl, jint if_scope) {
 663 #ifdef AF_INET6
 664     jbyte caddr[16];
 665     jint fd, sz;
 666     struct sockaddr_in6 him6;
 667     struct sockaddr_in6 inf6;
 668     struct sockaddr_in6* netif = NULL;
 669     int len = 0;
 670     int connect_rv = -1;
 671 
 672     /*
 673      * If IPv6 is not enable, then we can't reach an IPv6 address, can we?
 674      */
 675     if (!ipv6_available()) {
 676       return JNI_FALSE;
 677     }
 678     /*
 679      * If it's an IPv4 address, ICMP won't work with IPv4 mapped address,
 680      * therefore, let's delegate to the Inet4Address method.
 681      */
 682     sz = (*env)->GetArrayLength(env, addrArray);
 683     if (sz == 4) {
 684       return Java_java_net_Inet4AddressImpl_isReachable0(env, this,
 685                                                          addrArray,
 686                                                          timeout,
 687                                                          ifArray, ttl);
 688     }
 689 
 690     memset((void *) caddr, 0, 16);
 691     memset((void *) &him6, 0, sizeof(him6));
 692     (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
 693     memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
 694     him6.sin6_family = AF_INET6;
 695 #ifdef __linux__
 696     if (scope > 0)
 697       him6.sin6_scope_id = scope;
 698     else
 699       him6.sin6_scope_id = getDefaultIPv6Interface( &(him6.sin6_addr));
 700     len = sizeof(struct sockaddr_in6);
 701 #else
 702     if (scope > 0)
 703       him6.sin6_scope_id = scope;
 704     len = sizeof(struct sockaddr_in6);
 705 #endif
 706     /*
 707      * If a network interface was specified, let's create the address
 708      * for it.
 709      */
 710     if (!(IS_NULL(ifArray))) {
 711       memset((void *) caddr, 0, 16);
 712       memset((void *) &inf6, 0, sizeof(inf6));
 713       (*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);
 714       memcpy((void *)&(inf6.sin6_addr), caddr, sizeof(struct in6_addr) );
 715       inf6.sin6_family = AF_INET6;
 716       inf6.sin6_scope_id = if_scope;
 717       netif = &inf6;
 718     }
 719     /*
 720      * If we can create a RAW socket, then when can use the ICMP ECHO_REQUEST
 721      * otherwise we'll try a tcp socket to the Echo port (7).
 722      * Note that this is empiric, and not connecting could mean it's blocked
 723      * or the echo service has been disabled.
 724      */
 725 
 726     fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
 727 
 728     if (fd != -1) { /* Good to go, let's do a ping */
 729         return ping6(env, fd, &him6, timeout, netif, ttl);
 730     }
 731 
 732     /* No good, let's fall back on TCP */
 733     fd = socket(AF_INET6, SOCK_STREAM, 0);
 734     if (fd == -1) {
 735         /* note: if you run out of fds, you may not be able to load
 736          * the exception class, and get a NoClassDefFoundError
 737          * instead.
 738          */
 739         NET_ThrowNew(env, errno, "Can't create socket");
 740         return JNI_FALSE;
 741     }
 742     if (ttl > 0) {
 743       setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
 744     }
 745 
 746     /*
 747      * A network interface was specified, so let's bind to it.
 748      */
 749     if (netif != NULL) {
 750       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) <0) {
 751         NET_ThrowNew(env, errno, "Can't bind socket");
 752         close(fd);
 753         return JNI_FALSE;
 754       }
 755     }
 756     SET_NONBLOCKING(fd);
 757 
 758     him6.sin6_port = htons((short) 7); /* Echo port */
 759     connect_rv = NET_Connect(fd, (struct sockaddr *)&him6, len);
 760 
 761     /**
 762      * connection established or refused immediately, either way it means
 763      * we were able to reach the host!
 764      */
 765     if (connect_rv == 0 || errno == ECONNREFUSED) {
 766         close(fd);
 767         return JNI_TRUE;
 768     } else {
 769         socklen_t optlen = (socklen_t)sizeof(connect_rv);
 770 
 771         switch (errno) {
 772         case ENETUNREACH: /* Network Unreachable */
 773         case EAFNOSUPPORT: /* Address Family not supported */
 774         case EADDRNOTAVAIL: /* address is not available on  the  remote machine */
 775 #ifdef __linux__
 776         case EINVAL:
 777         case EHOSTUNREACH:
 778           /*
 779            * On some Linux versions, when  a socket is bound to the
 780            * loopback interface, connect will fail and errno will
 781            * be set to EINVAL or EHOSTUNREACH.  When that happens,
 782            * don't throw an exception, just return false.
 783            */
 784 #endif /* __linux__ */
 785           close(fd);
 786           return JNI_FALSE;
 787         }
 788 
 789         if (errno != EINPROGRESS) {
 790             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 791                                          "connect failed");
 792             close(fd);
 793             return JNI_FALSE;
 794         }
 795 
 796         timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
 797 
 798         if (timeout >= 0) {
 799           /* has connection been established */
 800           if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
 801                          &optlen) <0) {
 802             connect_rv = errno;
 803           }
 804           if (connect_rv == 0 || ECONNREFUSED) {
 805             close(fd);
 806             return JNI_TRUE;
 807           }
 808         }
 809         close(fd);
 810         return JNI_FALSE;
 811     }
 812 #else /* AF_INET6 */
 813     return JNI_FALSE;
 814 #endif /* AF_INET6 */
 815 }