Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/windows/native/java/net/net_util_md.c
32287 views
/*1* Copyright (c) 1997, 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 <winsock2.h>26#include <ws2tcpip.h>2728#include "net_util.h"29#include "jni.h"3031// Taken from mstcpip.h in Windows SDK 8.0 or newer.32#define SIO_LOOPBACK_FAST_PATH _WSAIOW(IOC_VENDOR,16)3334#ifndef IPTOS_TOS_MASK35#define IPTOS_TOS_MASK 0x1e36#endif37#ifndef IPTOS_PREC_MASK38#define IPTOS_PREC_MASK 0xe039#endif4041/* true if SO_RCVTIMEO is supported */42jboolean isRcvTimeoutSupported = JNI_TRUE;4344/*45* Table of Windows Sockets errors, the specific exception we46* throw for the error, and the error text.47*48* Note that this table excludes OS dependent errors.49*50* Latest list of Windows Sockets errors can be found at :-51* http://msdn.microsoft.com/library/psdk/winsock/errors_3wc2.htm52*/53static struct {54int errCode;55const char *exc;56const char *errString;57} const winsock_errors[] = {58{ WSAEACCES, 0, "Permission denied" },59{ WSAEADDRINUSE, "BindException", "Address already in use" },60{ WSAEADDRNOTAVAIL, "BindException", "Cannot assign requested address" },61{ WSAEAFNOSUPPORT, 0, "Address family not supported by protocol family" },62{ WSAEALREADY, 0, "Operation already in progress" },63{ WSAECONNABORTED, 0, "Software caused connection abort" },64{ WSAECONNREFUSED, "ConnectException", "Connection refused" },65{ WSAECONNRESET, 0, "Connection reset by peer" },66{ WSAEDESTADDRREQ, 0, "Destination address required" },67{ WSAEFAULT, 0, "Bad address" },68{ WSAEHOSTDOWN, 0, "Host is down" },69{ WSAEHOSTUNREACH, "NoRouteToHostException", "No route to host" },70{ WSAEINPROGRESS, 0, "Operation now in progress" },71{ WSAEINTR, 0, "Interrupted function call" },72{ WSAEINVAL, 0, "Invalid argument" },73{ WSAEISCONN, 0, "Socket is already connected" },74{ WSAEMFILE, 0, "Too many open files" },75{ WSAEMSGSIZE, 0, "The message is larger than the maximum supported by the underlying transport" },76{ WSAENETDOWN, 0, "Network is down" },77{ WSAENETRESET, 0, "Network dropped connection on reset" },78{ WSAENETUNREACH, 0, "Network is unreachable" },79{ WSAENOBUFS, 0, "No buffer space available (maximum connections reached?)" },80{ WSAENOPROTOOPT, 0, "Bad protocol option" },81{ WSAENOTCONN, 0, "Socket is not connected" },82{ WSAENOTSOCK, 0, "Socket operation on nonsocket" },83{ WSAEOPNOTSUPP, 0, "Operation not supported" },84{ WSAEPFNOSUPPORT, 0, "Protocol family not supported" },85{ WSAEPROCLIM, 0, "Too many processes" },86{ WSAEPROTONOSUPPORT, 0, "Protocol not supported" },87{ WSAEPROTOTYPE, 0, "Protocol wrong type for socket" },88{ WSAESHUTDOWN, 0, "Cannot send after socket shutdown" },89{ WSAESOCKTNOSUPPORT, 0, "Socket type not supported" },90{ WSAETIMEDOUT, "ConnectException", "Connection timed out" },91{ WSATYPE_NOT_FOUND, 0, "Class type not found" },92{ WSAEWOULDBLOCK, 0, "Resource temporarily unavailable" },93{ WSAHOST_NOT_FOUND, 0, "Host not found" },94{ WSA_NOT_ENOUGH_MEMORY, 0, "Insufficient memory available" },95{ WSANOTINITIALISED, 0, "Successful WSAStartup not yet performed" },96{ WSANO_DATA, 0, "Valid name, no data record of requested type" },97{ WSANO_RECOVERY, 0, "This is a nonrecoverable error" },98{ WSASYSNOTREADY, 0, "Network subsystem is unavailable" },99{ WSATRY_AGAIN, 0, "Nonauthoritative host not found" },100{ WSAVERNOTSUPPORTED, 0, "Winsock.dll version out of range" },101{ WSAEDISCON, 0, "Graceful shutdown in progress" },102{ WSA_OPERATION_ABORTED, 0, "Overlapped operation aborted" },103};104105/*106* Initialize Windows Sockets API support107*/108BOOL WINAPI109DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved)110{111WSADATA wsadata;112113switch (reason) {114case DLL_PROCESS_ATTACH:115if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {116return FALSE;117}118break;119120case DLL_PROCESS_DETACH:121WSACleanup();122break;123124default:125break;126}127return TRUE;128}129130void platformInit() {}131void parseExclusiveBindProperty(JNIEnv *env) {}132133/*134* Since winsock doesn't have the equivalent of strerror(errno)135* use table to lookup error text for the error.136*/137JNIEXPORT void JNICALL138NET_ThrowNew(JNIEnv *env, int errorNum, char *msg)139{140int i;141int table_size = sizeof(winsock_errors) /142sizeof(winsock_errors[0]);143char exc[256];144char fullMsg[256];145char *excP = NULL;146147/*148* If exception already throw then don't overwrite it.149*/150if ((*env)->ExceptionOccurred(env)) {151return;152}153154/*155* Default message text if not provided156*/157if (!msg) {158msg = "no further information";159}160161/*162* Check table for known winsock errors163*/164i=0;165while (i < table_size) {166if (errorNum == winsock_errors[i].errCode) {167break;168}169i++;170}171172/*173* If found get pick the specific exception and error174* message corresponding to this error.175*/176if (i < table_size) {177excP = (char *)winsock_errors[i].exc;178jio_snprintf(fullMsg, sizeof(fullMsg), "%s: %s",179(char *)winsock_errors[i].errString, msg);180} else {181jio_snprintf(fullMsg, sizeof(fullMsg),182"Unrecognized Windows Sockets error: %d: %s",183errorNum, msg);184185}186187/*188* Throw SocketException if no specific exception for this189* error.190*/191if (excP == NULL) {192excP = "SocketException";193}194sprintf(exc, "%s%s", JNU_JAVANETPKG, excP);195JNU_ThrowByName(env, exc, fullMsg);196}197198void199NET_ThrowCurrent(JNIEnv *env, char *msg)200{201NET_ThrowNew(env, WSAGetLastError(), msg);202}203204void205NET_ThrowSocketException(JNIEnv *env, char* msg)206{207static jclass cls = NULL;208if (cls == NULL) {209cls = (*env)->FindClass(env, "java/net/SocketException");210CHECK_NULL(cls);211cls = (*env)->NewGlobalRef(env, cls);212CHECK_NULL(cls);213}214(*env)->ThrowNew(env, cls, msg);215}216217void218NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,219const char *defaultDetail) {220JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);221}222223jfieldID224NET_GetFileDescriptorID(JNIEnv *env)225{226jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");227CHECK_NULL_RETURN(cls, NULL);228return (*env)->GetFieldID(env, cls, "fd", "I");229}230231jint IPv6_supported()232{233SOCKET s = socket(AF_INET6, SOCK_STREAM, 0) ;234if (s == INVALID_SOCKET) {235return JNI_FALSE;236}237closesocket(s);238239return JNI_TRUE;240}241242/*243* Return the default TOS value244*/245int NET_GetDefaultTOS() {246static int default_tos = -1;247OSVERSIONINFO ver;248HKEY hKey;249LONG ret;250251/*252* If default ToS already determined then return it253*/254if (default_tos >= 0) {255return default_tos;256}257258/*259* Assume default is "normal service"260*/261default_tos = 0;262263/*264* Which OS is this?265*/266ver.dwOSVersionInfoSize = sizeof(ver);267GetVersionEx(&ver);268269/*270* If 2000 or greater then no default ToS in registry271*/272if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT) {273if (ver.dwMajorVersion >= 5) {274return default_tos;275}276}277278/*279* Query the registry to see if a Default ToS has been set.280* Different registry entry for NT vs 95/98/ME.281*/282if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT) {283ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,284"SYSTEM\\CurrentControlSet\\Services\\Tcp\\Parameters",2850, KEY_READ, (PHKEY)&hKey);286} else {287ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,288"SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP\\Parameters",2890, KEY_READ, (PHKEY)&hKey);290}291if (ret == ERROR_SUCCESS) {292DWORD dwLen;293DWORD dwDefaultTOS;294ULONG ulType;295dwLen = sizeof(dwDefaultTOS);296297ret = RegQueryValueEx(hKey, "DefaultTOS", NULL, &ulType,298(LPBYTE)&dwDefaultTOS, &dwLen);299RegCloseKey(hKey);300if (ret == ERROR_SUCCESS) {301default_tos = (int)dwDefaultTOS;302}303}304return default_tos;305}306307/* call NET_MapSocketOptionV6 for the IPv6 fd only308* and NET_MapSocketOption for the IPv4 fd309*/310JNIEXPORT int JNICALL311NET_MapSocketOptionV6(jint cmd, int *level, int *optname) {312313switch (cmd) {314case java_net_SocketOptions_IP_MULTICAST_IF:315case java_net_SocketOptions_IP_MULTICAST_IF2:316*level = IPPROTO_IPV6;317*optname = IPV6_MULTICAST_IF;318return 0;319320case java_net_SocketOptions_IP_MULTICAST_LOOP:321*level = IPPROTO_IPV6;322*optname = IPV6_MULTICAST_LOOP;323return 0;324}325return NET_MapSocketOption (cmd, level, optname);326}327328/*329* Map the Java level socket option to the platform specific330* level and option name.331*/332333JNIEXPORT int JNICALL334NET_MapSocketOption(jint cmd, int *level, int *optname) {335336typedef struct {337jint cmd;338int level;339int optname;340} sockopts;341342static sockopts opts[] = {343{ java_net_SocketOptions_TCP_NODELAY, IPPROTO_TCP, TCP_NODELAY },344{ java_net_SocketOptions_SO_OOBINLINE, SOL_SOCKET, SO_OOBINLINE },345{ java_net_SocketOptions_SO_LINGER, SOL_SOCKET, SO_LINGER },346{ java_net_SocketOptions_SO_SNDBUF, SOL_SOCKET, SO_SNDBUF },347{ java_net_SocketOptions_SO_RCVBUF, SOL_SOCKET, SO_RCVBUF },348{ java_net_SocketOptions_SO_KEEPALIVE, SOL_SOCKET, SO_KEEPALIVE },349{ java_net_SocketOptions_SO_REUSEADDR, SOL_SOCKET, SO_REUSEADDR },350{ java_net_SocketOptions_SO_BROADCAST, SOL_SOCKET, SO_BROADCAST },351{ java_net_SocketOptions_IP_MULTICAST_IF, IPPROTO_IP, IP_MULTICAST_IF },352{ java_net_SocketOptions_IP_MULTICAST_LOOP, IPPROTO_IP, IP_MULTICAST_LOOP },353{ java_net_SocketOptions_IP_TOS, IPPROTO_IP, IP_TOS },354355};356357358int i;359360/*361* Map the Java level option to the native level362*/363for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {364if (cmd == opts[i].cmd) {365*level = opts[i].level;366*optname = opts[i].optname;367return 0;368}369}370371/* not found */372return -1;373}374375376/*377* Wrapper for setsockopt dealing with Windows specific issues :-378*379* IP_TOS and IP_MULTICAST_LOOP can't be set on some Windows380* editions.381*382* The value for the type-of-service (TOS) needs to be masked383* to get consistent behaviour with other operating systems.384*/385JNIEXPORT int JNICALL386NET_SetSockOpt(int s, int level, int optname, const void *optval,387int optlen)388{389int rv = 0;390int parg = 0;391int plen = sizeof(parg);392393if (level == IPPROTO_IP && optname == IP_TOS) {394int *tos = (int *)optval;395*tos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);396}397398if (optname == SO_REUSEADDR) {399/*400* Do not set SO_REUSEADDE if SO_EXCLUSIVEADDUSE is already set401*/402rv = NET_GetSockOpt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&parg, &plen);403if (rv == 0 && parg == 1) {404return rv;405}406}407408rv = setsockopt(s, level, optname, optval, optlen);409410if (rv == SOCKET_ERROR) {411/*412* IP_TOS & IP_MULTICAST_LOOP can't be set on some versions413* of Windows.414*/415if ((WSAGetLastError() == WSAENOPROTOOPT) &&416(level == IPPROTO_IP) &&417(optname == IP_TOS || optname == IP_MULTICAST_LOOP)) {418rv = 0;419}420421/*422* IP_TOS can't be set on unbound UDP sockets.423*/424if ((WSAGetLastError() == WSAEINVAL) &&425(level == IPPROTO_IP) &&426(optname == IP_TOS)) {427rv = 0;428}429}430431return rv;432}433434/*435* Wrapper for setsockopt dealing with Windows specific issues :-436*437* IP_TOS is not supported on some versions of Windows so438* instead return the default value for the OS.439*/440JNIEXPORT int JNICALL441NET_GetSockOpt(int s, int level, int optname, void *optval,442int *optlen)443{444int rv;445446if (level == IPPROTO_IPV6 && optname == IPV6_TCLASS) {447int *intopt = (int *)optval;448*intopt = 0;449*optlen = sizeof(*intopt);450return 0;451}452453rv = getsockopt(s, level, optname, optval, optlen);454455456/*457* IPPROTO_IP/IP_TOS is not supported on some Windows458* editions so return the default type-of-service459* value.460*/461if (rv == SOCKET_ERROR) {462463if (WSAGetLastError() == WSAENOPROTOOPT &&464level == IPPROTO_IP && optname == IP_TOS) {465466int *tos;467tos = (int *)optval;468*tos = NET_GetDefaultTOS();469470rv = 0;471}472}473474return rv;475}476477/*478* Sets SO_ECLUSIVEADDRUSE if SO_REUSEADDR is not already set.479*/480void setExclusiveBind(int fd) {481int parg = 0;482int plen = sizeof(parg);483int rv = 0;484rv = NET_GetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&parg, &plen);485if (rv == 0 && parg == 0) {486parg = 1;487rv = NET_SetSockOpt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&parg, plen);488}489}490491/*492* Wrapper for bind winsock call - transparent converts an493* error related to binding to a port that has exclusive access494* into an error indicating the port is in use (facilitates495* better error reporting).496*497* Should be only called by the wrapper method NET_WinBind498*/499JNIEXPORT int JNICALL500NET_Bind(int s, struct sockaddr *him, int len)501{502int rv = 0;503rv = bind(s, him, len);504505if (rv == SOCKET_ERROR) {506/*507* If bind fails with WSAEACCES it means that a privileged508* process has done an exclusive bind (NT SP4/2000/XP only).509*/510if (WSAGetLastError() == WSAEACCES) {511WSASetLastError(WSAEADDRINUSE);512}513}514515return rv;516}517518/*519* Wrapper for NET_Bind call. Sets SO_EXCLUSIVEADDRUSE520* if required, and then calls NET_BIND521*/522JNIEXPORT int JNICALL523NET_WinBind(int s, struct sockaddr *him, int len, jboolean exclBind)524{525if (exclBind == JNI_TRUE)526setExclusiveBind(s);527return NET_Bind(s, him, len);528}529530JNIEXPORT int JNICALL531NET_SocketClose(int fd) {532struct linger l = {0, 0};533int ret = 0;534int len = sizeof (l);535if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, &len) == 0) {536if (l.l_onoff == 0) {537WSASendDisconnect(fd, NULL);538}539}540ret = closesocket (fd);541return ret;542}543544JNIEXPORT int JNICALL545NET_Timeout(int fd, long timeout) {546int ret;547fd_set tbl;548struct timeval t;549t.tv_sec = timeout / 1000;550t.tv_usec = (timeout % 1000) * 1000;551FD_ZERO(&tbl);552FD_SET(fd, &tbl);553ret = select (fd + 1, &tbl, 0, 0, &t);554return ret;555}556557558/*559* differs from NET_Timeout() as follows:560*561* If timeout = -1, it blocks forever.562*563* returns 1 or 2 depending if only one or both sockets564* fire at same time.565*566* *fdret is (one of) the active fds. If both sockets567* fire at same time, *fdret = fd always.568*/569JNIEXPORT int JNICALL570NET_Timeout2(int fd, int fd1, long timeout, int *fdret) {571int ret;572fd_set tbl;573struct timeval t, *tP = &t;574if (timeout == -1) {575tP = 0;576} else {577t.tv_sec = timeout / 1000;578t.tv_usec = (timeout % 1000) * 1000;579}580FD_ZERO(&tbl);581FD_SET(fd, &tbl);582FD_SET(fd1, &tbl);583ret = select (0, &tbl, 0, 0, tP);584switch (ret) {585case 0:586return 0; /* timeout */587case 1:588if (FD_ISSET (fd, &tbl)) {589*fdret= fd;590} else {591*fdret= fd1;592}593return 1;594case 2:595*fdret= fd;596return 2;597}598return -1;599}600601602void dumpAddr (char *str, void *addr) {603struct SOCKADDR_IN6 *a = (struct SOCKADDR_IN6 *)addr;604int family = a->sin6_family;605printf ("%s\n", str);606if (family == AF_INET) {607struct sockaddr_in *him = (struct sockaddr_in *)addr;608printf ("AF_INET: port %d: %x\n", ntohs(him->sin_port),609ntohl(him->sin_addr.s_addr));610} else {611int i;612struct in6_addr *in = &a->sin6_addr;613printf ("AF_INET6 ");614printf ("port %d ", ntohs (a->sin6_port));615printf ("flow %d ", a->sin6_flowinfo);616printf ("addr ");617for (i=0; i<7; i++) {618printf ("%04x:", ntohs(in->s6_words[i]));619}620printf ("%04x", ntohs(in->s6_words[7]));621printf (" scope %d\n", a->sin6_scope_id);622}623}624625/* Macro, which cleans-up the iv6bind structure,626* closes the two sockets (if open),627* and returns SOCKET_ERROR. Used in NET_BindV6 only.628*/629630#define CLOSE_SOCKETS_AND_RETURN do { \631if (fd != -1) { \632closesocket (fd); \633fd = -1; \634} \635if (ofd != -1) { \636closesocket (ofd); \637ofd = -1; \638} \639if (close_fd != -1) { \640closesocket (close_fd); \641close_fd = -1; \642} \643if (close_ofd != -1) { \644closesocket (close_ofd); \645close_ofd = -1; \646} \647b->ipv4_fd = b->ipv6_fd = -1; \648return SOCKET_ERROR; \649} while(0)650651/*652* if ipv6 is available, call NET_BindV6 to bind to the required address/port.653* Because the same port number may need to be reserved in both v4 and v6 space,654* this may require socket(s) to be re-opened. Therefore, all of this information655* is passed in and returned through the ipv6bind structure.656*657* If the request is to bind to a specific address, then this (by definition) means658* only bind in either v4 or v6, and this is just the same as normal. ie. a single659* call to bind() will suffice. The other socket is closed in this case.660*661* The more complicated case is when the requested address is ::0 or 0.0.0.0.662*663* Two further cases:664* 2. If the reqeusted port is 0 (ie. any port) then we try to bind in v4 space665* first with a wild-card port argument. We then try to bind in v6 space666* using the returned port number. If this fails, we repeat the process667* until a free port common to both spaces becomes available.668*669* 3. If the requested port is a specific port, then we just try to get that670* port in both spaces, and if it is not free in both, then the bind fails.671*672* On failure, sockets are closed and an error returned with CLOSE_SOCKETS_AND_RETURN673*/674675JNIEXPORT int JNICALL676NET_BindV6(struct ipv6bind* b, jboolean exclBind) {677int fd=-1, ofd=-1, rv, len;678/* need to defer close until new sockets created */679int close_fd=-1, close_ofd=-1;680SOCKETADDRESS oaddr; /* other address to bind */681int family = b->addr->him.sa_family;682int ofamily;683u_short port; /* requested port parameter */684u_short bound_port;685686if (family == AF_INET && (b->addr->him4.sin_addr.s_addr != INADDR_ANY)) {687/* bind to v4 only */688int ret;689ret = NET_WinBind ((int)b->ipv4_fd, (struct sockaddr *)b->addr,690sizeof (struct sockaddr_in), exclBind);691if (ret == SOCKET_ERROR) {692CLOSE_SOCKETS_AND_RETURN;693}694closesocket (b->ipv6_fd);695b->ipv6_fd = -1;696return 0;697}698if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->him6.sin6_addr))) {699/* bind to v6 only */700int ret;701ret = NET_WinBind ((int)b->ipv6_fd, (struct sockaddr *)b->addr,702sizeof (struct SOCKADDR_IN6), exclBind);703if (ret == SOCKET_ERROR) {704CLOSE_SOCKETS_AND_RETURN;705}706closesocket (b->ipv4_fd);707b->ipv4_fd = -1;708return 0;709}710711/* We need to bind on both stacks, with the same port number */712713memset (&oaddr, 0, sizeof(oaddr));714if (family == AF_INET) {715ofamily = AF_INET6;716fd = (int)b->ipv4_fd;717ofd = (int)b->ipv6_fd;718port = (u_short)GET_PORT (b->addr);719IN6ADDR_SETANY (&oaddr.him6);720oaddr.him6.sin6_port = port;721} else {722ofamily = AF_INET;723ofd = (int)b->ipv4_fd;724fd = (int)b->ipv6_fd;725port = (u_short)GET_PORT (b->addr);726oaddr.him4.sin_family = AF_INET;727oaddr.him4.sin_port = port;728oaddr.him4.sin_addr.s_addr = INADDR_ANY;729}730731rv = NET_WinBind(fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr), exclBind);732if (rv == SOCKET_ERROR) {733CLOSE_SOCKETS_AND_RETURN;734}735736/* get the port and set it in the other address */737len = SOCKETADDRESS_LEN(b->addr);738if (getsockname(fd, (struct sockaddr *)b->addr, &len) == -1) {739CLOSE_SOCKETS_AND_RETURN;740}741bound_port = GET_PORT (b->addr);742SET_PORT (&oaddr, bound_port);743if ((rv=NET_WinBind (ofd, (struct sockaddr *) &oaddr,744SOCKETADDRESS_LEN (&oaddr), exclBind)) == SOCKET_ERROR) {745int retries;746int sotype, arglen=sizeof(sotype);747748/* no retries unless, the request was for any free port */749750if (port != 0) {751CLOSE_SOCKETS_AND_RETURN;752}753754getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen);755756#define SOCK_RETRIES 50757/* 50 is an arbitrary limit, just to ensure that this758* cannot be an endless loop. Would expect socket creation to759* succeed sooner.760*/761for (retries = 0; retries < SOCK_RETRIES; retries ++) {762int len;763close_fd = fd; fd = -1;764close_ofd = ofd; ofd = -1;765b->ipv4_fd = SOCKET_ERROR;766b->ipv6_fd = SOCKET_ERROR;767768/* create two new sockets */769fd = (int)socket (family, sotype, 0);770if (fd == SOCKET_ERROR) {771CLOSE_SOCKETS_AND_RETURN;772}773ofd = (int)socket (ofamily, sotype, 0);774if (ofd == SOCKET_ERROR) {775CLOSE_SOCKETS_AND_RETURN;776}777778/* bind random port on first socket */779SET_PORT (&oaddr, 0);780rv = NET_WinBind (ofd, (struct sockaddr *)&oaddr, SOCKETADDRESS_LEN(&oaddr),781exclBind);782if (rv == SOCKET_ERROR) {783CLOSE_SOCKETS_AND_RETURN;784}785/* close the original pair of sockets before continuing */786closesocket (close_fd);787closesocket (close_ofd);788close_fd = close_ofd = -1;789790/* bind new port on second socket */791len = SOCKETADDRESS_LEN(&oaddr);792if (getsockname(ofd, (struct sockaddr *)&oaddr, &len) == -1) {793CLOSE_SOCKETS_AND_RETURN;794}795bound_port = GET_PORT (&oaddr);796SET_PORT (b->addr, bound_port);797rv = NET_WinBind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr),798exclBind);799800if (rv != SOCKET_ERROR) {801if (family == AF_INET) {802b->ipv4_fd = fd;803b->ipv6_fd = ofd;804} else {805b->ipv4_fd = ofd;806b->ipv6_fd = fd;807}808return 0;809}810}811CLOSE_SOCKETS_AND_RETURN;812}813return 0;814}815816/*817* Determine the default interface for an IPv6 address.818*819* Returns :-820* 0 if error821* > 0 interface index to use822*/823jint getDefaultIPv6Interface(JNIEnv *env, struct SOCKADDR_IN6 *target_addr)824{825int ret;826DWORD b;827struct sockaddr_in6 route;828SOCKET fd = socket(AF_INET6, SOCK_STREAM, 0);829if (fd == INVALID_SOCKET) {830return 0;831}832833ret = WSAIoctl(fd, SIO_ROUTING_INTERFACE_QUERY,834(void *)target_addr, sizeof(struct sockaddr_in6),835(void *)&route, sizeof(struct sockaddr_in6),836&b, 0, 0);837if (ret == SOCKET_ERROR) {838// error839closesocket(fd);840return 0;841} else {842closesocket(fd);843return route.sin6_scope_id;844}845}846847/**848* Enables SIO_LOOPBACK_FAST_PATH849*/850JNIEXPORT jint JNICALL851NET_EnableFastTcpLoopback(int fd) {852int enabled = 1;853DWORD result_byte_count = -1;854int result = WSAIoctl(fd,855SIO_LOOPBACK_FAST_PATH,856&enabled,857sizeof(enabled),858NULL,8590,860&result_byte_count,861NULL,862NULL);863return result == SOCKET_ERROR ? WSAGetLastError() : 0;864}865866/* If address types is IPv6, then IPv6 must be available. Otherwise867* no address can be generated. In the case of an IPv4 Inetaddress this868* method will return an IPv4 mapped address where IPv6 is available and869* v4MappedAddress is TRUE. Otherwise it will return a sockaddr_in870* structure for an IPv4 InetAddress.871*/872JNIEXPORT int JNICALL873NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr *him,874int *len, jboolean v4MappedAddress) {875jint family, iafam;876iafam = getInetAddress_family(env, iaObj);877JNU_CHECK_EXCEPTION_RETURN(env, -1);878family = (iafam == IPv4)? AF_INET : AF_INET6;879if (ipv6_available() && !(family == AF_INET && v4MappedAddress == JNI_FALSE)) {880struct SOCKADDR_IN6 *him6 = (struct SOCKADDR_IN6 *)him;881jbyte caddr[16];882jint address, scopeid = 0;883jint cached_scope_id = 0;884885if (family == AF_INET) { /* will convert to IPv4-mapped address */886memset((char *) caddr, 0, 16);887address = getInetAddress_addr(env, iaObj);888JNU_CHECK_EXCEPTION_RETURN(env, -1);889if (address == INADDR_ANY) {890/* we would always prefer IPv6 wildcard address891caddr[10] = 0xff;892caddr[11] = 0xff; */893} else {894caddr[10] = 0xff;895caddr[11] = 0xff;896caddr[12] = ((address >> 24) & 0xff);897caddr[13] = ((address >> 16) & 0xff);898caddr[14] = ((address >> 8) & 0xff);899caddr[15] = (address & 0xff);900}901} else {902getInet6Address_ipaddress(env, iaObj, (char *)caddr);903scopeid = getInet6Address_scopeid(env, iaObj);904cached_scope_id = (jint)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);905}906907memset((char *)him6, 0, sizeof(struct SOCKADDR_IN6));908him6->sin6_port = (u_short) htons((u_short)port);909memcpy((void *)&(him6->sin6_addr), caddr, sizeof(struct in6_addr) );910him6->sin6_family = AF_INET6;911if ((family == AF_INET6) && IN6_IS_ADDR_LINKLOCAL( &(him6->sin6_addr) )912&& (!scopeid && !cached_scope_id)) {913cached_scope_id = getDefaultIPv6Interface(env, him6);914(*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);915}916him6->sin6_scope_id = scopeid != 0 ? scopeid : cached_scope_id;917*len = sizeof(struct SOCKADDR_IN6) ;918} else {919struct sockaddr_in *him4 = (struct sockaddr_in*)him;920jint address;921if (family != AF_INET) {922JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");923return -1;924}925memset((char *) him4, 0, sizeof(struct sockaddr_in));926address = getInetAddress_addr(env, iaObj);927JNU_CHECK_EXCEPTION_RETURN(env, -1);928him4->sin_port = htons((short) port);929him4->sin_addr.s_addr = (u_long) htonl(address);930him4->sin_family = AF_INET;931*len = sizeof(struct sockaddr_in);932}933return 0;934}935936JNIEXPORT jint JNICALL937NET_GetPortFromSockaddr(struct sockaddr *him) {938if (him->sa_family == AF_INET6) {939return ntohs(((struct sockaddr_in6*)him)->sin6_port);940} else {941return ntohs(((struct sockaddr_in*)him)->sin_port);942}943}944945int946NET_IsIPv4Mapped(jbyte* caddr) {947int i;948for (i = 0; i < 10; i++) {949if (caddr[i] != 0x00) {950return 0; /* false */951}952}953954if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {955return 1; /* true */956}957return 0; /* false */958}959960int961NET_IPv4MappedToIPv4(jbyte* caddr) {962return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)963| (caddr[15] & 0xff);964}965966int967NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {968int i;969for (i = 0; i < 16; i++) {970if (caddr1[i] != caddr2[i]) {971return 0; /* false */972}973}974return 1;975}976977int getScopeID (struct sockaddr *him) {978struct SOCKADDR_IN6 *him6 = (struct SOCKADDR_IN6 *)him;979return him6->sin6_scope_id;980}981982int cmpScopeID (unsigned int scope, struct sockaddr *him) {983struct SOCKADDR_IN6 *him6 = (struct SOCKADDR_IN6 *)him;984return him6->sin6_scope_id == scope;985}986987/**988* Wrapper for select/poll with timeout on a single file descriptor.989*990* flags (defined in net_util_md.h can be any combination of991* NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.992*993* The function will return when either the socket is ready for one994* of the specified operation or the timeout expired.995*996* It returns the time left from the timeout, or -1 if it expired.997*/998999jint1000NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)1001{1002jlong prevTime = JVM_CurrentTimeMillis(env, 0);1003jint read_rv;10041005while (1) {1006jlong newTime;1007fd_set rd, wr, ex;1008struct timeval t;10091010t.tv_sec = timeout / 1000;1011t.tv_usec = (timeout % 1000) * 1000;10121013FD_ZERO(&rd);1014FD_ZERO(&wr);1015FD_ZERO(&ex);1016if (flags & NET_WAIT_READ) {1017FD_SET(fd, &rd);1018}1019if (flags & NET_WAIT_WRITE) {1020FD_SET(fd, &wr);1021}1022if (flags & NET_WAIT_CONNECT) {1023FD_SET(fd, &wr);1024FD_SET(fd, &ex);1025}10261027errno = 0;1028read_rv = select(fd+1, &rd, &wr, &ex, &t);10291030newTime = JVM_CurrentTimeMillis(env, 0);1031timeout -= (jint)(newTime - prevTime);1032if (timeout <= 0) {1033return read_rv > 0 ? 0 : -1;1034}1035newTime = prevTime;10361037if (read_rv > 0) {1038break;1039}104010411042} /* while */10431044return timeout;1045}10461047int NET_Socket (int domain, int type, int protocol) {1048SOCKET sock;1049sock = socket (domain, type, protocol);1050if (sock != INVALID_SOCKET) {1051SetHandleInformation((HANDLE)(uintptr_t)sock, HANDLE_FLAG_INHERIT, FALSE);1052}1053return (int)sock;1054}105510561057