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