Path: blob/master/src/java.base/unix/native/libnet/Inet4AddressImpl.c
41119 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24#include <ctype.h>25#include <errno.h>26#include <sys/types.h>27#include <netinet/in.h>28#include <netinet/in_systm.h>29#include <netinet/ip.h>30#include <netinet/ip_icmp.h>31#include <stdlib.h>32#include <string.h>33#include <sys/time.h>3435#include "net_util.h"3637#include "java_net_Inet4AddressImpl.h"3839#if defined(MACOSX)40extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6);41#endif4243#define SET_NONBLOCKING(fd) { \44int flags = fcntl(fd, F_GETFL); \45flags |= O_NONBLOCK; \46fcntl(fd, F_SETFL, flags); \47}4849/*50* Inet4AddressImpl51*/5253/*54* Class: java_net_Inet4AddressImpl55* Method: getLocalHostName56* Signature: ()Ljava/lang/String;57*/58JNIEXPORT jstring JNICALL59Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {60char hostname[NI_MAXHOST + 1];6162hostname[0] = '\0';63if (gethostname(hostname, sizeof(hostname)) != 0) {64strcpy(hostname, "localhost");65} else {66// make sure string is null-terminated67hostname[NI_MAXHOST] = '\0';68}69return (*env)->NewStringUTF(env, hostname);70}7172/*73* Find an internet address for a given hostname. Note that this74* code only works for addresses of type INET. The translation75* of %d.%d.%d.%d to an address (int) occurs in java now, so the76* String "host" shouldn't be a %d.%d.%d.%d string. The only77* exception should be when any of the %d are out of range and78* we fallback to a lookup.79*80* Class: java_net_Inet4AddressImpl81* Method: lookupAllHostAddr82* Signature: (Ljava/lang/String;)[[B83*/84JNIEXPORT jobjectArray JNICALL85Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,86jstring host) {87jobjectArray ret = NULL;88const char *hostname;89int error = 0;90struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL,91*iterator;9293initInetAddressIDs(env);94JNU_CHECK_EXCEPTION_RETURN(env, NULL);9596if (IS_NULL(host)) {97JNU_ThrowNullPointerException(env, "host argument is null");98return NULL;99}100hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);101CHECK_NULL_RETURN(hostname, NULL);102103// try once, with our static buffer104memset(&hints, 0, sizeof(hints));105hints.ai_flags = AI_CANONNAME;106hints.ai_family = AF_INET;107108error = getaddrinfo(hostname, NULL, &hints, &res);109110if (error) {111#if defined(MACOSX)112// If getaddrinfo fails try getifaddrs, see bug 8170910.113ret = lookupIfLocalhost(env, hostname, JNI_FALSE);114if (ret != NULL || (*env)->ExceptionCheck(env)) {115goto cleanupAndReturn;116}117#endif118// report error119NET_ThrowUnknownHostExceptionWithGaiError(env, hostname, error);120goto cleanupAndReturn;121} else {122int i = 0;123iterator = res;124while (iterator != NULL) {125// skip duplicates126int skip = 0;127struct addrinfo *iteratorNew = resNew;128while (iteratorNew != NULL) {129struct sockaddr_in *addr1, *addr2;130addr1 = (struct sockaddr_in *)iterator->ai_addr;131addr2 = (struct sockaddr_in *)iteratorNew->ai_addr;132if (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr) {133skip = 1;134break;135}136iteratorNew = iteratorNew->ai_next;137}138139if (!skip) {140struct addrinfo *next141= (struct addrinfo *)malloc(sizeof(struct addrinfo));142if (!next) {143JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");144ret = NULL;145goto cleanupAndReturn;146}147memcpy(next, iterator, sizeof(struct addrinfo));148next->ai_next = NULL;149if (resNew == NULL) {150resNew = next;151} else {152last->ai_next = next;153}154last = next;155i++;156}157iterator = iterator->ai_next;158}159160// allocate array - at this point i contains the number of addresses161ret = (*env)->NewObjectArray(env, i, ia_class, NULL);162if (IS_NULL(ret)) {163goto cleanupAndReturn;164}165166i = 0;167iterator = resNew;168while (iterator != NULL) {169jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);170if (IS_NULL(iaObj)) {171ret = NULL;172goto cleanupAndReturn;173}174setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in *)175(iterator->ai_addr))->sin_addr.s_addr));176if ((*env)->ExceptionCheck(env))177goto cleanupAndReturn;178setInetAddress_hostName(env, iaObj, host);179if ((*env)->ExceptionCheck(env))180goto cleanupAndReturn;181(*env)->SetObjectArrayElement(env, ret, i++, iaObj);182iterator = iterator->ai_next;183}184}185cleanupAndReturn:186JNU_ReleaseStringPlatformChars(env, host, hostname);187while (resNew != NULL) {188last = resNew;189resNew = resNew->ai_next;190free(last);191}192if (res != NULL) {193freeaddrinfo(res);194}195return ret;196}197198/*199* Class: java_net_Inet4AddressImpl200* Method: getHostByAddr201* Signature: ([B)Ljava/lang/String;202*203* Theoretically the UnknownHostException could be enriched with gai error204* information. But as it is silently ignored anyway, there's no need for this.205* It's only important that either a valid hostname is returned or an206* UnknownHostException is thrown.207*/208JNIEXPORT jstring JNICALL209Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,210jbyteArray addrArray) {211jstring ret = NULL;212char host[NI_MAXHOST + 1];213jbyte caddr[4];214jint addr;215struct sockaddr_in sa;216217// construct a sockaddr_in structure218memset((char *)&sa, 0, sizeof(struct sockaddr_in));219(*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);220addr = ((caddr[0] << 24) & 0xff000000);221addr |= ((caddr[1] << 16) & 0xff0000);222addr |= ((caddr[2] << 8) & 0xff00);223addr |= (caddr[3] & 0xff);224sa.sin_addr.s_addr = htonl(addr);225sa.sin_family = AF_INET;226227if (getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in),228host, sizeof(host), NULL, 0, NI_NAMEREQD)) {229JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);230} else {231ret = (*env)->NewStringUTF(env, host);232if (ret == NULL) {233JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);234}235}236237return ret;238}239240/**241* ping implementation using tcp port 7 (echo)242*/243static jboolean244tcp_ping4(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout,245jint ttl)246{247jint fd;248int connect_rv = -1;249250// open a TCP socket251fd = socket(AF_INET, SOCK_STREAM, 0);252if (fd == -1) {253// note: if you run out of fds, you may not be able to load254// the exception class, and get a NoClassDefFoundError instead.255NET_ThrowNew(env, errno, "Can't create socket");256return JNI_FALSE;257}258259// set TTL260if (ttl > 0) {261setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));262}263264// A network interface was specified, so let's bind to it.265if (netif != NULL) {266if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) {267NET_ThrowNew(env, errno, "Can't bind socket");268close(fd);269return JNI_FALSE;270}271}272273// Make the socket non blocking so we can use select/poll.274SET_NONBLOCKING(fd);275276sa->sa4.sin_port = htons(7); // echo port277connect_rv = NET_Connect(fd, &sa->sa, sizeof(struct sockaddr_in));278279// connection established or refused immediately, either way it means280// we were able to reach the host!281if (connect_rv == 0 || errno == ECONNREFUSED) {282close(fd);283return JNI_TRUE;284}285286switch (errno) {287case ENETUNREACH: // Network Unreachable288case EAFNOSUPPORT: // Address Family not supported289case EADDRNOTAVAIL: // address is not available on the remote machine290#if defined(__linux__) || defined(_AIX)291// On some Linux versions, when a socket is bound to the loopback292// interface, connect will fail and errno will be set to EINVAL293// or EHOSTUNREACH. When that happens, don't throw an exception,294// just return false.295case EINVAL:296case EHOSTUNREACH: // No route to host297#endif298close(fd);299return JNI_FALSE;300case EINPROGRESS: // this is expected as we'll probably have to wait301break;302default:303NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",304"connect failed");305close(fd);306return JNI_FALSE;307}308309timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);310if (timeout >= 0) {311// connection has been established, check for error condition312socklen_t optlen = (socklen_t)sizeof(connect_rv);313if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,314&optlen) <0)315{316connect_rv = errno;317}318if (connect_rv == 0 || connect_rv == ECONNREFUSED) {319close(fd);320return JNI_TRUE;321}322}323close(fd);324return JNI_FALSE;325}326327/**328* ping implementation.329* Send an ICMP_ECHO_REQUEST packet every second until either the timeout330* expires or an answer is received.331* Returns true if an ECHO_REPLY is received, false otherwise.332*/333static jboolean334ping4(JNIEnv *env, jint fd, SOCKETADDRESS *sa, SOCKETADDRESS *netif,335jint timeout, jint ttl)336{337jint n, size = 60 * 1024, hlen, tmout2, seq = 1;338socklen_t len;339unsigned char sendbuf[1500], recvbuf[1500];340struct icmp *icmp;341struct ip *ip;342struct sockaddr_in sa_recv;343jchar pid;344struct timeval tv;345size_t plen = ICMP_ADVLENMIN + sizeof(tv);346347setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));348349// sets the ttl (max number of hops)350if (ttl > 0) {351setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));352}353354// a specific interface was specified, so let's bind the socket355// to that interface to ensure the requests are sent only through it.356if (netif != NULL) {357if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) {358NET_ThrowNew(env, errno, "Can't bind socket");359close(fd);360return JNI_FALSE;361}362}363364// icmp_id is a 16 bit data type, therefore down cast the pid365pid = (jchar)getpid();366367// Make the socket non blocking so we can use select368SET_NONBLOCKING(fd);369do {370// create the ICMP request371icmp = (struct icmp *)sendbuf;372icmp->icmp_type = ICMP_ECHO;373icmp->icmp_code = 0;374// let's tag the ECHO packet with our pid so we can identify it375icmp->icmp_id = htons(pid);376icmp->icmp_seq = htons(seq);377seq++;378gettimeofday(&tv, NULL);379memcpy(icmp->icmp_data, &tv, sizeof(tv));380icmp->icmp_cksum = 0;381// manually calculate checksum382icmp->icmp_cksum = in_cksum((u_short *)icmp, plen);383// send it384n = sendto(fd, sendbuf, plen, 0, &sa->sa, sizeof(struct sockaddr_in));385if (n < 0 && errno != EINPROGRESS) {386#if defined(__linux__)387/*388* On some Linux versions, when a socket is bound to the loopback389* interface, sendto will fail and errno will be set to390* EINVAL or EHOSTUNREACH. When that happens, don't throw an391* exception, just return false.392*/393if (errno != EINVAL && errno != EHOSTUNREACH) {394NET_ThrowNew(env, errno, "Can't send ICMP packet");395}396#else397NET_ThrowNew(env, errno, "Can't send ICMP packet");398#endif399close(fd);400return JNI_FALSE;401}402403tmout2 = timeout > 1000 ? 1000 : timeout;404do {405tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);406if (tmout2 >= 0) {407len = sizeof(sa_recv);408n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0,409(struct sockaddr *)&sa_recv, &len);410// check if we received enough data411if (n < (jint)sizeof(struct ip)) {412continue;413}414ip = (struct ip *)recvbuf;415hlen = ((jint)(unsigned int)(ip->ip_hl)) << 2;416// check if we received enough data417if (n < (jint)(hlen + sizeof(struct icmp))) {418continue;419}420icmp = (struct icmp *)(recvbuf + hlen);421// We did receive something, but is it what we were expecting?422// I.E.: An ICMP_ECHO_REPLY packet with the proper PID and423// from the host that we are trying to determine is reachable.424if (icmp->icmp_type == ICMP_ECHOREPLY &&425(ntohs(icmp->icmp_id) == pid))426{427if (sa->sa4.sin_addr.s_addr == sa_recv.sin_addr.s_addr) {428close(fd);429return JNI_TRUE;430} else if (sa->sa4.sin_addr.s_addr == 0) {431close(fd);432return JNI_TRUE;433}434}435}436} while (tmout2 > 0);437timeout -= 1000;438} while (timeout > 0);439close(fd);440return JNI_FALSE;441}442443/*444* Class: java_net_Inet4AddressImpl445* Method: isReachable0446* Signature: ([bI[bI)Z447*/448JNIEXPORT jboolean JNICALL449Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,450jbyteArray addrArray, jint timeout,451jbyteArray ifArray, jint ttl)452{453jbyte caddr[4];454jint addr = 0, sz, fd;455SOCKETADDRESS sa, inf, *netif = NULL;456457// check if address array size is 4 (IPv4 address)458sz = (*env)->GetArrayLength(env, addrArray);459if (sz != 4) {460return JNI_FALSE;461}462463// convert IP address from byte array to integer464memset((char *)caddr, 0, sizeof(caddr));465(*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);466addr = ((caddr[0] << 24) & 0xff000000);467addr |= ((caddr[1] << 16) & 0xff0000);468addr |= ((caddr[2] << 8) & 0xff00);469addr |= (caddr[3] & 0xff);470memset((char *)&sa, 0, sizeof(SOCKETADDRESS));471sa.sa4.sin_addr.s_addr = htonl(addr);472sa.sa4.sin_family = AF_INET;473474// If a network interface was specified, let's convert its address as well.475if (!(IS_NULL(ifArray))) {476memset((char *)caddr, 0, sizeof(caddr));477(*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);478addr = ((caddr[0] << 24) & 0xff000000);479addr |= ((caddr[1] << 16) & 0xff0000);480addr |= ((caddr[2] << 8) & 0xff00);481addr |= (caddr[3] & 0xff);482memset((char *)&inf, 0, sizeof(SOCKETADDRESS));483inf.sa4.sin_addr.s_addr = htonl(addr);484inf.sa4.sin_family = AF_INET;485netif = &inf;486}487488// Let's try to create a RAW socket to send ICMP packets.489// This usually requires "root" privileges, so it's likely to fail.490fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);491if (fd == -1) {492return tcp_ping4(env, &sa, netif, timeout, ttl);493} else {494// It didn't fail, so we can use ICMP_ECHO requests.495return ping4(env, fd, &sa, netif, timeout, ttl);496}497}498499500