1 /* 2 * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 #include <ctype.h> 26 #include <errno.h> 27 #include <sys/types.h> 28 #include <netinet/in.h> 29 #include <netinet/in_systm.h> 30 #include <netinet/ip.h> 31 #include <netinet/ip_icmp.h> 32 #include <stdlib.h> 33 #include <string.h> 34 #include <sys/time.h> 35 36 #include "net_util.h" 37 38 #include "java_net_Inet4AddressImpl.h" 39 #include "java_net_spi_InetAddressResolver_LookupPolicy.h" 40 41 #if defined(MACOSX) 42 extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6, 43 int addressesOrder); 44 #endif 45 46 #define SET_NONBLOCKING(fd) { \ 47 int flags = fcntl(fd, F_GETFL); \ 48 flags |= O_NONBLOCK; \ 49 fcntl(fd, F_SETFL, flags); \ 50 } 51 52 /* 53 * Inet4AddressImpl 54 */ 55 56 /* 57 * Class: java_net_Inet4AddressImpl 58 * Method: getLocalHostName 59 * Signature: ()Ljava/lang/String; 60 */ 61 JNIEXPORT jstring JNICALL 62 Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) { 63 char hostname[NI_MAXHOST + 1]; 64 65 hostname[0] = '\0'; 66 if (gethostname(hostname, sizeof(hostname)) != 0) { 67 strcpy(hostname, "localhost"); 68 } else { 69 // make sure string is null-terminated 70 hostname[NI_MAXHOST] = '\0'; 71 } 72 return (*env)->NewStringUTF(env, hostname); 73 } 74 75 /* 76 * Find an internet address for a given hostname. Note that this 77 * code only works for addresses of type INET. The translation 78 * of %d.%d.%d.%d to an address (int) occurs in java now, so the 79 * String "host" shouldn't be a %d.%d.%d.%d string. The only 80 * exception should be when any of the %d are out of range and 81 * we fallback to a lookup. 82 * 83 * Class: java_net_Inet4AddressImpl 84 * Method: lookupAllHostAddr 85 * Signature: (Ljava/lang/String;)[[B 86 */ 87 JNIEXPORT jobjectArray JNICALL 88 Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this, 89 jstring host) { 90 jobjectArray ret = NULL; 91 const char *hostname; 92 int error = 0; 93 struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL, 94 *iterator; 95 96 initInetAddressIDs(env); 97 JNU_CHECK_EXCEPTION_RETURN(env, NULL); 98 99 if (IS_NULL(host)) { 100 JNU_ThrowNullPointerException(env, "host argument is null"); 101 return NULL; 102 } 103 hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE); 104 CHECK_NULL_RETURN(hostname, NULL); 105 106 // try once, with our static buffer 107 memset(&hints, 0, sizeof(hints)); 108 hints.ai_flags = AI_CANONNAME; 109 hints.ai_family = AF_INET; 110 111 error = getaddrinfo(hostname, NULL, &hints, &res); 112 113 if (error) { 114 #if defined(MACOSX) 115 // If getaddrinfo fails try getifaddrs, see bug 8170910. 116 // java_net_spi_InetAddressResolver_LookupPolicy_IPV4_FIRST and no ordering is ok 117 // here since only AF_INET addresses will be returned. 118 ret = lookupIfLocalhost(env, hostname, JNI_FALSE, java_net_spi_InetAddressResolver_LookupPolicy_IPV4); 119 if (ret != NULL || (*env)->ExceptionCheck(env)) { 120 goto cleanupAndReturn; 121 } 122 #endif 123 // report error 124 NET_ThrowUnknownHostExceptionWithGaiError(env, hostname, error); 125 goto cleanupAndReturn; 126 } else { 127 int i = 0; 128 iterator = res; 129 while (iterator != NULL) { 130 // skip duplicates 131 int skip = 0; 132 struct addrinfo *iteratorNew = resNew; 133 while (iteratorNew != NULL) { 134 struct sockaddr_in *addr1, *addr2; 135 addr1 = (struct sockaddr_in *)iterator->ai_addr; 136 addr2 = (struct sockaddr_in *)iteratorNew->ai_addr; 137 if (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr) { 138 skip = 1; 139 break; 140 } 141 iteratorNew = iteratorNew->ai_next; 142 } 143 144 if (!skip) { 145 struct addrinfo *next 146 = (struct addrinfo *)malloc(sizeof(struct addrinfo)); 147 if (!next) { 148 JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); 149 ret = NULL; 150 goto cleanupAndReturn; 151 } 152 memcpy(next, iterator, sizeof(struct addrinfo)); 153 next->ai_next = NULL; 154 if (resNew == NULL) { 155 resNew = next; 156 } else { 157 last->ai_next = next; 158 } 159 last = next; 160 i++; 161 } 162 iterator = iterator->ai_next; 163 } 164 165 // allocate array - at this point i contains the number of addresses 166 ret = (*env)->NewObjectArray(env, i, ia_class, NULL); 167 if (IS_NULL(ret)) { 168 goto cleanupAndReturn; 169 } 170 171 i = 0; 172 iterator = resNew; 173 while (iterator != NULL) { 174 jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID); 175 if (IS_NULL(iaObj)) { 176 ret = NULL; 177 goto cleanupAndReturn; 178 } 179 setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in *) 180 (iterator->ai_addr))->sin_addr.s_addr)); 181 if ((*env)->ExceptionCheck(env)) 182 goto cleanupAndReturn; 183 setInetAddress_hostName(env, iaObj, host); 184 if ((*env)->ExceptionCheck(env)) 185 goto cleanupAndReturn; 186 (*env)->SetObjectArrayElement(env, ret, i++, iaObj); 187 iterator = iterator->ai_next; 188 } 189 } 190 cleanupAndReturn: 191 JNU_ReleaseStringPlatformChars(env, host, hostname); 192 while (resNew != NULL) { 193 last = resNew; 194 resNew = resNew->ai_next; 195 free(last); 196 } 197 if (res != NULL) { 198 freeaddrinfo(res); 199 } 200 return ret; 201 } 202 203 /* 204 * Class: java_net_Inet4AddressImpl 205 * Method: getHostByAddr 206 * Signature: ([B)Ljava/lang/String; 207 * 208 * Theoretically the UnknownHostException could be enriched with gai error 209 * information. But as it is silently ignored anyway, there's no need for this. 210 * It's only important that either a valid hostname is returned or an 211 * UnknownHostException is thrown. 212 */ 213 JNIEXPORT jstring JNICALL 214 Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this, 215 jbyteArray addrArray) { 216 jstring ret = NULL; 217 char host[NI_MAXHOST + 1]; 218 jbyte caddr[4]; 219 jint addr; 220 struct sockaddr_in sa; 221 222 // construct a sockaddr_in structure 223 memset((char *)&sa, 0, sizeof(struct sockaddr_in)); 224 (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr); 225 addr = ((caddr[0] << 24) & 0xff000000); 226 addr |= ((caddr[1] << 16) & 0xff0000); 227 addr |= ((caddr[2] << 8) & 0xff00); 228 addr |= (caddr[3] & 0xff); 229 sa.sin_addr.s_addr = htonl(addr); 230 sa.sin_family = AF_INET; 231 232 if (getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), 233 host, sizeof(host), NULL, 0, NI_NAMEREQD)) { 234 JNU_ThrowByName(env, "java/net/UnknownHostException", NULL); 235 } else { 236 ret = (*env)->NewStringUTF(env, host); 237 if (ret == NULL) { 238 JNU_ThrowByName(env, "java/net/UnknownHostException", NULL); 239 } 240 } 241 242 return ret; 243 } 244 245 /** 246 * ping implementation using tcp port 7 (echo) 247 */ 248 static jboolean 249 tcp_ping4(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout, 250 jint ttl) 251 { 252 jint fd; 253 int connect_rv = -1; 254 255 // open a TCP socket 256 fd = socket(AF_INET, SOCK_STREAM, 0); 257 if (fd == -1) { 258 // note: if you run out of fds, you may not be able to load 259 // the exception class, and get a NoClassDefFoundError instead. 260 NET_ThrowNew(env, errno, "Can't create socket"); 261 return JNI_FALSE; 262 } 263 264 // set TTL 265 if (ttl > 0) { 266 setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)); 267 } 268 269 // A network interface was specified, so let's bind to it. 270 if (netif != NULL) { 271 if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) { 272 NET_ThrowNew(env, errno, "Can't bind socket"); 273 close(fd); 274 return JNI_FALSE; 275 } 276 } 277 278 // Make the socket non blocking so we can use select/poll. 279 SET_NONBLOCKING(fd); 280 281 sa->sa4.sin_port = htons(7); // echo port 282 connect_rv = NET_Connect(fd, &sa->sa, sizeof(struct sockaddr_in)); 283 284 // connection established or refused immediately, either way it means 285 // we were able to reach the host! 286 if (connect_rv == 0 || errno == ECONNREFUSED) { 287 close(fd); 288 return JNI_TRUE; 289 } 290 291 switch (errno) { 292 case ENETUNREACH: // Network Unreachable 293 case EAFNOSUPPORT: // Address Family not supported 294 case EADDRNOTAVAIL: // address is not available on the remote machine 295 #if defined(__linux__) || defined(_AIX) 296 // On some Linux versions, when a socket is bound to the loopback 297 // interface, connect will fail and errno will be set to EINVAL 298 // or EHOSTUNREACH. When that happens, don't throw an exception, 299 // just return false. 300 case EINVAL: 301 case EHOSTUNREACH: // No route to host 302 #endif 303 close(fd); 304 return JNI_FALSE; 305 case EINPROGRESS: // this is expected as we'll probably have to wait 306 break; 307 default: 308 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException", 309 "connect failed"); 310 close(fd); 311 return JNI_FALSE; 312 } 313 314 timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout); 315 if (timeout >= 0) { 316 // connection has been established, check for error condition 317 socklen_t optlen = (socklen_t)sizeof(connect_rv); 318 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv, 319 &optlen) <0) 320 { 321 connect_rv = errno; 322 } 323 if (connect_rv == 0 || connect_rv == ECONNREFUSED) { 324 close(fd); 325 return JNI_TRUE; 326 } 327 } 328 close(fd); 329 return JNI_FALSE; 330 } 331 332 /** 333 * ping implementation. 334 * Send an ICMP_ECHO_REQUEST packet every second until either the timeout 335 * expires or an answer is received. 336 * Returns true if an ECHO_REPLY is received, false otherwise. 337 */ 338 static jboolean 339 ping4(JNIEnv *env, jint fd, SOCKETADDRESS *sa, SOCKETADDRESS *netif, 340 jint timeout, jint ttl) 341 { 342 jint n, size = 60 * 1024, hlen, tmout2, seq = 1; 343 socklen_t len; 344 unsigned char sendbuf[1500], recvbuf[1500]; 345 struct icmp *icmp; 346 struct ip *ip; 347 struct sockaddr_in sa_recv; 348 jchar pid; 349 struct timeval tv; 350 size_t plen = ICMP_ADVLENMIN + sizeof(tv); 351 352 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); 353 354 // sets the ttl (max number of hops) 355 if (ttl > 0) { 356 setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)); 357 } 358 359 // a specific interface was specified, so let's bind the socket 360 // to that interface to ensure the requests are sent only through it. 361 if (netif != NULL) { 362 if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) { 363 NET_ThrowNew(env, errno, "Can't bind socket"); 364 close(fd); 365 return JNI_FALSE; 366 } 367 } 368 369 // icmp_id is a 16 bit data type, therefore down cast the pid 370 pid = (jchar)getpid(); 371 372 // Make the socket non blocking so we can use select 373 SET_NONBLOCKING(fd); 374 do { 375 // create the ICMP request 376 icmp = (struct icmp *)sendbuf; 377 icmp->icmp_type = ICMP_ECHO; 378 icmp->icmp_code = 0; 379 // let's tag the ECHO packet with our pid so we can identify it 380 icmp->icmp_id = htons(pid); 381 icmp->icmp_seq = htons(seq); 382 seq++; 383 gettimeofday(&tv, NULL); 384 memcpy(icmp->icmp_data, &tv, sizeof(tv)); 385 icmp->icmp_cksum = 0; 386 // manually calculate checksum 387 icmp->icmp_cksum = in_cksum((u_short *)icmp, plen); 388 // send it 389 n = sendto(fd, sendbuf, plen, 0, &sa->sa, sizeof(struct sockaddr_in)); 390 if (n < 0 && errno != EINPROGRESS) { 391 #if defined(__linux__) 392 /* 393 * On some Linux versions, when a socket is bound to the loopback 394 * interface, sendto will fail and errno will be set to 395 * EINVAL or EHOSTUNREACH. When that happens, don't throw an 396 * exception, just return false. 397 */ 398 if (errno != EINVAL && errno != EHOSTUNREACH) { 399 NET_ThrowNew(env, errno, "Can't send ICMP packet"); 400 } 401 #else 402 NET_ThrowNew(env, errno, "Can't send ICMP packet"); 403 #endif 404 close(fd); 405 return JNI_FALSE; 406 } 407 408 tmout2 = timeout > 1000 ? 1000 : timeout; 409 do { 410 tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2); 411 if (tmout2 >= 0) { 412 len = sizeof(sa_recv); 413 n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, 414 (struct sockaddr *)&sa_recv, &len); 415 // check if we received enough data 416 if (n < (jint)sizeof(struct ip)) { 417 continue; 418 } 419 ip = (struct ip *)recvbuf; 420 hlen = ((jint)(unsigned int)(ip->ip_hl)) << 2; 421 // check if we received enough data 422 if (n < (jint)(hlen + sizeof(struct icmp))) { 423 continue; 424 } 425 icmp = (struct icmp *)(recvbuf + hlen); 426 // We did receive something, but is it what we were expecting? 427 // I.E.: An ICMP_ECHO_REPLY packet with the proper PID and 428 // from the host that we are trying to determine is reachable. 429 if (icmp->icmp_type == ICMP_ECHOREPLY && 430 (ntohs(icmp->icmp_id) == pid)) 431 { 432 if (sa->sa4.sin_addr.s_addr == sa_recv.sin_addr.s_addr) { 433 close(fd); 434 return JNI_TRUE; 435 } else if (sa->sa4.sin_addr.s_addr == 0) { 436 close(fd); 437 return JNI_TRUE; 438 } 439 } 440 } 441 } while (tmout2 > 0); 442 timeout -= 1000; 443 } while (timeout > 0); 444 close(fd); 445 return JNI_FALSE; 446 } 447 448 /* 449 * Class: java_net_Inet4AddressImpl 450 * Method: isReachable0 451 * Signature: ([bI[bI)Z 452 */ 453 JNIEXPORT jboolean JNICALL 454 Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this, 455 jbyteArray addrArray, jint timeout, 456 jbyteArray ifArray, jint ttl) 457 { 458 jbyte caddr[4]; 459 jint addr = 0, sz, fd; 460 SOCKETADDRESS sa, inf, *netif = NULL; 461 462 // check if address array size is 4 (IPv4 address) 463 sz = (*env)->GetArrayLength(env, addrArray); 464 if (sz != 4) { 465 return JNI_FALSE; 466 } 467 468 // convert IP address from byte array to integer 469 memset((char *)caddr, 0, sizeof(caddr)); 470 (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr); 471 addr = ((caddr[0] << 24) & 0xff000000); 472 addr |= ((caddr[1] << 16) & 0xff0000); 473 addr |= ((caddr[2] << 8) & 0xff00); 474 addr |= (caddr[3] & 0xff); 475 memset((char *)&sa, 0, sizeof(SOCKETADDRESS)); 476 sa.sa4.sin_addr.s_addr = htonl(addr); 477 sa.sa4.sin_family = AF_INET; 478 479 // If a network interface was specified, let's convert its address as well. 480 if (!(IS_NULL(ifArray))) { 481 memset((char *)caddr, 0, sizeof(caddr)); 482 (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr); 483 addr = ((caddr[0] << 24) & 0xff000000); 484 addr |= ((caddr[1] << 16) & 0xff0000); 485 addr |= ((caddr[2] << 8) & 0xff00); 486 addr |= (caddr[3] & 0xff); 487 memset((char *)&inf, 0, sizeof(SOCKETADDRESS)); 488 inf.sa4.sin_addr.s_addr = htonl(addr); 489 inf.sa4.sin_family = AF_INET; 490 netif = &inf; 491 } 492 493 // Let's try to create a RAW socket to send ICMP packets. 494 // This usually requires "root" privileges, so it's likely to fail. 495 fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 496 if (fd == -1) { 497 return tcp_ping4(env, &sa, netif, timeout, ttl); 498 } else { 499 // It didn't fail, so we can use ICMP_ECHO requests. 500 return ping4(env, fd, &sa, netif, timeout, ttl); 501 } 502 } --- EOF ---