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