Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/windows/native/java/net/Inet6AddressImpl.c
32287 views
/*1* Copyright (c) 2000, 2018, 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*/2425#include <windows.h>26#include <winsock2.h>27#include <ctype.h>28#include <stdio.h>29#include <stdlib.h>30#include <malloc.h>31#include <sys/types.h>32#include <process.h>33#include <iphlpapi.h>34#include <icmpapi.h>3536#include "java_net_InetAddress.h"37#include "java_net_Inet4AddressImpl.h"38#include "java_net_Inet6AddressImpl.h"39#include "net_util.h"40#include "icmp.h"4142#ifdef WIN3243#ifndef _WIN644445/* Retain this code a little longer to support building in46* old environments. _MSC_VER is defined as:47* 1200 for MSVC++ 6.048* 1310 for Vc749*/50#if defined(_MSC_VER) && _MSC_VER < 131051#define sockaddr_in6 SOCKADDR_IN652#endif53#endif54#define uint32_t UINT3255#endif5657/*58* Inet6AddressImpl59*/6061/*62* Class: java_net_Inet6AddressImpl63* Method: getLocalHostName64* Signature: ()Ljava/lang/String;65*/66JNIEXPORT jstring JNICALL67Java_java_net_Inet6AddressImpl_getLocalHostName (JNIEnv *env, jobject this) {68char hostname [256];6970if (gethostname (hostname, sizeof (hostname)) == -1) {71strcpy (hostname, "localhost");72}73return JNU_NewStringPlatform (env, hostname);74}7576JNIEXPORT jobjectArray JNICALL77Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,78jstring host) {79const char *hostname;80jobjectArray ret = 0;81int retLen = 0;82jboolean preferIPv6Address;8384int error=0;85struct addrinfo hints, *res, *resNew = NULL;8687initInetAddressIDs(env);88JNU_CHECK_EXCEPTION_RETURN(env, NULL);8990if (IS_NULL(host)) {91JNU_ThrowNullPointerException(env, "host is null");92return 0;93}94hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);95CHECK_NULL_RETURN(hostname, NULL);9697/* get the address preference */98preferIPv6Address99= (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);100101/* Try once, with our static buffer. */102memset(&hints, 0, sizeof(hints));103hints.ai_flags = AI_CANONNAME;104hints.ai_family = AF_UNSPEC;105106error = getaddrinfo(hostname, NULL, &hints, &res);107108if (error) {109if (WSAGetLastError() == WSATRY_AGAIN) {110NET_ThrowByNameWithLastError(env,111JNU_JAVANETPKG "UnknownHostException",112hostname);113JNU_ReleaseStringPlatformChars(env, host, hostname);114return NULL;115} else {116/* report error */117JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",118(char *)hostname);119JNU_ReleaseStringPlatformChars(env, host, hostname);120return NULL;121}122} else {123int i = 0;124int inetCount = 0, inet6Count = 0, inetIndex, inet6Index;125struct addrinfo *itr, *last, *iterator = res;126while (iterator != NULL) {127int skip = 0;128itr = resNew;129while (itr != NULL) {130if (iterator->ai_family == itr->ai_family &&131iterator->ai_addrlen == itr->ai_addrlen) {132if (itr->ai_family == AF_INET) { /* AF_INET */133struct sockaddr_in *addr1, *addr2;134addr1 = (struct sockaddr_in *)iterator->ai_addr;135addr2 = (struct sockaddr_in *)itr->ai_addr;136if (addr1->sin_addr.s_addr ==137addr2->sin_addr.s_addr) {138skip = 1;139break;140}141} else {142int t;143struct sockaddr_in6 *addr1, *addr2;144addr1 = (struct sockaddr_in6 *)iterator->ai_addr;145addr2 = (struct sockaddr_in6 *)itr->ai_addr;146147for (t = 0; t < 16; t++) {148if (addr1->sin6_addr.s6_addr[t] !=149addr2->sin6_addr.s6_addr[t]) {150break;151}152}153if (t < 16) {154itr = itr->ai_next;155continue;156} else {157skip = 1;158break;159}160}161} else if (iterator->ai_family != AF_INET &&162iterator->ai_family != AF_INET6) {163/* we can't handle other family types */164skip = 1;165break;166}167itr = itr->ai_next;168}169170if (!skip) {171struct addrinfo *next172= (struct addrinfo*) malloc(sizeof(struct addrinfo));173if (!next) {174JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");175ret = NULL;176goto cleanupAndReturn;177}178memcpy(next, iterator, sizeof(struct addrinfo));179next->ai_next = NULL;180if (resNew == NULL) {181resNew = next;182} else {183last->ai_next = next;184}185last = next;186i++;187if (iterator->ai_family == AF_INET) {188inetCount ++;189} else if (iterator->ai_family == AF_INET6) {190inet6Count ++;191}192}193iterator = iterator->ai_next;194}195retLen = i;196iterator = resNew;197i = 0;198ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);199200if (IS_NULL(ret)) {201/* we may have memory to free at the end of this */202goto cleanupAndReturn;203}204205if (preferIPv6Address) {206inetIndex = inet6Count;207inet6Index = 0;208} else {209inetIndex = 0;210inet6Index = inetCount;211}212213while (iterator != NULL) {214if (iterator->ai_family == AF_INET) {215jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);216if (IS_NULL(iaObj)) {217ret = NULL;218goto cleanupAndReturn;219}220setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));221if ((*env)->ExceptionCheck(env))222goto cleanupAndReturn;223setInetAddress_hostName(env, iaObj, host);224if ((*env)->ExceptionCheck(env))225goto cleanupAndReturn;226(*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj);227inetIndex ++;228} else if (iterator->ai_family == AF_INET6) {229jint scope = 0, ret1;230jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);231if (IS_NULL(iaObj)) {232ret = NULL;233goto cleanupAndReturn;234}235ret1 = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));236237if (ret1 == JNI_FALSE) {238ret = NULL;239goto cleanupAndReturn;240}241scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;242if (scope != 0) { /* zero is default value, no need to set */243setInet6Address_scopeid(env, iaObj, scope);244}245setInetAddress_hostName(env, iaObj, host);246if ((*env)->ExceptionCheck(env))247goto cleanupAndReturn;248(*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);249inet6Index ++;250}251iterator = iterator->ai_next;252}253}254255cleanupAndReturn:256{257struct addrinfo *iterator, *tmp;258iterator = resNew;259while (iterator != NULL) {260tmp = iterator;261iterator = iterator->ai_next;262free(tmp);263}264JNU_ReleaseStringPlatformChars(env, host, hostname);265}266267freeaddrinfo(res);268269return ret;270}271272/*273* Class: java_net_Inet6AddressImpl274* Method: getHostByAddr275* Signature: (I)Ljava/lang/String;276*/277JNIEXPORT jstring JNICALL278Java_java_net_Inet6AddressImpl_getHostByAddr(JNIEnv *env, jobject this,279jbyteArray addrArray) {280jstring ret = NULL;281282char host[NI_MAXHOST+1];283int error = 0;284int len = 0;285jbyte caddr[16];286287struct sockaddr_in him4;288struct sockaddr_in6 him6;289struct sockaddr *sa;290291/*292* For IPv4 addresses construct a sockaddr_in structure.293*/294if ((*env)->GetArrayLength(env, addrArray) == 4) {295jint addr;296(*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);297addr = ((caddr[0]<<24) & 0xff000000);298addr |= ((caddr[1] <<16) & 0xff0000);299addr |= ((caddr[2] <<8) & 0xff00);300addr |= (caddr[3] & 0xff);301memset((char *) &him4, 0, sizeof(him4));302him4.sin_addr.s_addr = (uint32_t) htonl(addr);303him4.sin_family = AF_INET;304sa = (struct sockaddr *) &him4;305len = sizeof(him4);306} else {307/*308* For IPv6 address construct a sockaddr_in6 structure.309*/310(*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);311memset((char *) &him6, 0, sizeof(him6));312memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );313him6.sin6_family = AF_INET6;314sa = (struct sockaddr *) &him6 ;315len = sizeof(him6) ;316}317318error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);319320if (!error) {321ret = (*env)->NewStringUTF(env, host);322CHECK_NULL_RETURN(ret, NULL);323}324325if (ret == NULL) {326JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);327}328329return ret;330}331332#ifdef AF_INET6333334/**335* ping implementation using tcp port 7 (echo)336*/337static jboolean338tcp_ping6(JNIEnv *env,339jint timeout,340jint ttl,341struct sockaddr_in6 him6,342struct sockaddr_in6* netif,343int len)344{345jint fd;346WSAEVENT hEvent;347int connect_rv = -1;348349fd = NET_Socket(AF_INET6, SOCK_STREAM, 0);350if (fd == SOCKET_ERROR) {351/* note: if you run out of fds, you may not be able to load352* the exception class, and get a NoClassDefFoundError353* instead.354*/355NET_ThrowNew(env, errno, "Can't create socket");356return JNI_FALSE;357}358359/**360* A TTL was specified, let's set the socket option.361*/362if (ttl > 0) {363setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char *)&ttl, sizeof(ttl));364}365366/**367* A network interface was specified, let's bind to it.368*/369if (netif != NULL) {370if (NET_Bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) < 0) {371NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket to interface");372closesocket(fd);373return JNI_FALSE;374}375}376377/**378* Make the socket non blocking.379*/380hEvent = WSACreateEvent();381WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);382383/* no need to use NET_Connect as non-blocking */384him6.sin6_port = htons((short) 7); /* Echo port */385connect_rv = connect(fd, (struct sockaddr *)&him6, len);386387/**388* connection established or refused immediately, either way it means389* we were able to reach the host!390*/391if (connect_rv == 0 || WSAGetLastError() == WSAECONNREFUSED) {392WSACloseEvent(hEvent);393closesocket(fd);394return JNI_TRUE;395} else {396int optlen;397398switch (WSAGetLastError()) {399case WSAEHOSTUNREACH: /* Host Unreachable */400case WSAENETUNREACH: /* Network Unreachable */401case WSAENETDOWN: /* Network is down */402case WSAEPFNOSUPPORT: /* Protocol Family unsupported */403WSACloseEvent(hEvent);404closesocket(fd);405return JNI_FALSE;406}407408if (WSAGetLastError() != WSAEWOULDBLOCK) {409NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",410"connect failed");411WSACloseEvent(hEvent);412closesocket(fd);413return JNI_FALSE;414}415416timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);417418if (timeout >= 0) {419/* has connection been established? */420optlen = sizeof(connect_rv);421if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,422&optlen) <0) {423connect_rv = WSAGetLastError();424}425426if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {427WSACloseEvent(hEvent);428closesocket(fd);429return JNI_TRUE;430}431}432}433WSACloseEvent(hEvent);434closesocket(fd);435return JNI_FALSE;436}437438/**439* ping implementation.440* Send a ICMP_ECHO_REQUEST packet every second until either the timeout441* expires or a answer is received.442* Returns true is an ECHO_REPLY is received, otherwise, false.443*/444static jboolean445ping6(JNIEnv *env,446struct sockaddr_in6* src,447struct sockaddr_in6* dest,448jint timeout,449HANDLE hIcmpFile)450{451DWORD dwRetVal = 0;452char SendData[32] = {0};453LPVOID ReplyBuffer = NULL;454DWORD ReplySize = 0;455IP_OPTION_INFORMATION ipInfo = {255, 0, 0, 0, NULL};456struct sockaddr_in6 sa6Source;457458ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData);459ReplyBuffer = (VOID*) malloc(ReplySize);460if (ReplyBuffer == NULL) {461IcmpCloseHandle(hIcmpFile);462NET_ThrowNew(env, -1, "Unable to allocate memory");463return JNI_FALSE;464}465466//define local source information467sa6Source.sin6_addr = in6addr_any;468sa6Source.sin6_family = AF_INET6;469sa6Source.sin6_flowinfo = 0;470sa6Source.sin6_port = 0;471472dwRetVal = Icmp6SendEcho2(hIcmpFile, // HANDLE IcmpHandle,473NULL, // HANDLE Event,474NULL, // PIO_APC_ROUTINE ApcRoutine,475NULL, // PVOID ApcContext,476&sa6Source, // struct sockaddr_in6 *SourceAddress,477dest, // struct sockaddr_in6 *DestinationAddress,478SendData, // LPVOID RequestData,479sizeof(SendData), // WORD RequestSize,480&ipInfo, // PIP_OPTION_INFORMATION RequestOptions,481ReplyBuffer, // LPVOID ReplyBuffer,482ReplySize, // DWORD ReplySize,483timeout); // DWORD Timeout484485free(ReplyBuffer);486IcmpCloseHandle(hIcmpFile);487488489if (dwRetVal != 0) {490return JNI_TRUE;491} else {492return JNI_FALSE;493}494}495#endif /* AF_INET6 */496497/*498* Class: java_net_Inet6AddressImpl499* Method: isReachable0500* Signature: ([bII[bI)Z501*/502JNIEXPORT jboolean JNICALL503Java_java_net_Inet6AddressImpl_isReachable0(JNIEnv *env, jobject this,504jbyteArray addrArray,505jint scope,506jint timeout,507jbyteArray ifArray,508jint ttl, jint if_scope) {509#ifdef AF_INET6510jbyte caddr[16];511jint sz;512struct sockaddr_in6 him6;513struct sockaddr_in6* netif = NULL;514struct sockaddr_in6 inf6;515int len = 0;516HANDLE hIcmpFile;517518/*519* If IPv6 is not enable, then we can't reach an IPv6 address, can we?520* Actually, we probably shouldn't even get here.521*/522if (!ipv6_available()) {523return JNI_FALSE;524}525/*526* If it's an IPv4 address, ICMP won't work with IPv4 mapped address,527* therefore, let's delegate to the Inet4Address method.528*/529sz = (*env)->GetArrayLength(env, addrArray);530if (sz == 4) {531return Java_java_net_Inet4AddressImpl_isReachable0(env, this,532addrArray,533timeout,534ifArray, ttl);535}536537memset((char *) caddr, 0, 16);538memset((char *) &him6, 0, sizeof(him6));539(*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);540memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );541him6.sin6_family = AF_INET6;542if (scope > 0) {543him6.sin6_scope_id = scope;544}545len = sizeof(struct sockaddr_in6);546547/**548* A network interface was specified, let's convert the address549*/550if (!(IS_NULL(ifArray))) {551memset((char *) caddr, 0, 16);552memset((char *) &inf6, 0, sizeof(inf6));553(*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);554memcpy((void *)&(inf6.sin6_addr), caddr, sizeof(struct in6_addr) );555inf6.sin6_family = AF_INET6;556inf6.sin6_port = 0;557inf6.sin6_scope_id = if_scope;558netif = &inf6;559}560561hIcmpFile = Icmp6CreateFile();562if (hIcmpFile == INVALID_HANDLE_VALUE) {563int err = WSAGetLastError();564if (err == ERROR_ACCESS_DENIED) {565// fall back to TCP echo if access is denied to ICMP566return tcp_ping6(env, timeout, ttl, him6, netif, len);567} else {568NET_ThrowNew(env, err, "Unable to create ICMP file handle");569return JNI_FALSE;570}571} else {572return ping6(env, netif, &him6, timeout, hIcmpFile);573}574575#endif /* AF_INET6 */576return JNI_FALSE;577}578579580