Path: blob/master/src/java.base/unix/native/libnet/net_util_md.c
41119 views
/*1* Copyright (c) 1997, 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 <dlfcn.h>25#include <errno.h>26#include <net/if.h>27#include <netinet/tcp.h> // defines TCP_NODELAY28#include <stdlib.h>29#include <string.h>30#include <sys/ioctl.h>31#include <sys/time.h>3233#if defined(__linux__)34#include <arpa/inet.h>35#include <net/route.h>36#include <sys/utsname.h>37#endif3839#if defined(MACOSX)40#include <sys/sysctl.h>41#endif4243#include "jvm.h"44#include "net_util.h"4546#include "java_net_SocketOptions.h"47#include "java_net_InetAddress.h"4849#if defined(__linux__) && !defined(IPV6_FLOWINFO_SEND)50#define IPV6_FLOWINFO_SEND 3351#endif5253#define RESTARTABLE(_cmd, _result) do { \54do { \55_result = _cmd; \56} while((_result == -1) && (errno == EINTR)); \57} while(0)5859int NET_SocketAvailable(int s, int *pbytes) {60int result;61RESTARTABLE(ioctl(s, FIONREAD, pbytes), result);62return result;63}6465void66NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,67const char *defaultDetail) {68JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);69}7071void72NET_ThrowCurrent(JNIEnv *env, char *msg) {73NET_ThrowNew(env, errno, msg);74}7576void77NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {78char fullMsg[512];79if (!msg) {80msg = "no further information";81}82switch(errorNumber) {83case EBADF:84jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);85JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);86break;87case EINTR:88JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException", msg);89break;90default:91errno = errorNumber;92JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", msg);93break;94}95}969798jfieldID99NET_GetFileDescriptorID(JNIEnv *env)100{101jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");102CHECK_NULL_RETURN(cls, NULL);103return (*env)->GetFieldID(env, cls, "fd", "I");104}105106jint IPv4_supported()107{108int fd = socket(AF_INET, SOCK_STREAM, 0) ;109if (fd < 0) {110return JNI_FALSE;111}112close(fd);113return JNI_TRUE;114}115116#if defined(DONT_ENABLE_IPV6)117jint IPv6_supported()118{119return JNI_FALSE;120}121122#else /* !DONT_ENABLE_IPV6 */123124jint IPv6_supported()125{126int fd;127void *ipv6_fn;128SOCKETADDRESS sa;129socklen_t sa_len = sizeof(SOCKETADDRESS);130131fd = socket(AF_INET6, SOCK_STREAM, 0) ;132if (fd < 0) {133/*134* TODO: We really cant tell since it may be an unrelated error135* for now we will assume that AF_INET6 is not available136*/137return JNI_FALSE;138}139140/*141* If fd 0 is a socket it means we may have been launched from inetd or142* xinetd. If it's a socket then check the family - if it's an143* IPv4 socket then we need to disable IPv6.144*/145if (getsockname(0, &sa.sa, &sa_len) == 0) {146if (sa.sa.sa_family == AF_INET) {147close(fd);148return JNI_FALSE;149}150}151152/**153* Linux - check if any interface has an IPv6 address.154* Don't need to parse the line - we just need an indication.155*/156#ifdef __linux__157{158FILE *fP = fopen("/proc/net/if_inet6", "r");159char buf[255];160char *bufP;161162if (fP == NULL) {163close(fd);164return JNI_FALSE;165}166bufP = fgets(buf, sizeof(buf), fP);167fclose(fP);168if (bufP == NULL) {169close(fd);170return JNI_FALSE;171}172}173#endif174175/*176* OK we may have the stack available in the kernel,177* we should also check if the APIs are available.178*/179ipv6_fn = JVM_FindLibraryEntry(RTLD_DEFAULT, "inet_pton");180close(fd);181if (ipv6_fn == NULL ) {182return JNI_FALSE;183} else {184return JNI_TRUE;185}186}187#endif /* DONT_ENABLE_IPV6 */188189jint reuseport_supported()190{191/* Do a simple dummy call, and try to figure out from that */192int one = 1;193int rv, s;194s = socket(PF_INET, SOCK_STREAM, 0);195if (s < 0) {196return JNI_FALSE;197}198rv = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void *)&one, sizeof(one));199if (rv != 0) {200rv = JNI_FALSE;201} else {202rv = JNI_TRUE;203}204close(s);205return rv;206}207208void NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv *env,209const char* hostname,210int gai_error)211{212int size;213char *buf;214const char *format = "%s: %s";215const char *error_string = gai_strerror(gai_error);216if (error_string == NULL)217error_string = "unknown error";218219size = strlen(format) + strlen(hostname) + strlen(error_string) + 2;220buf = (char *) malloc(size);221if (buf) {222jstring s;223sprintf(buf, format, hostname, error_string);224s = JNU_NewStringPlatform(env, buf);225if (s != NULL) {226jobject x = JNU_NewObjectByName(env,227"java/net/UnknownHostException",228"(Ljava/lang/String;)V", s);229if (x != NULL)230(*env)->Throw(env, x);231}232free(buf);233}234}235236#if defined(_AIX)237238/* Initialize stubs for blocking I/O workarounds (see src/solaris/native/java/net/linux_close.c) */239extern void aix_close_init();240241void platformInit () {242aix_close_init();243}244245#else246247void platformInit () {}248249#endif250251JNIEXPORT jint JNICALL252NET_EnableFastTcpLoopback(int fd) {253return 0;254}255256/**257* See net_util.h for documentation258*/259JNIEXPORT int JNICALL260NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,261SOCKETADDRESS *sa, int *len,262jboolean v4MappedAddress)263{264jint family = getInetAddress_family(env, iaObj);265JNU_CHECK_EXCEPTION_RETURN(env, -1);266memset((char *)sa, 0, sizeof(SOCKETADDRESS));267268if (ipv6_available() &&269!(family == java_net_InetAddress_IPv4 &&270v4MappedAddress == JNI_FALSE))271{272jbyte caddr[16];273jint address;274275if (family == java_net_InetAddress_IPv4) {276// convert to IPv4-mapped address277memset((char *)caddr, 0, 16);278address = getInetAddress_addr(env, iaObj);279JNU_CHECK_EXCEPTION_RETURN(env, -1);280if (address == INADDR_ANY) {281/* we would always prefer IPv6 wildcard address282* caddr[10] = 0xff;283* caddr[11] = 0xff; */284} else {285caddr[10] = 0xff;286caddr[11] = 0xff;287caddr[12] = ((address >> 24) & 0xff);288caddr[13] = ((address >> 16) & 0xff);289caddr[14] = ((address >> 8) & 0xff);290caddr[15] = (address & 0xff);291}292} else {293getInet6Address_ipaddress(env, iaObj, (char *)caddr);294}295sa->sa6.sin6_port = htons(port);296memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));297sa->sa6.sin6_family = AF_INET6;298if (len != NULL) {299*len = sizeof(struct sockaddr_in6);300}301302/* handle scope_id */303if (family != java_net_InetAddress_IPv4) {304if (ia6_scopeidID) {305sa->sa6.sin6_scope_id = getInet6Address_scopeid(env, iaObj);306}307}308} else {309jint address;310if (family != java_net_InetAddress_IPv4) {311JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");312return -1;313}314address = getInetAddress_addr(env, iaObj);315JNU_CHECK_EXCEPTION_RETURN(env, -1);316sa->sa4.sin_port = htons(port);317sa->sa4.sin_addr.s_addr = htonl(address);318sa->sa4.sin_family = AF_INET;319if (len != NULL) {320*len = sizeof(struct sockaddr_in);321}322}323return 0;324}325326void327NET_SetTrafficClass(SOCKETADDRESS *sa, int trafficClass) {328if (sa->sa.sa_family == AF_INET6) {329sa->sa6.sin6_flowinfo = htonl((trafficClass & 0xff) << 20);330}331}332333int334NET_IsIPv4Mapped(jbyte* caddr) {335int i;336for (i = 0; i < 10; i++) {337if (caddr[i] != 0x00) {338return 0; /* false */339}340}341342if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {343return 1; /* true */344}345return 0; /* false */346}347348int349NET_IPv4MappedToIPv4(jbyte* caddr) {350return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)351| (caddr[15] & 0xff);352}353354int355NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {356int i;357for (i = 0; i < 16; i++) {358if (caddr1[i] != caddr2[i]) {359return 0; /* false */360}361}362return 1;363}364365int NET_IsZeroAddr(jbyte* caddr) {366int i;367for (i = 0; i < 16; i++) {368if (caddr[i] != 0) {369return 0;370}371}372return 1;373}374375/*376* Map the Java level socket option to the platform specific377* level and option name.378*/379int380NET_MapSocketOption(jint cmd, int *level, int *optname) {381static struct {382jint cmd;383int level;384int optname;385} const opts[] = {386{ java_net_SocketOptions_TCP_NODELAY, IPPROTO_TCP, TCP_NODELAY },387{ java_net_SocketOptions_SO_OOBINLINE, SOL_SOCKET, SO_OOBINLINE },388{ java_net_SocketOptions_SO_LINGER, SOL_SOCKET, SO_LINGER },389{ java_net_SocketOptions_SO_SNDBUF, SOL_SOCKET, SO_SNDBUF },390{ java_net_SocketOptions_SO_RCVBUF, SOL_SOCKET, SO_RCVBUF },391{ java_net_SocketOptions_SO_KEEPALIVE, SOL_SOCKET, SO_KEEPALIVE },392{ java_net_SocketOptions_SO_REUSEADDR, SOL_SOCKET, SO_REUSEADDR },393{ java_net_SocketOptions_SO_REUSEPORT, SOL_SOCKET, SO_REUSEPORT },394{ java_net_SocketOptions_SO_BROADCAST, SOL_SOCKET, SO_BROADCAST },395{ java_net_SocketOptions_IP_TOS, IPPROTO_IP, IP_TOS },396{ java_net_SocketOptions_IP_MULTICAST_IF, IPPROTO_IP, IP_MULTICAST_IF },397{ java_net_SocketOptions_IP_MULTICAST_IF2, IPPROTO_IP, IP_MULTICAST_IF },398{ java_net_SocketOptions_IP_MULTICAST_LOOP, IPPROTO_IP, IP_MULTICAST_LOOP },399};400401int i;402403if (ipv6_available()) {404switch (cmd) {405// Different multicast options if IPv6 is enabled406case java_net_SocketOptions_IP_MULTICAST_IF:407case java_net_SocketOptions_IP_MULTICAST_IF2:408*level = IPPROTO_IPV6;409*optname = IPV6_MULTICAST_IF;410return 0;411412case java_net_SocketOptions_IP_MULTICAST_LOOP:413*level = IPPROTO_IPV6;414*optname = IPV6_MULTICAST_LOOP;415return 0;416#if defined(MACOSX)417// Map IP_TOS request to IPV6_TCLASS418case java_net_SocketOptions_IP_TOS:419*level = IPPROTO_IPV6;420*optname = IPV6_TCLASS;421return 0;422#endif423}424}425426/*427* Map the Java level option to the native level428*/429for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {430if (cmd == opts[i].cmd) {431*level = opts[i].level;432*optname = opts[i].optname;433return 0;434}435}436437/* not found */438return -1;439}440441/*442* Wrapper for getsockopt system routine - does any necessary443* pre/post processing to deal with OS specific oddities :-444*445* On Linux the SO_SNDBUF/SO_RCVBUF values must be post-processed446* to compensate for an incorrect value returned by the kernel.447*/448int449NET_GetSockOpt(int fd, int level, int opt, void *result,450int *len)451{452int rv;453socklen_t socklen = *len;454455rv = getsockopt(fd, level, opt, result, &socklen);456*len = socklen;457458if (rv < 0) {459return rv;460}461462#ifdef __linux__463/*464* On Linux SO_SNDBUF/SO_RCVBUF aren't symmetric. This465* stems from additional socket structures in the send466* and receive buffers.467*/468if ((level == SOL_SOCKET) && ((opt == SO_SNDBUF)469|| (opt == SO_RCVBUF))) {470int n = *((int *)result);471n /= 2;472*((int *)result) = n;473}474#endif475476/* Workaround for Mac OS treating linger value as477* signed integer478*/479#ifdef MACOSX480if (level == SOL_SOCKET && opt == SO_LINGER) {481struct linger* to_cast = (struct linger*)result;482to_cast->l_linger = (unsigned short)to_cast->l_linger;483}484#endif485return rv;486}487488/*489* Wrapper for setsockopt system routine - performs any490* necessary pre/post processing to deal with OS specific491* issue :-492*493* On Solaris need to limit the suggested value for SO_SNDBUF494* and SO_RCVBUF to the kernel configured limit495*496* For IP_TOS socket option need to mask off bits as this497* aren't automatically masked by the kernel and results in498* an error.499*/500int501NET_SetSockOpt(int fd, int level, int opt, const void *arg,502int len)503{504505#ifndef IPTOS_TOS_MASK506#define IPTOS_TOS_MASK 0x1e507#endif508#ifndef IPTOS_PREC_MASK509#define IPTOS_PREC_MASK 0xe0510#endif511512#if defined(_ALLBSD_SOURCE)513#if defined(KIPC_MAXSOCKBUF)514int mib[3];515size_t rlen;516#endif517518int *bufsize;519520#ifdef __APPLE__521static int maxsockbuf = -1;522#else523static long maxsockbuf = -1;524#endif525#endif526527/*528* IPPROTO/IP_TOS :-529* 1. IPv6 on Solaris/Mac OS:530* Set the TOS OR Traffic Class value to cater for531* IPv6 and IPv4 scenarios.532* 2. IPv6 on Linux: By default Linux ignores flowinfo533* field so enable IPV6_FLOWINFO_SEND so that flowinfo534* will be examined. We also set the IPv4 TOS option in this case.535* 3. IPv4: set socket option based on ToS and Precedence536* fields (otherwise get invalid argument)537*/538if (level == IPPROTO_IP && opt == IP_TOS) {539int *iptos;540541#if defined(__linux__)542if (ipv6_available()) {543int optval = 1;544if (setsockopt(fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,545(void *)&optval, sizeof(optval)) < 0) {546return -1;547}548/*549* Let's also set the IPV6_TCLASS flag.550* Linux appears to allow both IP_TOS and IPV6_TCLASS to be set551* This helps in mixed environments where IPv4 and IPv6 sockets552* are connecting.553*/554if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,555arg, len) < 0) {556return -1;557}558}559#endif560561iptos = (int *)arg;562*iptos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);563}564565#ifdef _AIX566if (level == SOL_SOCKET) {567if (opt == SO_SNDBUF || opt == SO_RCVBUF) {568/*569* Just try to set the requested size. If it fails we will leave the570* socket option as is. Setting the buffer size means only a hint in571* the jse2/java software layer, see javadoc. In the previous572* solution the buffer has always been truncated to a length of573* 0x100000 Byte, even if the technical limit has not been reached.574* This kind of absolute truncation was unexpected in the jck tests.575*/576int ret = setsockopt(fd, level, opt, arg, len);577if ((ret == 0) || (ret == -1 && errno == ENOBUFS)) {578// Accept failure because of insufficient buffer memory resources.579return 0;580} else {581// Deliver all other kinds of errors.582return ret;583}584}585}586#endif587588/*589* On Linux the receive buffer is used for both socket590* structures and the packet payload. The implication591* is that if SO_RCVBUF is too small then small packets592* must be discarded.593*/594#ifdef __linux__595if (level == SOL_SOCKET && opt == SO_RCVBUF) {596int *bufsize = (int *)arg;597if (*bufsize < 1024) {598*bufsize = 1024;599}600}601#endif602603#if defined(_ALLBSD_SOURCE)604/*605* SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On FreeBSD need to606* ensure that value is <= kern.ipc.maxsockbuf as otherwise we get607* an ENOBUFS error.608*/609if (level == SOL_SOCKET) {610if (opt == SO_SNDBUF || opt == SO_RCVBUF) {611#ifdef KIPC_MAXSOCKBUF612if (maxsockbuf == -1) {613mib[0] = CTL_KERN;614mib[1] = KERN_IPC;615mib[2] = KIPC_MAXSOCKBUF;616rlen = sizeof(maxsockbuf);617if (sysctl(mib, 3, &maxsockbuf, &rlen, NULL, 0) == -1)618maxsockbuf = 1024;619620#if 1621/* XXXBSD: This is a hack to workaround mb_max/mb_max_adj622problem. It should be removed when kern.ipc.maxsockbuf623will be real value. */624maxsockbuf = (maxsockbuf/5)*4;625#endif626}627#elif defined(__OpenBSD__)628maxsockbuf = SB_MAX;629#else630maxsockbuf = 64 * 1024; /* XXX: NetBSD */631#endif632633bufsize = (int *)arg;634if (*bufsize > maxsockbuf) {635*bufsize = maxsockbuf;636}637638if (opt == SO_RCVBUF && *bufsize < 1024) {639*bufsize = 1024;640}641642}643}644#endif645646#if defined(_ALLBSD_SOURCE) || defined(_AIX)647/*648* On Solaris, SO_REUSEADDR will allow multiple datagram649* sockets to bind to the same port. The network jck tests check650* for this "feature", so we need to emulate it by turning on651* SO_REUSEPORT as well for that combination.652*/653if (level == SOL_SOCKET && opt == SO_REUSEADDR) {654int sotype;655socklen_t arglen;656657arglen = sizeof(sotype);658if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) < 0) {659return -1;660}661662if (sotype == SOCK_DGRAM) {663setsockopt(fd, level, SO_REUSEPORT, arg, len);664}665}666#endif667668return setsockopt(fd, level, opt, arg, len);669}670671/*672* Wrapper for bind system call - performs any necessary pre/post673* processing to deal with OS specific issues :-674*675* Linux allows a socket to bind to 127.0.0.255 which must be676* caught.677*/678int679NET_Bind(int fd, SOCKETADDRESS *sa, int len)680{681int rv;682int arg, alen;683684#ifdef __linux__685/*686* ## get bugId for this issue - goes back to 1.2.2 port ##687* ## When IPv6 is enabled this will be an IPv4-mapped688* ## with family set to AF_INET6689*/690if (sa->sa.sa_family == AF_INET) {691if ((ntohl(sa->sa4.sin_addr.s_addr) & 0x7f0000ff) == 0x7f0000ff) {692errno = EADDRNOTAVAIL;693return -1;694}695}696#endif697698rv = bind(fd, &sa->sa, len);699700return rv;701}702703/**704* Wrapper for poll with timeout on a single file descriptor.705*706* flags (defined in net_util_md.h can be any combination of707* NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.708*709* The function will return when either the socket is ready for one710* of the specified operations or the timeout expired.711*712* It returns the time left from the timeout (possibly 0), or -1 if it expired.713*/714715jint716NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)717{718jlong prevNanoTime = JVM_NanoTime(env, 0);719jlong nanoTimeout = (jlong) timeout * NET_NSEC_PER_MSEC;720jint read_rv;721722while (1) {723jlong newNanoTime;724struct pollfd pfd;725pfd.fd = fd;726pfd.events = 0;727if (flags & NET_WAIT_READ)728pfd.events |= POLLIN;729if (flags & NET_WAIT_WRITE)730pfd.events |= POLLOUT;731if (flags & NET_WAIT_CONNECT)732pfd.events |= POLLOUT;733734errno = 0;735read_rv = NET_Poll(&pfd, 1, nanoTimeout / NET_NSEC_PER_MSEC);736737newNanoTime = JVM_NanoTime(env, 0);738nanoTimeout -= (newNanoTime - prevNanoTime);739if (nanoTimeout < NET_NSEC_PER_MSEC) {740return read_rv > 0 ? 0 : -1;741}742prevNanoTime = newNanoTime;743744if (read_rv > 0) {745break;746}747} /* while */748return (nanoTimeout / NET_NSEC_PER_MSEC);749}750751752