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