1 /*
2  * Copyright (c) 1997, 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 <dlfcn.h>
26 #include <errno.h>
27 #include <net/if.h>
28 #include <netinet/tcp.h> // defines TCP_NODELAY
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <sys/time.h>
33 
34 #if defined(__linux__)
35 #include <arpa/inet.h>
36 #include <net/route.h>
37 #include <sys/utsname.h>
38 #endif
39 
40 #if defined(MACOSX)
41 #include <sys/sysctl.h>
42 #endif
43 
44 #ifdef __OpenBSD__
45 #include <sys/socketvar.h>
46 #endif
47 
48 #include "jvm.h"
49 #include "net_util.h"
50 
51 #include "java_net_SocketOptions.h"
52 #include "java_net_InetAddress.h"
53 
54 #if defined(__linux__) && !defined(IPV6_FLOWINFO_SEND)
55 #define IPV6_FLOWINFO_SEND      33
56 #endif
57 
58 #define RESTARTABLE(_cmd, _result) do { \
59     do { \
60         _result = _cmd; \
61     } while((_result == -1) && (errno == EINTR)); \
62 } while(0)
63 
NET_SocketAvailable(int s,int * pbytes)64 int NET_SocketAvailable(int s, int *pbytes) {
65     int result;
66     RESTARTABLE(ioctl(s, FIONREAD, pbytes), result);
67     return result;
68 }
69 
70 void
NET_ThrowByNameWithLastError(JNIEnv * env,const char * name,const char * defaultDetail)71 NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
72                    const char *defaultDetail) {
73     JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);
74 }
75 
76 void
NET_ThrowCurrent(JNIEnv * env,char * msg)77 NET_ThrowCurrent(JNIEnv *env, char *msg) {
78     NET_ThrowNew(env, errno, msg);
79 }
80 
81 void
NET_ThrowNew(JNIEnv * env,int errorNumber,char * msg)82 NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {
83     char fullMsg[512];
84     if (!msg) {
85         msg = "no further information";
86     }
87     switch(errorNumber) {
88     case EBADF:
89         jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);
90         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
91         break;
92     case EINTR:
93         JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException", msg);
94         break;
95     default:
96         errno = errorNumber;
97         JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", msg);
98         break;
99     }
100 }
101 
102 
103 jfieldID
NET_GetFileDescriptorID(JNIEnv * env)104 NET_GetFileDescriptorID(JNIEnv *env)
105 {
106     jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
107     CHECK_NULL_RETURN(cls, NULL);
108     return (*env)->GetFieldID(env, cls, "fd", "I");
109 }
110 
IPv4_supported()111 jint  IPv4_supported()
112 {
113     int fd = socket(AF_INET, SOCK_STREAM, 0) ;
114     if (fd < 0) {
115         return JNI_FALSE;
116     }
117     close(fd);
118     return JNI_TRUE;
119 }
120 
121 #if defined(DONT_ENABLE_IPV6) || defined(__DragonFly__)
IPv6_supported()122 jint  IPv6_supported()
123 {
124     return JNI_FALSE;
125 }
126 
127 #else /* !DONT_ENABLE_IPV6 */
128 
IPv6_supported()129 jint  IPv6_supported()
130 {
131     int fd;
132     void *ipv6_fn;
133     SOCKETADDRESS sa;
134     socklen_t sa_len = sizeof(SOCKETADDRESS);
135 
136     fd = socket(AF_INET6, SOCK_STREAM, 0) ;
137     if (fd < 0) {
138         /*
139          *  TODO: We really cant tell since it may be an unrelated error
140          *  for now we will assume that AF_INET6 is not available
141          */
142         return JNI_FALSE;
143     }
144 
145     /*
146      * If fd 0 is a socket it means we may have been launched from inetd or
147      * xinetd. If it's a socket then check the family - if it's an
148      * IPv4 socket then we need to disable IPv6.
149      */
150     if (getsockname(0, &sa.sa, &sa_len) == 0) {
151         if (sa.sa.sa_family == AF_INET) {
152             close(fd);
153             return JNI_FALSE;
154         }
155     }
156 
157     /**
158      * Linux - check if any interface has an IPv6 address.
159      * Don't need to parse the line - we just need an indication.
160      */
161 #ifdef __linux__
162     {
163         FILE *fP = fopen("/proc/net/if_inet6", "r");
164         char buf[255];
165         char *bufP;
166 
167         if (fP == NULL) {
168             close(fd);
169             return JNI_FALSE;
170         }
171         bufP = fgets(buf, sizeof(buf), fP);
172         fclose(fP);
173         if (bufP == NULL) {
174             close(fd);
175             return JNI_FALSE;
176         }
177     }
178 #endif
179 
180     /*
181      *  OK we may have the stack available in the kernel,
182      *  we should also check if the APIs are available.
183      */
184     ipv6_fn = JVM_FindLibraryEntry(RTLD_DEFAULT, "inet_pton");
185     close(fd);
186     if (ipv6_fn == NULL ) {
187         return JNI_FALSE;
188     } else {
189         return JNI_TRUE;
190     }
191 }
192 #endif /* DONT_ENABLE_IPV6 */
193 
reuseport_supported()194 jint reuseport_supported()
195 {
196     /* Do a simple dummy call, and try to figure out from that */
197     int one = 1;
198     int rv, s;
199     s = socket(PF_INET, SOCK_STREAM, 0);
200     if (s < 0) {
201         return JNI_FALSE;
202     }
203     rv = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void *)&one, sizeof(one));
204     if (rv != 0) {
205         rv = JNI_FALSE;
206     } else {
207         rv = JNI_TRUE;
208     }
209     close(s);
210     return rv;
211 }
212 
NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv * env,const char * hostname,int gai_error)213 void NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv *env,
214                                                const char* hostname,
215                                                int gai_error)
216 {
217     int size;
218     char *buf;
219     const char *format = "%s: %s";
220     const char *error_string = gai_strerror(gai_error);
221     if (error_string == NULL)
222         error_string = "unknown error";
223 
224     size = strlen(format) + strlen(hostname) + strlen(error_string) + 2;
225     buf = (char *) malloc(size);
226     if (buf) {
227         jstring s;
228         sprintf(buf, format, hostname, error_string);
229         s = JNU_NewStringPlatform(env, buf);
230         if (s != NULL) {
231             jobject x = JNU_NewObjectByName(env,
232                                             "java/net/UnknownHostException",
233                                             "(Ljava/lang/String;)V", s);
234             if (x != NULL)
235                 (*env)->Throw(env, x);
236         }
237         free(buf);
238     }
239 }
240 
241 #if defined(_AIX)
242 
243 /* Initialize stubs for blocking I/O workarounds (see src/solaris/native/java/net/linux_close.c) */
244 extern void aix_close_init();
245 
platformInit()246 void platformInit () {
247     aix_close_init();
248 }
249 
250 #else
251 
platformInit()252 void platformInit () {}
253 
254 #endif
255 
256 JNIEXPORT jint JNICALL
NET_EnableFastTcpLoopback(int fd)257 NET_EnableFastTcpLoopback(int fd) {
258     return 0;
259 }
260 
261 /**
262  * See net_util.h for documentation
263  */
264 JNIEXPORT int JNICALL
NET_InetAddressToSockaddr(JNIEnv * env,jobject iaObj,int port,SOCKETADDRESS * sa,int * len,jboolean v4MappedAddress)265 NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,
266                           SOCKETADDRESS *sa, int *len,
267                           jboolean v4MappedAddress)
268 {
269     jint family = getInetAddress_family(env, iaObj);
270     JNU_CHECK_EXCEPTION_RETURN(env, -1);
271     memset((char *)sa, 0, sizeof(SOCKETADDRESS));
272 
273     if (ipv6_available() &&
274         !(family == java_net_InetAddress_IPv4 &&
275           v4MappedAddress == JNI_FALSE))
276     {
277         jbyte caddr[16];
278         jint address;
279 
280         if (family == java_net_InetAddress_IPv4) {
281             // convert to IPv4-mapped address
282             memset((char *)caddr, 0, 16);
283             address = getInetAddress_addr(env, iaObj);
284             JNU_CHECK_EXCEPTION_RETURN(env, -1);
285             if (address == INADDR_ANY) {
286                 /* we would always prefer IPv6 wildcard address
287                  * caddr[10] = 0xff;
288                  * caddr[11] = 0xff; */
289             } else {
290                 caddr[10] = 0xff;
291                 caddr[11] = 0xff;
292                 caddr[12] = ((address >> 24) & 0xff);
293                 caddr[13] = ((address >> 16) & 0xff);
294                 caddr[14] = ((address >> 8) & 0xff);
295                 caddr[15] = (address & 0xff);
296             }
297         } else {
298             getInet6Address_ipaddress(env, iaObj, (char *)caddr);
299         }
300         sa->sa6.sin6_port = htons(port);
301         memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));
302         sa->sa6.sin6_family = AF_INET6;
303         if (len != NULL) {
304             *len = sizeof(struct sockaddr_in6);
305         }
306 
307         /* handle scope_id */
308         if (family != java_net_InetAddress_IPv4) {
309             if (ia6_scopeidID) {
310                 sa->sa6.sin6_scope_id = getInet6Address_scopeid(env, iaObj);
311             }
312         }
313     } else {
314         jint address;
315         if (family != java_net_InetAddress_IPv4) {
316             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
317             return -1;
318         }
319         address = getInetAddress_addr(env, iaObj);
320         JNU_CHECK_EXCEPTION_RETURN(env, -1);
321         sa->sa4.sin_port = htons(port);
322         sa->sa4.sin_addr.s_addr = htonl(address);
323         sa->sa4.sin_family = AF_INET;
324         if (len != NULL) {
325             *len = sizeof(struct sockaddr_in);
326         }
327     }
328     return 0;
329 }
330 
331 void
NET_SetTrafficClass(SOCKETADDRESS * sa,int trafficClass)332 NET_SetTrafficClass(SOCKETADDRESS *sa, int trafficClass) {
333     if (sa->sa.sa_family == AF_INET6) {
334         sa->sa6.sin6_flowinfo = htonl((trafficClass & 0xff) << 20);
335     }
336 }
337 
338 int
NET_IsIPv4Mapped(jbyte * caddr)339 NET_IsIPv4Mapped(jbyte* caddr) {
340     int i;
341     for (i = 0; i < 10; i++) {
342         if (caddr[i] != 0x00) {
343             return 0; /* false */
344         }
345     }
346 
347     if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
348         return 1; /* true */
349     }
350     return 0; /* false */
351 }
352 
353 int
NET_IPv4MappedToIPv4(jbyte * caddr)354 NET_IPv4MappedToIPv4(jbyte* caddr) {
355     return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
356         | (caddr[15] & 0xff);
357 }
358 
359 int
NET_IsEqual(jbyte * caddr1,jbyte * caddr2)360 NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
361     int i;
362     for (i = 0; i < 16; i++) {
363         if (caddr1[i] != caddr2[i]) {
364             return 0; /* false */
365         }
366     }
367     return 1;
368 }
369 
NET_IsZeroAddr(jbyte * caddr)370 int NET_IsZeroAddr(jbyte* caddr) {
371     int i;
372     for (i = 0; i < 16; i++) {
373         if (caddr[i] != 0) {
374             return 0;
375         }
376     }
377     return 1;
378 }
379 
380 /*
381  * Map the Java level socket option to the platform specific
382  * level and option name.
383  */
384 int
NET_MapSocketOption(jint cmd,int * level,int * optname)385 NET_MapSocketOption(jint cmd, int *level, int *optname) {
386     static struct {
387         jint cmd;
388         int level;
389         int optname;
390     } const opts[] = {
391         { java_net_SocketOptions_TCP_NODELAY,           IPPROTO_TCP,    TCP_NODELAY },
392         { java_net_SocketOptions_SO_OOBINLINE,          SOL_SOCKET,     SO_OOBINLINE },
393         { java_net_SocketOptions_SO_LINGER,             SOL_SOCKET,     SO_LINGER },
394         { java_net_SocketOptions_SO_SNDBUF,             SOL_SOCKET,     SO_SNDBUF },
395         { java_net_SocketOptions_SO_RCVBUF,             SOL_SOCKET,     SO_RCVBUF },
396         { java_net_SocketOptions_SO_KEEPALIVE,          SOL_SOCKET,     SO_KEEPALIVE },
397         { java_net_SocketOptions_SO_REUSEADDR,          SOL_SOCKET,     SO_REUSEADDR },
398         { java_net_SocketOptions_SO_REUSEPORT,          SOL_SOCKET,     SO_REUSEPORT },
399         { java_net_SocketOptions_SO_BROADCAST,          SOL_SOCKET,     SO_BROADCAST },
400         { java_net_SocketOptions_IP_TOS,                IPPROTO_IP,     IP_TOS },
401         { java_net_SocketOptions_IP_MULTICAST_IF,       IPPROTO_IP,     IP_MULTICAST_IF },
402         { java_net_SocketOptions_IP_MULTICAST_IF2,      IPPROTO_IP,     IP_MULTICAST_IF },
403         { java_net_SocketOptions_IP_MULTICAST_LOOP,     IPPROTO_IP,     IP_MULTICAST_LOOP },
404     };
405 
406     int i;
407 
408     if (ipv6_available()) {
409         switch (cmd) {
410             // Different multicast options if IPv6 is enabled
411             case java_net_SocketOptions_IP_MULTICAST_IF:
412             case java_net_SocketOptions_IP_MULTICAST_IF2:
413                 *level = IPPROTO_IPV6;
414                 *optname = IPV6_MULTICAST_IF;
415                 return 0;
416 
417             case java_net_SocketOptions_IP_MULTICAST_LOOP:
418                 *level = IPPROTO_IPV6;
419                 *optname = IPV6_MULTICAST_LOOP;
420                 return 0;
421 #if defined(MACOSX)
422             // Map IP_TOS request to IPV6_TCLASS
423             case java_net_SocketOptions_IP_TOS:
424                 *level = IPPROTO_IPV6;
425                 *optname = IPV6_TCLASS;
426                 return 0;
427 #endif
428         }
429     }
430 
431     /*
432      * Map the Java level option to the native level
433      */
434     for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
435         if (cmd == opts[i].cmd) {
436             *level = opts[i].level;
437             *optname = opts[i].optname;
438             return 0;
439         }
440     }
441 
442     /* not found */
443     return -1;
444 }
445 
446 /*
447  * Wrapper for getsockopt system routine - does any necessary
448  * pre/post processing to deal with OS specific oddities :-
449  *
450  * On Linux the SO_SNDBUF/SO_RCVBUF values must be post-processed
451  * to compensate for an incorrect value returned by the kernel.
452  */
453 int
NET_GetSockOpt(int fd,int level,int opt,void * result,int * len)454 NET_GetSockOpt(int fd, int level, int opt, void *result,
455                int *len)
456 {
457     int rv;
458     socklen_t socklen = *len;
459 
460     rv = getsockopt(fd, level, opt, result, &socklen);
461     *len = socklen;
462 
463     if (rv < 0) {
464         return rv;
465     }
466 
467 #ifdef __linux__
468     /*
469      * On Linux SO_SNDBUF/SO_RCVBUF aren't symmetric. This
470      * stems from additional socket structures in the send
471      * and receive buffers.
472      */
473     if ((level == SOL_SOCKET) && ((opt == SO_SNDBUF)
474                                   || (opt == SO_RCVBUF))) {
475         int n = *((int *)result);
476         n /= 2;
477         *((int *)result) = n;
478     }
479 #endif
480 
481 /* Workaround for Mac OS treating linger value as
482  *  signed integer
483  */
484 #ifdef MACOSX
485     if (level == SOL_SOCKET && opt == SO_LINGER) {
486         struct linger* to_cast = (struct linger*)result;
487         to_cast->l_linger = (unsigned short)to_cast->l_linger;
488     }
489 #endif
490     return rv;
491 }
492 
493 /*
494  * Wrapper for setsockopt system routine - performs any
495  * necessary pre/post processing to deal with OS specific
496  * issue :-
497  *
498  * On Solaris need to limit the suggested value for SO_SNDBUF
499  * and SO_RCVBUF to the kernel configured limit
500  *
501  * For IP_TOS socket option need to mask off bits as this
502  * aren't automatically masked by the kernel and results in
503  * an error.
504  */
505 int
NET_SetSockOpt(int fd,int level,int opt,const void * arg,int len)506 NET_SetSockOpt(int fd, int level, int  opt, const void *arg,
507                int len)
508 {
509 
510 #ifndef IPTOS_TOS_MASK
511 #define IPTOS_TOS_MASK 0x1e
512 #endif
513 #ifndef IPTOS_PREC_MASK
514 #define IPTOS_PREC_MASK 0xe0
515 #endif
516 
517 #if defined(_ALLBSD_SOURCE)
518 #if defined(KIPC_MAXSOCKBUF)
519     int mib[3];
520     size_t rlen;
521 #endif
522 
523     int *bufsize;
524 
525 #ifdef __APPLE__
526     static int maxsockbuf = -1;
527 #else
528     static long maxsockbuf = -1;
529 #endif
530 #endif
531 
532     /*
533      * IPPROTO/IP_TOS :-
534      * 1. IPv6 on Solaris/Mac OS:
535      *    Set the TOS OR Traffic Class value to cater for
536      *    IPv6 and IPv4 scenarios.
537      * 2. IPv6 on Linux: By default Linux ignores flowinfo
538      *    field so enable IPV6_FLOWINFO_SEND so that flowinfo
539      *    will be examined. We also set the IPv4 TOS option in this case.
540      * 3. IPv4: set socket option based on ToS and Precedence
541      *    fields (otherwise get invalid argument)
542      */
543     if (level == IPPROTO_IP && opt == IP_TOS) {
544         int *iptos;
545 
546 #if defined(__linux__)
547         if (ipv6_available()) {
548             int optval = 1;
549             if (setsockopt(fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
550                            (void *)&optval, sizeof(optval)) < 0) {
551                 return -1;
552             }
553            /*
554             * Let's also set the IPV6_TCLASS flag.
555             * Linux appears to allow both IP_TOS and IPV6_TCLASS to be set
556             * This helps in mixed environments where IPv4 and IPv6 sockets
557             * are connecting.
558             */
559            if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
560                            arg, len) < 0) {
561                 return -1;
562             }
563         }
564 #endif
565 
566         iptos = (int *)arg;
567         *iptos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
568     }
569 
570 #ifdef _AIX
571     if (level == SOL_SOCKET) {
572         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
573             /*
574              * Just try to set the requested size. If it fails we will leave the
575              * socket option as is. Setting the buffer size means only a hint in
576              * the jse2/java software layer, see javadoc. In the previous
577              * solution the buffer has always been truncated to a length of
578              * 0x100000 Byte, even if the technical limit has not been reached.
579              * This kind of absolute truncation was unexpected in the jck tests.
580              */
581             int ret = setsockopt(fd, level, opt, arg, len);
582             if ((ret == 0) || (ret == -1 && errno == ENOBUFS)) {
583                 // Accept failure because of insufficient buffer memory resources.
584                 return 0;
585             } else {
586                 // Deliver all other kinds of errors.
587                 return ret;
588             }
589         }
590     }
591 #endif
592 
593     /*
594      * On Linux the receive buffer is used for both socket
595      * structures and the packet payload. The implication
596      * is that if SO_RCVBUF is too small then small packets
597      * must be discarded.
598      */
599 #ifdef __linux__
600     if (level == SOL_SOCKET && opt == SO_RCVBUF) {
601         int *bufsize = (int *)arg;
602         if (*bufsize < 1024) {
603             *bufsize = 1024;
604         }
605     }
606 #endif
607 
608 #if defined(_ALLBSD_SOURCE)
609     /*
610      * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On FreeBSD need to
611      * ensure that value is <= kern.ipc.maxsockbuf as otherwise we get
612      * an ENOBUFS error.
613      */
614     if (level == SOL_SOCKET) {
615         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
616 #ifdef KIPC_MAXSOCKBUF
617             if (maxsockbuf == -1) {
618                mib[0] = CTL_KERN;
619                mib[1] = KERN_IPC;
620                mib[2] = KIPC_MAXSOCKBUF;
621                rlen = sizeof(maxsockbuf);
622                if (sysctl(mib, 3, &maxsockbuf, &rlen, NULL, 0) == -1)
623                    maxsockbuf = 1024;
624 
625 #if 1
626                /* XXXBSD: This is a hack to workaround mb_max/mb_max_adj
627                   problem.  It should be removed when kern.ipc.maxsockbuf
628                   will be real value. */
629                maxsockbuf = (maxsockbuf/5)*4;
630 #endif
631            }
632 #elif defined(__OpenBSD__)
633            maxsockbuf = SB_MAX;
634 #else
635            maxsockbuf = 64 * 1024;      /* XXX: NetBSD */
636 #endif
637 
638            bufsize = (int *)arg;
639            if (*bufsize > maxsockbuf) {
640                *bufsize = maxsockbuf;
641            }
642 
643            if (opt == SO_RCVBUF && *bufsize < 1024) {
644                 *bufsize = 1024;
645            }
646 
647         }
648     }
649 #endif
650 
651 #if defined(_ALLBSD_SOURCE) || defined(_AIX)
652     /*
653      * On Solaris, SO_REUSEADDR will allow multiple datagram
654      * sockets to bind to the same port. The network jck tests check
655      * for this "feature", so we need to emulate it by turning on
656      * SO_REUSEPORT as well for that combination.
657      */
658     if (level == SOL_SOCKET && opt == SO_REUSEADDR) {
659         int sotype;
660         socklen_t arglen;
661 
662         arglen = sizeof(sotype);
663         if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) < 0) {
664             return -1;
665         }
666 
667         if (sotype == SOCK_DGRAM) {
668             setsockopt(fd, level, SO_REUSEPORT, arg, len);
669         }
670     }
671 #endif
672 
673     return setsockopt(fd, level, opt, arg, len);
674 }
675 
676 /*
677  * Wrapper for bind system call - performs any necessary pre/post
678  * processing to deal with OS specific issues :-
679  *
680  * Linux allows a socket to bind to 127.0.0.255 which must be
681  * caught.
682  */
683 int
NET_Bind(int fd,SOCKETADDRESS * sa,int len)684 NET_Bind(int fd, SOCKETADDRESS *sa, int len)
685 {
686     int rv;
687     int arg, alen;
688 
689 #ifdef __linux__
690     /*
691      * ## get bugId for this issue - goes back to 1.2.2 port ##
692      * ## When IPv6 is enabled this will be an IPv4-mapped
693      * ## with family set to AF_INET6
694      */
695     if (sa->sa.sa_family == AF_INET) {
696         if ((ntohl(sa->sa4.sin_addr.s_addr) & 0x7f0000ff) == 0x7f0000ff) {
697             errno = EADDRNOTAVAIL;
698             return -1;
699         }
700     }
701 #endif
702 
703     rv = bind(fd, &sa->sa, len);
704 
705     return rv;
706 }
707 
708 /**
709  * Wrapper for poll with timeout on a single file descriptor.
710  *
711  * flags (defined in net_util_md.h can be any combination of
712  * NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
713  *
714  * The function will return when either the socket is ready for one
715  * of the specified operations or the timeout expired.
716  *
717  * It returns the time left from the timeout (possibly 0), or -1 if it expired.
718  */
719 
720 jint
NET_Wait(JNIEnv * env,jint fd,jint flags,jint timeout)721 NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
722 {
723     jlong prevNanoTime = JVM_NanoTime(env, 0);
724     jlong nanoTimeout = (jlong) timeout * NET_NSEC_PER_MSEC;
725     jint read_rv;
726 
727     while (1) {
728         jlong newNanoTime;
729         struct pollfd pfd;
730         pfd.fd = fd;
731         pfd.events = 0;
732         if (flags & NET_WAIT_READ)
733           pfd.events |= POLLIN;
734         if (flags & NET_WAIT_WRITE)
735           pfd.events |= POLLOUT;
736         if (flags & NET_WAIT_CONNECT)
737           pfd.events |= POLLOUT;
738 
739         errno = 0;
740         read_rv = NET_Poll(&pfd, 1, nanoTimeout / NET_NSEC_PER_MSEC);
741 
742         newNanoTime = JVM_NanoTime(env, 0);
743         nanoTimeout -= (newNanoTime - prevNanoTime);
744         if (nanoTimeout < NET_NSEC_PER_MSEC) {
745           return read_rv > 0 ? 0 : -1;
746         }
747         prevNanoTime = newNanoTime;
748 
749         if (read_rv > 0) {
750           break;
751         }
752       } /* while */
753     return (nanoTimeout / NET_NSEC_PER_MSEC);
754 }
755