1 /*
2  * Copyright (c) 1997, 2019, 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(__solaris__)
41 #include <inet/nd.h>
42 #include <limits.h>
43 #include <stropts.h>
44 #include <sys/filio.h>
45 #include <sys/sockio.h>
46 #endif
47 
48 #if defined(MACOSX)
49 #include <sys/sysctl.h>
50 #endif
51 
52 #ifdef __OpenBSD__
53 #include <sys/socketvar.h>
54 #endif
55 
56 #include "jvm.h"
57 #include "net_util.h"
58 
59 #include "java_net_SocketOptions.h"
60 #include "java_net_InetAddress.h"
61 
62 #if defined(__linux__) && !defined(IPV6_FLOWINFO_SEND)
63 #define IPV6_FLOWINFO_SEND      33
64 #endif
65 
66 #if defined(__solaris__) && !defined(MAXINT)
67 #define MAXINT INT_MAX
68 #endif
69 
70 /*
71  * EXCLBIND socket options only on Solaris
72  */
73 #if defined(__solaris__) && !defined(TCP_EXCLBIND)
74 #define TCP_EXCLBIND            0x21
75 #endif
76 #if defined(__solaris__) && !defined(UDP_EXCLBIND)
77 #define UDP_EXCLBIND            0x0101
78 #endif
79 
setDefaultScopeID(JNIEnv * env,struct sockaddr * him)80 void setDefaultScopeID(JNIEnv *env, struct sockaddr *him)
81 {
82 #ifdef _ALLBSD_SOURCE
83     static jclass ni_class = NULL;
84     static jfieldID ni_defaultIndexID;
85     if (ni_class == NULL) {
86         jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
87         CHECK_NULL(c);
88         c = (*env)->NewGlobalRef(env, c);
89         CHECK_NULL(c);
90         ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
91         CHECK_NULL(ni_defaultIndexID);
92         ni_class = c;
93     }
94     int defaultIndex;
95     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)him;
96     if (sin6->sin6_family == AF_INET6 && (sin6->sin6_scope_id == 0) &&
97         (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
98          IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))) {
99         defaultIndex = (*env)->GetStaticIntField(env, ni_class,
100                                                  ni_defaultIndexID);
101         sin6->sin6_scope_id = defaultIndex;
102     }
103 #endif
104 }
105 
getDefaultScopeID(JNIEnv * env)106 int getDefaultScopeID(JNIEnv *env) {
107     int defaultIndex = 0;
108     static jclass ni_class = NULL;
109     static jfieldID ni_defaultIndexID;
110     if (ni_class == NULL) {
111         jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
112         CHECK_NULL_RETURN(c, 0);
113         c = (*env)->NewGlobalRef(env, c);
114         CHECK_NULL_RETURN(c, 0);
115         ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
116         CHECK_NULL_RETURN(ni_defaultIndexID, 0);
117         ni_class = c;
118     }
119     defaultIndex = (*env)->GetStaticIntField(env, ni_class,
120                                              ni_defaultIndexID);
121     return defaultIndex;
122 }
123 
124 #define RESTARTABLE(_cmd, _result) do { \
125     do { \
126         _result = _cmd; \
127     } while((_result == -1) && (errno == EINTR)); \
128 } while(0)
129 
NET_SocketAvailable(int s,int * pbytes)130 int NET_SocketAvailable(int s, int *pbytes) {
131     int result;
132     RESTARTABLE(ioctl(s, FIONREAD, pbytes), result);
133     return result;
134 }
135 
136 #ifdef __solaris__
137 static int init_tcp_max_buf, init_udp_max_buf;
138 static int tcp_max_buf;
139 static int udp_max_buf;
140 static int useExclBind = 0;
141 
142 /*
143  * Get the specified parameter from the specified driver. The value
144  * of the parameter is assumed to be an 'int'. If the parameter
145  * cannot be obtained return -1
146  */
net_getParam(char * driver,char * param)147 int net_getParam(char *driver, char *param)
148 {
149     struct strioctl stri;
150     char buf [64];
151     int s;
152     int value;
153 
154     s = open (driver, O_RDWR);
155     if (s < 0) {
156         return -1;
157     }
158     strncpy (buf, param, sizeof(buf));
159     stri.ic_cmd = ND_GET;
160     stri.ic_timout = 0;
161     stri.ic_dp = buf;
162     stri.ic_len = sizeof(buf);
163     if (ioctl (s, I_STR, &stri) < 0) {
164         value = -1;
165     } else {
166         value = atoi(buf);
167     }
168     close (s);
169     return value;
170 }
171 
172 /*
173  * Iterative way to find the max value that SO_SNDBUF or SO_RCVBUF
174  * for Solaris versions that do not support the ioctl() in net_getParam().
175  * Ugly, but only called once (for each sotype).
176  *
177  * As an optimization, we make a guess using the default values for Solaris
178  * assuming they haven't been modified with ndd.
179  */
180 
181 #define MAX_TCP_GUESS 1024 * 1024
182 #define MAX_UDP_GUESS 2 * 1024 * 1024
183 
184 #define FAIL_IF_NOT_ENOBUFS if (errno != ENOBUFS) return -1
185 
findMaxBuf(int fd,int opt,int sotype)186 static int findMaxBuf(int fd, int opt, int sotype) {
187     int a = 0;
188     int b = MAXINT;
189     int initial_guess;
190     int limit = -1;
191 
192     if (sotype == SOCK_DGRAM) {
193         initial_guess = MAX_UDP_GUESS;
194     } else {
195         initial_guess = MAX_TCP_GUESS;
196     }
197 
198     if (setsockopt(fd, SOL_SOCKET, opt, &initial_guess, sizeof(int)) == 0) {
199         initial_guess++;
200         if (setsockopt(fd, SOL_SOCKET, opt, &initial_guess,sizeof(int)) < 0) {
201             FAIL_IF_NOT_ENOBUFS;
202             return initial_guess - 1;
203         }
204         a = initial_guess;
205     } else {
206         FAIL_IF_NOT_ENOBUFS;
207         b = initial_guess - 1;
208     }
209     do {
210         int mid = a + (b-a)/2;
211         if (setsockopt(fd, SOL_SOCKET, opt, &mid, sizeof(int)) == 0) {
212             limit = mid;
213             a = mid + 1;
214         } else {
215             FAIL_IF_NOT_ENOBUFS;
216             b = mid - 1;
217         }
218     } while (b >= a);
219 
220     return limit;
221 }
222 #endif
223 
224 #ifdef __linux__
225 static int vinit = 0;
226 static int kernelV24 = 0;
227 static int vinit24 = 0;
228 
kernelIsV24()229 int kernelIsV24 () {
230     if (!vinit24) {
231         struct utsname sysinfo;
232         if (uname(&sysinfo) == 0) {
233             sysinfo.release[3] = '\0';
234             if (strcmp(sysinfo.release, "2.4") == 0) {
235                 kernelV24 = JNI_TRUE;
236             }
237         }
238         vinit24 = 1;
239     }
240     return kernelV24;
241 }
242 #endif
243 
244 void
NET_ThrowByNameWithLastError(JNIEnv * env,const char * name,const char * defaultDetail)245 NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
246                    const char *defaultDetail) {
247     JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);
248 }
249 
250 void
NET_ThrowCurrent(JNIEnv * env,char * msg)251 NET_ThrowCurrent(JNIEnv *env, char *msg) {
252     NET_ThrowNew(env, errno, msg);
253 }
254 
255 void
NET_ThrowNew(JNIEnv * env,int errorNumber,char * msg)256 NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {
257     char fullMsg[512];
258     if (!msg) {
259         msg = "no further information";
260     }
261     switch(errorNumber) {
262     case EBADF:
263         jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);
264         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
265         break;
266     case EINTR:
267         JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException", msg);
268         break;
269     default:
270         errno = errorNumber;
271         JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", msg);
272         break;
273     }
274 }
275 
276 
277 jfieldID
NET_GetFileDescriptorID(JNIEnv * env)278 NET_GetFileDescriptorID(JNIEnv *env)
279 {
280     jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
281     CHECK_NULL_RETURN(cls, NULL);
282     return (*env)->GetFieldID(env, cls, "fd", "I");
283 }
284 
IPv4_supported()285 jint  IPv4_supported()
286 {
287     int fd = socket(AF_INET, SOCK_STREAM, 0) ;
288     if (fd < 0) {
289         return JNI_FALSE;
290     }
291     close(fd);
292     return JNI_TRUE;
293 }
294 
295 #if defined(DONT_ENABLE_IPV6) || defined(__DragonFly__)
IPv6_supported()296 jint  IPv6_supported()
297 {
298     return JNI_FALSE;
299 }
300 
301 #else /* !DONT_ENABLE_IPV6 */
302 
IPv6_supported()303 jint  IPv6_supported()
304 {
305     int fd;
306     void *ipv6_fn;
307     SOCKETADDRESS sa;
308     socklen_t sa_len = sizeof(SOCKETADDRESS);
309 
310     fd = socket(AF_INET6, SOCK_STREAM, 0) ;
311     if (fd < 0) {
312         /*
313          *  TODO: We really cant tell since it may be an unrelated error
314          *  for now we will assume that AF_INET6 is not available
315          */
316         return JNI_FALSE;
317     }
318 
319     /*
320      * If fd 0 is a socket it means we may have been launched from inetd or
321      * xinetd. If it's a socket then check the family - if it's an
322      * IPv4 socket then we need to disable IPv6.
323      */
324     if (getsockname(0, &sa.sa, &sa_len) == 0) {
325         if (sa.sa.sa_family == AF_INET) {
326             close(fd);
327             return JNI_FALSE;
328         }
329     }
330 
331     /**
332      * Linux - check if any interface has an IPv6 address.
333      * Don't need to parse the line - we just need an indication.
334      */
335 #ifdef __linux__
336     {
337         FILE *fP = fopen("/proc/net/if_inet6", "r");
338         char buf[255];
339         char *bufP;
340 
341         if (fP == NULL) {
342             close(fd);
343             return JNI_FALSE;
344         }
345         bufP = fgets(buf, sizeof(buf), fP);
346         fclose(fP);
347         if (bufP == NULL) {
348             close(fd);
349             return JNI_FALSE;
350         }
351     }
352 #endif
353 
354     /**
355      * On Solaris 8 it's possible to create INET6 sockets even
356      * though IPv6 is not enabled on all interfaces. Thus we
357      * query the number of IPv6 addresses to verify that IPv6
358      * has been configured on at least one interface.
359      *
360      * On Linux it doesn't matter - if IPv6 is built-in the
361      * kernel then IPv6 addresses will be bound automatically
362      * to all interfaces.
363      */
364 #ifdef __solaris__
365 
366 #ifdef SIOCGLIFNUM
367     {
368         struct lifnum numifs;
369 
370         numifs.lifn_family = AF_INET6;
371         numifs.lifn_flags = 0;
372         if (ioctl(fd, SIOCGLIFNUM, (char *)&numifs) < 0) {
373             /**
374              * SIOCGLIFNUM failed - assume IPv6 not configured
375              */
376             close(fd);
377             return JNI_FALSE;
378         }
379         /**
380          * If no IPv6 addresses then return false. If count > 0
381          * it's possible that all IPv6 addresses are "down" but
382          * that's okay as they may be brought "up" while the
383          * VM is running.
384          */
385         if (numifs.lifn_count == 0) {
386             close(fd);
387             return JNI_FALSE;
388         }
389     }
390 #else
391     /* SIOCGLIFNUM not defined in build environment ??? */
392     close(fd);
393     return JNI_FALSE;
394 #endif
395 
396 #endif /* __solaris */
397 
398     /*
399      *  OK we may have the stack available in the kernel,
400      *  we should also check if the APIs are available.
401      */
402     ipv6_fn = JVM_FindLibraryEntry(RTLD_DEFAULT, "inet_pton");
403     close(fd);
404     if (ipv6_fn == NULL ) {
405         return JNI_FALSE;
406     } else {
407         return JNI_TRUE;
408     }
409 }
410 #endif /* DONT_ENABLE_IPV6 */
411 
reuseport_supported()412 jint reuseport_supported()
413 {
414     /* Do a simple dummy call, and try to figure out from that */
415     int one = 1;
416     int rv, s;
417     s = socket(PF_INET, SOCK_STREAM, 0);
418     if (s < 0) {
419         return JNI_FALSE;
420     }
421     rv = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void *)&one, sizeof(one));
422     if (rv != 0) {
423         rv = JNI_FALSE;
424     } else {
425         rv = JNI_TRUE;
426     }
427     close(s);
428     return rv;
429 }
430 
NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv * env,const char * hostname,int gai_error)431 void NET_ThrowUnknownHostExceptionWithGaiError(JNIEnv *env,
432                                                const char* hostname,
433                                                int gai_error)
434 {
435     int size;
436     char *buf;
437     const char *format = "%s: %s";
438     const char *error_string = gai_strerror(gai_error);
439     if (error_string == NULL)
440         error_string = "unknown error";
441 
442     size = strlen(format) + strlen(hostname) + strlen(error_string) + 2;
443     buf = (char *) malloc(size);
444     if (buf) {
445         jstring s;
446         sprintf(buf, format, hostname, error_string);
447         s = JNU_NewStringPlatform(env, buf);
448         if (s != NULL) {
449             jobject x = JNU_NewObjectByName(env,
450                                             "java/net/UnknownHostException",
451                                             "(Ljava/lang/String;)V", s);
452             if (x != NULL)
453                 (*env)->Throw(env, x);
454         }
455         free(buf);
456     }
457 }
458 
459 #if defined(_AIX)
460 
461 /* Initialize stubs for blocking I/O workarounds (see src/solaris/native/java/net/linux_close.c) */
462 extern void aix_close_init();
463 
platformInit()464 void platformInit () {
465     aix_close_init();
466 }
467 
468 #else
469 
platformInit()470 void platformInit () {}
471 
472 #endif
473 
parseExclusiveBindProperty(JNIEnv * env)474 void parseExclusiveBindProperty(JNIEnv *env) {
475 #ifdef __solaris__
476     jstring s, flagSet;
477     jclass iCls;
478     jmethodID mid;
479 
480     s = (*env)->NewStringUTF(env, "sun.net.useExclusiveBind");
481     CHECK_NULL(s);
482     iCls = (*env)->FindClass(env, "java/lang/System");
483     CHECK_NULL(iCls);
484     mid = (*env)->GetStaticMethodID(env, iCls, "getProperty",
485                 "(Ljava/lang/String;)Ljava/lang/String;");
486     CHECK_NULL(mid);
487     flagSet = (*env)->CallStaticObjectMethod(env, iCls, mid, s);
488     if (flagSet != NULL) {
489         useExclBind = 1;
490     }
491 #endif
492 }
493 
494 JNIEXPORT jint JNICALL
NET_EnableFastTcpLoopback(int fd)495 NET_EnableFastTcpLoopback(int fd) {
496     return 0;
497 }
498 
499 /**
500  * See net_util.h for documentation
501  */
502 JNIEXPORT int JNICALL
NET_InetAddressToSockaddr(JNIEnv * env,jobject iaObj,int port,SOCKETADDRESS * sa,int * len,jboolean v4MappedAddress)503 NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,
504                           SOCKETADDRESS *sa, int *len,
505                           jboolean v4MappedAddress)
506 {
507     jint family = getInetAddress_family(env, iaObj);
508     JNU_CHECK_EXCEPTION_RETURN(env, -1);
509     memset((char *)sa, 0, sizeof(SOCKETADDRESS));
510 
511     if (ipv6_available() &&
512         !(family == java_net_InetAddress_IPv4 &&
513           v4MappedAddress == JNI_FALSE))
514     {
515         jbyte caddr[16];
516         jint address;
517 
518         if (family == java_net_InetAddress_IPv4) {
519             // convert to IPv4-mapped address
520             memset((char *)caddr, 0, 16);
521             address = getInetAddress_addr(env, iaObj);
522             JNU_CHECK_EXCEPTION_RETURN(env, -1);
523             if (address == INADDR_ANY) {
524                 /* we would always prefer IPv6 wildcard address
525                  * caddr[10] = 0xff;
526                  * caddr[11] = 0xff; */
527             } else {
528                 caddr[10] = 0xff;
529                 caddr[11] = 0xff;
530                 caddr[12] = ((address >> 24) & 0xff);
531                 caddr[13] = ((address >> 16) & 0xff);
532                 caddr[14] = ((address >> 8) & 0xff);
533                 caddr[15] = (address & 0xff);
534             }
535         } else {
536             getInet6Address_ipaddress(env, iaObj, (char *)caddr);
537         }
538         sa->sa6.sin6_port = htons(port);
539         memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));
540         sa->sa6.sin6_family = AF_INET6;
541         if (len != NULL) {
542             *len = sizeof(struct sockaddr_in6);
543         }
544 
545         /* handle scope_id */
546         if (family != java_net_InetAddress_IPv4) {
547             if (ia6_scopeidID) {
548                 sa->sa6.sin6_scope_id = getInet6Address_scopeid(env, iaObj);
549             }
550         }
551     } else {
552         jint address;
553         if (family != java_net_InetAddress_IPv4) {
554             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
555             return -1;
556         }
557         address = getInetAddress_addr(env, iaObj);
558         JNU_CHECK_EXCEPTION_RETURN(env, -1);
559         sa->sa4.sin_port = htons(port);
560         sa->sa4.sin_addr.s_addr = htonl(address);
561         sa->sa4.sin_family = AF_INET;
562         if (len != NULL) {
563             *len = sizeof(struct sockaddr_in);
564         }
565     }
566     return 0;
567 }
568 
569 void
NET_SetTrafficClass(SOCKETADDRESS * sa,int trafficClass)570 NET_SetTrafficClass(SOCKETADDRESS *sa, int trafficClass) {
571     if (sa->sa.sa_family == AF_INET6) {
572         sa->sa6.sin6_flowinfo = htonl((trafficClass & 0xff) << 20);
573     }
574 }
575 
576 int
NET_IsIPv4Mapped(jbyte * caddr)577 NET_IsIPv4Mapped(jbyte* caddr) {
578     int i;
579     for (i = 0; i < 10; i++) {
580         if (caddr[i] != 0x00) {
581             return 0; /* false */
582         }
583     }
584 
585     if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
586         return 1; /* true */
587     }
588     return 0; /* false */
589 }
590 
591 int
NET_IPv4MappedToIPv4(jbyte * caddr)592 NET_IPv4MappedToIPv4(jbyte* caddr) {
593     return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
594         | (caddr[15] & 0xff);
595 }
596 
597 int
NET_IsEqual(jbyte * caddr1,jbyte * caddr2)598 NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
599     int i;
600     for (i = 0; i < 16; i++) {
601         if (caddr1[i] != caddr2[i]) {
602             return 0; /* false */
603         }
604     }
605     return 1;
606 }
607 
NET_IsZeroAddr(jbyte * caddr)608 int NET_IsZeroAddr(jbyte* caddr) {
609     int i;
610     for (i = 0; i < 16; i++) {
611         if (caddr[i] != 0) {
612             return 0;
613         }
614     }
615     return 1;
616 }
617 
618 /*
619  * Map the Java level socket option to the platform specific
620  * level and option name.
621  */
622 int
NET_MapSocketOption(jint cmd,int * level,int * optname)623 NET_MapSocketOption(jint cmd, int *level, int *optname) {
624     static struct {
625         jint cmd;
626         int level;
627         int optname;
628     } const opts[] = {
629         { java_net_SocketOptions_TCP_NODELAY,           IPPROTO_TCP,    TCP_NODELAY },
630         { java_net_SocketOptions_SO_OOBINLINE,          SOL_SOCKET,     SO_OOBINLINE },
631         { java_net_SocketOptions_SO_LINGER,             SOL_SOCKET,     SO_LINGER },
632         { java_net_SocketOptions_SO_SNDBUF,             SOL_SOCKET,     SO_SNDBUF },
633         { java_net_SocketOptions_SO_RCVBUF,             SOL_SOCKET,     SO_RCVBUF },
634         { java_net_SocketOptions_SO_KEEPALIVE,          SOL_SOCKET,     SO_KEEPALIVE },
635         { java_net_SocketOptions_SO_REUSEADDR,          SOL_SOCKET,     SO_REUSEADDR },
636         { java_net_SocketOptions_SO_REUSEPORT,          SOL_SOCKET,     SO_REUSEPORT },
637         { java_net_SocketOptions_SO_BROADCAST,          SOL_SOCKET,     SO_BROADCAST },
638         { java_net_SocketOptions_IP_TOS,                IPPROTO_IP,     IP_TOS },
639         { java_net_SocketOptions_IP_MULTICAST_IF,       IPPROTO_IP,     IP_MULTICAST_IF },
640         { java_net_SocketOptions_IP_MULTICAST_IF2,      IPPROTO_IP,     IP_MULTICAST_IF },
641         { java_net_SocketOptions_IP_MULTICAST_LOOP,     IPPROTO_IP,     IP_MULTICAST_LOOP },
642     };
643 
644     int i;
645 
646     if (ipv6_available()) {
647         switch (cmd) {
648             // Different multicast options if IPv6 is enabled
649             case java_net_SocketOptions_IP_MULTICAST_IF:
650             case java_net_SocketOptions_IP_MULTICAST_IF2:
651                 *level = IPPROTO_IPV6;
652                 *optname = IPV6_MULTICAST_IF;
653                 return 0;
654 
655             case java_net_SocketOptions_IP_MULTICAST_LOOP:
656                 *level = IPPROTO_IPV6;
657                 *optname = IPV6_MULTICAST_LOOP;
658                 return 0;
659 #if (defined(__solaris__) || defined(MACOSX))
660             // Map IP_TOS request to IPV6_TCLASS
661             case java_net_SocketOptions_IP_TOS:
662                 *level = IPPROTO_IPV6;
663                 *optname = IPV6_TCLASS;
664                 return 0;
665 #endif
666         }
667     }
668 
669     /*
670      * Map the Java level option to the native level
671      */
672     for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
673         if (cmd == opts[i].cmd) {
674             *level = opts[i].level;
675             *optname = opts[i].optname;
676             return 0;
677         }
678     }
679 
680     /* not found */
681     return -1;
682 }
683 
684 /*
685  * Wrapper for getsockopt system routine - does any necessary
686  * pre/post processing to deal with OS specific oddities :-
687  *
688  * On Linux the SO_SNDBUF/SO_RCVBUF values must be post-processed
689  * to compensate for an incorrect value returned by the kernel.
690  */
691 int
NET_GetSockOpt(int fd,int level,int opt,void * result,int * len)692 NET_GetSockOpt(int fd, int level, int opt, void *result,
693                int *len)
694 {
695     int rv;
696     socklen_t socklen = *len;
697 
698     rv = getsockopt(fd, level, opt, result, &socklen);
699     *len = socklen;
700 
701     if (rv < 0) {
702         return rv;
703     }
704 
705 #ifdef __linux__
706     /*
707      * On Linux SO_SNDBUF/SO_RCVBUF aren't symmetric. This
708      * stems from additional socket structures in the send
709      * and receive buffers.
710      */
711     if ((level == SOL_SOCKET) && ((opt == SO_SNDBUF)
712                                   || (opt == SO_RCVBUF))) {
713         int n = *((int *)result);
714         n /= 2;
715         *((int *)result) = n;
716     }
717 #endif
718 
719 /* Workaround for Mac OS treating linger value as
720  *  signed integer
721  */
722 #ifdef MACOSX
723     if (level == SOL_SOCKET && opt == SO_LINGER) {
724         struct linger* to_cast = (struct linger*)result;
725         to_cast->l_linger = (unsigned short)to_cast->l_linger;
726     }
727 #endif
728     return rv;
729 }
730 
731 /*
732  * Wrapper for setsockopt system routine - performs any
733  * necessary pre/post processing to deal with OS specific
734  * issue :-
735  *
736  * On Solaris need to limit the suggested value for SO_SNDBUF
737  * and SO_RCVBUF to the kernel configured limit
738  *
739  * For IP_TOS socket option need to mask off bits as this
740  * aren't automatically masked by the kernel and results in
741  * an error.
742  */
743 int
NET_SetSockOpt(int fd,int level,int opt,const void * arg,int len)744 NET_SetSockOpt(int fd, int level, int  opt, const void *arg,
745                int len)
746 {
747 
748 #ifndef IPTOS_TOS_MASK
749 #define IPTOS_TOS_MASK 0x1e
750 #endif
751 #ifndef IPTOS_PREC_MASK
752 #define IPTOS_PREC_MASK 0xe0
753 #endif
754 
755 #if defined(_ALLBSD_SOURCE)
756 #if defined(KIPC_MAXSOCKBUF)
757     int mib[3];
758     size_t rlen;
759 #endif
760 
761     int *bufsize;
762 
763 #ifdef __APPLE__
764     static int maxsockbuf = -1;
765 #else
766     static long maxsockbuf = -1;
767 #endif
768 #endif
769 
770     /*
771      * IPPROTO/IP_TOS :-
772      * 1. IPv6 on Solaris/Mac OS:
773      *    Set the TOS OR Traffic Class value to cater for
774      *    IPv6 and IPv4 scenarios.
775      * 2. IPv6 on Linux: By default Linux ignores flowinfo
776      *    field so enable IPV6_FLOWINFO_SEND so that flowinfo
777      *    will be examined. We also set the IPv4 TOS option in this case.
778      * 3. IPv4: set socket option based on ToS and Precedence
779      *    fields (otherwise get invalid argument)
780      */
781     if (level == IPPROTO_IP && opt == IP_TOS) {
782         int *iptos;
783 
784 #if defined(__linux__)
785         if (ipv6_available()) {
786             int optval = 1;
787             if (setsockopt(fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
788                            (void *)&optval, sizeof(optval)) < 0) {
789                 return -1;
790             }
791            /*
792             * Let's also set the IPV6_TCLASS flag.
793             * Linux appears to allow both IP_TOS and IPV6_TCLASS to be set
794             * This helps in mixed environments where IPv4 and IPv6 sockets
795             * are connecting.
796             */
797            if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
798                            arg, len) < 0) {
799                 return -1;
800             }
801         }
802 #endif
803 
804         iptos = (int *)arg;
805         *iptos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
806     }
807 
808     /*
809      * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On Solaris we may need to clamp
810      * the value when it exceeds the system limit.
811      */
812 #ifdef __solaris__
813     if (level == SOL_SOCKET) {
814         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
815             int sotype=0;
816             socklen_t arglen;
817             int *bufsize, maxbuf;
818             int ret;
819 
820             /* Attempt with the original size */
821             ret = setsockopt(fd, level, opt, arg, len);
822             if ((ret == 0) || (ret == -1 && errno != ENOBUFS))
823                 return ret;
824 
825             /* Exceeded system limit so clamp and retry */
826 
827             arglen = sizeof(sotype);
828             if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype,
829                            &arglen) < 0) {
830                 return -1;
831             }
832 
833             /*
834              * We try to get tcp_maxbuf (and udp_max_buf) using
835              * an ioctl() that isn't available on all versions of Solaris.
836              * If that fails, we use the search algorithm in findMaxBuf()
837              */
838             if (!init_tcp_max_buf && sotype == SOCK_STREAM) {
839                 tcp_max_buf = net_getParam("/dev/tcp", "tcp_max_buf");
840                 if (tcp_max_buf == -1) {
841                     tcp_max_buf = findMaxBuf(fd, opt, SOCK_STREAM);
842                     if (tcp_max_buf == -1) {
843                         return -1;
844                     }
845                 }
846                 init_tcp_max_buf = 1;
847             } else if (!init_udp_max_buf && sotype == SOCK_DGRAM) {
848                 udp_max_buf = net_getParam("/dev/udp", "udp_max_buf");
849                 if (udp_max_buf == -1) {
850                     udp_max_buf = findMaxBuf(fd, opt, SOCK_DGRAM);
851                     if (udp_max_buf == -1) {
852                         return -1;
853                     }
854                 }
855                 init_udp_max_buf = 1;
856             }
857 
858             maxbuf = (sotype == SOCK_STREAM) ? tcp_max_buf : udp_max_buf;
859             bufsize = (int *)arg;
860             if (*bufsize > maxbuf) {
861                 *bufsize = maxbuf;
862             }
863         }
864     }
865 #endif
866 
867 #ifdef _AIX
868     if (level == SOL_SOCKET) {
869         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
870             /*
871              * Just try to set the requested size. If it fails we will leave the
872              * socket option as is. Setting the buffer size means only a hint in
873              * the jse2/java software layer, see javadoc. In the previous
874              * solution the buffer has always been truncated to a length of
875              * 0x100000 Byte, even if the technical limit has not been reached.
876              * This kind of absolute truncation was unexpected in the jck tests.
877              */
878             int ret = setsockopt(fd, level, opt, arg, len);
879             if ((ret == 0) || (ret == -1 && errno == ENOBUFS)) {
880                 // Accept failure because of insufficient buffer memory resources.
881                 return 0;
882             } else {
883                 // Deliver all other kinds of errors.
884                 return ret;
885             }
886         }
887     }
888 #endif
889 
890     /*
891      * On Linux the receive buffer is used for both socket
892      * structures and the packet payload. The implication
893      * is that if SO_RCVBUF is too small then small packets
894      * must be discarded.
895      */
896 #ifdef __linux__
897     if (level == SOL_SOCKET && opt == SO_RCVBUF) {
898         int *bufsize = (int *)arg;
899         if (*bufsize < 1024) {
900             *bufsize = 1024;
901         }
902     }
903 #endif
904 
905 #if defined(_ALLBSD_SOURCE)
906     /*
907      * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On FreeBSD need to
908      * ensure that value is <= kern.ipc.maxsockbuf as otherwise we get
909      * an ENOBUFS error.
910      */
911     if (level == SOL_SOCKET) {
912         if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
913 #ifdef KIPC_MAXSOCKBUF
914             if (maxsockbuf == -1) {
915                mib[0] = CTL_KERN;
916                mib[1] = KERN_IPC;
917                mib[2] = KIPC_MAXSOCKBUF;
918                rlen = sizeof(maxsockbuf);
919                if (sysctl(mib, 3, &maxsockbuf, &rlen, NULL, 0) == -1)
920                    maxsockbuf = 1024;
921 
922 #if 1
923                /* XXXBSD: This is a hack to workaround mb_max/mb_max_adj
924                   problem.  It should be removed when kern.ipc.maxsockbuf
925                   will be real value. */
926                maxsockbuf = (maxsockbuf/5)*4;
927 #endif
928            }
929 #elif defined(__OpenBSD__)
930            maxsockbuf = SB_MAX;
931 #else
932            maxsockbuf = 64 * 1024;      /* XXX: NetBSD */
933 #endif
934 
935            bufsize = (int *)arg;
936            if (*bufsize > maxsockbuf) {
937                *bufsize = maxsockbuf;
938            }
939 
940            if (opt == SO_RCVBUF && *bufsize < 1024) {
941                 *bufsize = 1024;
942            }
943 
944         }
945     }
946 #endif
947 
948 #if defined(_ALLBSD_SOURCE) || defined(_AIX)
949     /*
950      * On Solaris, SO_REUSEADDR will allow multiple datagram
951      * sockets to bind to the same port. The network jck tests check
952      * for this "feature", so we need to emulate it by turning on
953      * SO_REUSEPORT as well for that combination.
954      */
955     if (level == SOL_SOCKET && opt == SO_REUSEADDR) {
956         int sotype;
957         socklen_t arglen;
958 
959         arglen = sizeof(sotype);
960         if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) < 0) {
961             return -1;
962         }
963 
964         if (sotype == SOCK_DGRAM) {
965             setsockopt(fd, level, SO_REUSEPORT, arg, len);
966         }
967     }
968 #endif
969 
970     return setsockopt(fd, level, opt, arg, len);
971 }
972 
973 /*
974  * Wrapper for bind system call - performs any necessary pre/post
975  * processing to deal with OS specific issues :-
976  *
977  * Linux allows a socket to bind to 127.0.0.255 which must be
978  * caught.
979  *
980  * On Solaris with IPv6 enabled we must use an exclusive
981  * bind to guarantee a unique port number across the IPv4 and
982  * IPv6 port spaces.
983  *
984  */
985 int
NET_Bind(int fd,SOCKETADDRESS * sa,int len)986 NET_Bind(int fd, SOCKETADDRESS *sa, int len)
987 {
988 #if defined(__solaris__)
989     int level = -1;
990     int exclbind = -1;
991 #endif
992     int rv;
993     int arg, alen;
994 
995 #ifdef __linux__
996     /*
997      * ## get bugId for this issue - goes back to 1.2.2 port ##
998      * ## When IPv6 is enabled this will be an IPv4-mapped
999      * ## with family set to AF_INET6
1000      */
1001     if (sa->sa.sa_family == AF_INET) {
1002         if ((ntohl(sa->sa4.sin_addr.s_addr) & 0x7f0000ff) == 0x7f0000ff) {
1003             errno = EADDRNOTAVAIL;
1004             return -1;
1005         }
1006     }
1007 #endif
1008 
1009 #if defined(__solaris__)
1010     /*
1011      * Solaris has separate IPv4 and IPv6 port spaces so we
1012      * use an exclusive bind when SO_REUSEADDR is not used to
1013      * give the illusion of a unified port space.
1014      * This also avoids problems with IPv6 sockets connecting
1015      * to IPv4 mapped addresses whereby the socket conversion
1016      * results in a late bind that fails because the
1017      * corresponding IPv4 port is in use.
1018      */
1019     alen = sizeof(arg);
1020 
1021     if (useExclBind ||
1022         getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&arg, &alen) == 0)
1023     {
1024         if (useExclBind || arg == 0) {
1025             /*
1026              * SO_REUSEADDR is disabled or sun.net.useExclusiveBind
1027              * property is true so enable TCP_EXCLBIND or
1028              * UDP_EXCLBIND
1029              */
1030             alen = sizeof(arg);
1031             if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&arg, &alen) == 0)
1032             {
1033                 if (arg == SOCK_STREAM) {
1034                     level = IPPROTO_TCP;
1035                     exclbind = TCP_EXCLBIND;
1036                 } else {
1037                     level = IPPROTO_UDP;
1038                     exclbind = UDP_EXCLBIND;
1039                 }
1040             }
1041 
1042             arg = 1;
1043             setsockopt(fd, level, exclbind, (char *)&arg, sizeof(arg));
1044         }
1045     }
1046 
1047 #endif
1048 
1049     rv = bind(fd, &sa->sa, len);
1050 
1051 #if defined(__solaris__)
1052     if (rv < 0) {
1053         int en = errno;
1054         /* Restore *_EXCLBIND if the bind fails */
1055         if (exclbind != -1) {
1056             int arg = 0;
1057             setsockopt(fd, level, exclbind, (char *)&arg,
1058                        sizeof(arg));
1059         }
1060         errno = en;
1061     }
1062 #endif
1063 
1064     return rv;
1065 }
1066 
1067 /**
1068  * Wrapper for poll with timeout on a single file descriptor.
1069  *
1070  * flags (defined in net_util_md.h can be any combination of
1071  * NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
1072  *
1073  * The function will return when either the socket is ready for one
1074  * of the specified operations or the timeout expired.
1075  *
1076  * It returns the time left from the timeout (possibly 0), or -1 if it expired.
1077  */
1078 
1079 jint
NET_Wait(JNIEnv * env,jint fd,jint flags,jint timeout)1080 NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
1081 {
1082     jlong prevNanoTime = JVM_NanoTime(env, 0);
1083     jlong nanoTimeout = (jlong) timeout * NET_NSEC_PER_MSEC;
1084     jint read_rv;
1085 
1086     while (1) {
1087         jlong newNanoTime;
1088         struct pollfd pfd;
1089         pfd.fd = fd;
1090         pfd.events = 0;
1091         if (flags & NET_WAIT_READ)
1092           pfd.events |= POLLIN;
1093         if (flags & NET_WAIT_WRITE)
1094           pfd.events |= POLLOUT;
1095         if (flags & NET_WAIT_CONNECT)
1096           pfd.events |= POLLOUT;
1097 
1098         errno = 0;
1099         read_rv = NET_Poll(&pfd, 1, nanoTimeout / NET_NSEC_PER_MSEC);
1100 
1101         newNanoTime = JVM_NanoTime(env, 0);
1102         nanoTimeout -= (newNanoTime - prevNanoTime);
1103         if (nanoTimeout < NET_NSEC_PER_MSEC) {
1104           return read_rv > 0 ? 0 : -1;
1105         }
1106         prevNanoTime = newNanoTime;
1107 
1108         if (read_rv > 0) {
1109           break;
1110         }
1111       } /* while */
1112     return (nanoTimeout / NET_NSEC_PER_MSEC);
1113 }
1114