blob: 83218899d4296a7525d945a41c806dadc9e92beb [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 1997-2007 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26#include <errno.h>
27#include <string.h>
28#include <sys/types.h>
29#include <sys/socket.h>
30#include <netinet/tcp.h> /* Defines TCP_NODELAY, needed for 2.6 */
31#include <netinet/in.h>
32#include <net/if.h>
33#include <netdb.h>
34#include <stdlib.h>
35#include <dlfcn.h>
36
37#ifdef __solaris__
38#include <sys/sockio.h>
39#include <stropts.h>
40#include <inet/nd.h>
41#endif
42
43#ifdef __linux__
44#include <arpa/inet.h>
45#include <net/route.h>
46#include <sys/utsname.h>
47
48#ifndef IPV6_FLOWINFO_SEND
49#define IPV6_FLOWINFO_SEND 33
50#endif
51
52#endif
53
54#include "jni_util.h"
55#include "jvm.h"
56#include "net_util.h"
57
58#include "java_net_SocketOptions.h"
59
60/* needed from libsocket on Solaris 8 */
61
62getaddrinfo_f getaddrinfo_ptr = NULL;
63freeaddrinfo_f freeaddrinfo_ptr = NULL;
64getnameinfo_f getnameinfo_ptr = NULL;
65
66/*
67 * EXCLBIND socket options only on Solaris 8 & 9.
68 */
69#if defined(__solaris__) && !defined(TCP_EXCLBIND)
70#define TCP_EXCLBIND 0x21
71#endif
72#if defined(__solaris__) && !defined(UDP_EXCLBIND)
73#define UDP_EXCLBIND 0x0101
74#endif
75
76#ifdef __solaris__
77static int init_max_buf;
78static int tcp_max_buf;
79static int udp_max_buf;
80
81/*
82 * Get the specified parameter from the specified driver. The value
83 * of the parameter is assumed to be an 'int'. If the parameter
84 * cannot be obtained return the specified default value.
85 */
86static int
87getParam(char *driver, char *param, int dflt)
88{
89 struct strioctl stri;
90 char buf [64];
91 int s;
92 int value;
93
94 s = open (driver, O_RDWR);
95 if (s < 0) {
96 return dflt;
97 }
98 strncpy (buf, param, sizeof(buf));
99 stri.ic_cmd = ND_GET;
100 stri.ic_timout = 0;
101 stri.ic_dp = buf;
102 stri.ic_len = sizeof(buf);
103 if (ioctl (s, I_STR, &stri) < 0) {
104 value = dflt;
105 } else {
106 value = atoi(buf);
107 }
108 close (s);
109 return value;
110}
111#endif
112
113#ifdef __linux__
114static int kernelV22 = 0;
115static int vinit = 0;
116
117int kernelIsV22 () {
118 if (!vinit) {
119 struct utsname sysinfo;
120 if (uname(&sysinfo) == 0) {
121 sysinfo.release[3] = '\0';
122 if (strcmp(sysinfo.release, "2.2") == 0) {
123 kernelV22 = JNI_TRUE;
124 }
125 }
126 vinit = 1;
127 }
128 return kernelV22;
129}
130
131static int kernelV24 = 0;
132static int vinit24 = 0;
133
134int kernelIsV24 () {
135 if (!vinit24) {
136 struct utsname sysinfo;
137 if (uname(&sysinfo) == 0) {
138 sysinfo.release[3] = '\0';
139 if (strcmp(sysinfo.release, "2.4") == 0) {
140 kernelV24 = JNI_TRUE;
141 }
142 }
143 vinit24 = 1;
144 }
145 return kernelV24;
146}
147
148int getScopeID (struct sockaddr *him) {
149 struct sockaddr_in6 *hext = (struct sockaddr_in6 *)him;
150 if (kernelIsV22()) {
151 return 0;
152 }
153 return hext->sin6_scope_id;
154}
155
156int cmpScopeID (unsigned int scope, struct sockaddr *him) {
157 struct sockaddr_in6 *hext = (struct sockaddr_in6 *)him;
158 if (kernelIsV22()) {
159 return 1; /* scope is ignored for comparison in 2.2 kernel */
160 }
161 return hext->sin6_scope_id == scope;
162}
163
164#else
165
166int getScopeID (struct sockaddr *him) {
167 struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
168 return him6->sin6_scope_id;
169}
170
171int cmpScopeID (unsigned int scope, struct sockaddr *him) {
172 struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
173 return him6->sin6_scope_id == scope;
174}
175
176#endif
177
178
179void
180NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
181 const char *defaultDetail) {
182 char errmsg[255];
183 sprintf(errmsg, "errno: %d, error: %s\n", errno, defaultDetail);
184 JNU_ThrowByNameWithLastError(env, name, errmsg);
185}
186
187void
188NET_ThrowCurrent(JNIEnv *env, char *msg) {
189 NET_ThrowNew(env, errno, msg);
190}
191
192void
193NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {
194 char fullMsg[512];
195 if (!msg) {
196 msg = "no further information";
197 }
198 switch(errorNumber) {
199 case EBADF:
200 jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);
201 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
202 break;
203 case EINTR:
204 JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException", msg);
205 break;
206 default:
207 errno = errorNumber;
208 JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", msg);
209 break;
210 }
211}
212
213
214jfieldID
215NET_GetFileDescriptorID(JNIEnv *env)
216{
217 jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
218 CHECK_NULL_RETURN(cls, NULL);
219 return (*env)->GetFieldID(env, cls, "fd", "I");
220}
221
222jint IPv6_supported()
223{
224#ifndef AF_INET6
225 return JNI_FALSE;
226#endif
227
228#ifdef AF_INET6
229 int fd;
230 void *ipv6_fn;
231 SOCKADDR sa;
232 int sa_len = sizeof(sa);
233
234 fd = JVM_Socket(AF_INET6, SOCK_STREAM, 0) ;
235 if (fd < 0) {
236 /*
237 * TODO: We really cant tell since it may be an unrelated error
238 * for now we will assume that AF_INET6 is not available
239 */
240 return JNI_FALSE;
241 }
242
243 /*
244 * If fd 0 is a socket it means we've been launched from inetd or
245 * xinetd. If it's a socket then check the family - if it's an
246 * IPv4 socket then we need to disable IPv6.
247 */
248 if (getsockname(0, (struct sockaddr *)&sa, &sa_len) == 0) {
249 struct sockaddr *saP = (struct sockaddr *)&sa;
250 if (saP->sa_family != AF_INET6) {
251 return JNI_FALSE;
252 }
253 }
254
255 /**
256 * Linux - check if any interface has an IPv6 address.
257 * Don't need to parse the line - we just need an indication.
258 */
259#ifdef __linux__
260 {
261 FILE *fP = fopen("/proc/net/if_inet6", "r");
262 char buf[255];
263 char *bufP;
264
265 if (fP == NULL) {
266 close(fd);
267 return JNI_FALSE;
268 }
269 bufP = fgets(buf, sizeof(buf), fP);
270 fclose(fP);
271 if (bufP == NULL) {
272 close(fd);
273 return JNI_FALSE;
274 }
275 }
276#endif
277
278 /**
279 * On Solaris 8 it's possible to create INET6 sockets even
280 * though IPv6 is not enabled on all interfaces. Thus we
281 * query the number of IPv6 addresses to verify that IPv6
282 * has been configured on at least one interface.
283 *
284 * On Linux it doesn't matter - if IPv6 is built-in the
285 * kernel then IPv6 addresses will be bound automatically
286 * to all interfaces.
287 */
288#ifdef __solaris__
289
290#ifdef SIOCGLIFNUM
291 {
292 struct lifnum numifs;
293
294 numifs.lifn_family = AF_INET6;
295 numifs.lifn_flags = 0;
296 if (ioctl(fd, SIOCGLIFNUM, (char *)&numifs) < 0) {
297 /**
298 * SIOCGLIFNUM failed - assume IPv6 not configured
299 */
300 close(fd);
301 return JNI_FALSE;
302 }
303 /**
304 * If no IPv6 addresses then return false. If count > 0
305 * it's possible that all IPv6 addresses are "down" but
306 * that's okay as they may be brought "up" while the
307 * VM is running.
308 */
309 if (numifs.lifn_count == 0) {
310 close(fd);
311 return JNI_FALSE;
312 }
313 }
314#else
315 /* SIOCGLIFNUM not defined in build environment ??? */
316 close(fd);
317 return JNI_FALSE;
318#endif
319
320#endif /* __solaris */
321
322#endif /* AF_INET6 */
323
324 /*
325 * OK we may have the stack available in the kernel,
326 * we should also check if the APIs are available.
327 */
328 ipv6_fn = JVM_FindLibraryEntry(RTLD_DEFAULT, "inet_pton");
329 if (ipv6_fn == NULL ) {
330 close(fd);
331 return JNI_FALSE;
332 }
333
334 /*
335 * We've got the library, let's get the pointers to some
336 * IPV6 specific functions. We have to do that because, at least
337 * on Solaris we may build on a system without IPV6 networking
338 * libraries, therefore we can't have a hard link to these
339 * functions.
340 */
341 getaddrinfo_ptr = (getaddrinfo_f)
342 JVM_FindLibraryEntry(RTLD_DEFAULT, "getaddrinfo");
343
344 freeaddrinfo_ptr = (freeaddrinfo_f)
345 JVM_FindLibraryEntry(RTLD_DEFAULT, "freeaddrinfo");
346
347 getnameinfo_ptr = (getnameinfo_f)
348 JVM_FindLibraryEntry(RTLD_DEFAULT, "getnameinfo");
349
350 if (freeaddrinfo_ptr == NULL || getnameinfo_ptr == NULL) {
351 /* Wee need all 3 of them */
352 getaddrinfo_ptr = NULL;
353 }
354
355 close(fd);
356 return JNI_TRUE;
357}
358
359void
360NET_AllocSockaddr(struct sockaddr **him, int *len) {
361#ifdef AF_INET6
362 if (ipv6_available()) {
363 struct sockaddr_in6 *him6 = (struct sockaddr_in6*)malloc(sizeof(struct sockaddr_in6));
364 *him = (struct sockaddr*)him6;
365 *len = sizeof(struct sockaddr_in6);
366 } else
367#endif /* AF_INET6 */
368 {
369 struct sockaddr_in *him4 = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
370 *him = (struct sockaddr*)him4;
371 *len = sizeof(struct sockaddr_in);
372 }
373}
374
375#if defined(__linux__) && defined(AF_INET6)
376
377
378/* following code creates a list of addresses from the kernel
379 * routing table that are routed via the loopback address.
380 * We check all destination addresses against this table
381 * and override the scope_id field to use the relevant value for "lo"
382 * in order to work-around the Linux bug that prevents packets destined
383 * for certain local addresses from being sent via a physical interface.
384 */
385
386struct loopback_route {
387 struct in6_addr addr; /* destination address */
388 int plen; /* prefix length */
389};
390
391static struct loopback_route *loRoutes = 0;
392static int nRoutes = 0; /* number of routes */
393static int loRoutes_size = 16; /* initial size */
394static int lo_scope_id = 0;
395
396static void initLoopbackRoutes();
397
398void printAddr (struct in6_addr *addr) {
399 int i;
400 for (i=0; i<16; i++) {
401 printf ("%02x", addr->s6_addr[i]);
402 }
403 printf ("\n");
404}
405
406static jboolean needsLoopbackRoute (struct in6_addr* dest_addr) {
407 int byte_count;
408 int extra_bits, i;
409 struct loopback_route *ptr;
410
411 if (loRoutes == 0) {
412 initLoopbackRoutes();
413 }
414
415 for (ptr = loRoutes, i=0; i<nRoutes; i++, ptr++) {
416 struct in6_addr *target_addr=&ptr->addr;
417 int dest_plen = ptr->plen;
418 byte_count = dest_plen >> 3;
419 extra_bits = dest_plen & 0x3;
420
421 if (byte_count > 0) {
422 if (memcmp(target_addr, dest_addr, byte_count)) {
423 continue; /* no match */
424 }
425 }
426
427 if (extra_bits > 0) {
428 unsigned char c1 = ((unsigned char *)target_addr)[byte_count];
429 unsigned char c2 = ((unsigned char *)&dest_addr)[byte_count];
430 unsigned char mask = 0xff << (8 - extra_bits);
431 if ((c1 & mask) != (c2 & mask)) {
432 continue;
433 }
434 }
435 return JNI_TRUE;
436 }
437 return JNI_FALSE;
438}
439
440
441static void initLoopbackRoutes() {
442 FILE *f;
443 char srcp[8][5];
444 char hopp[8][5];
445 int dest_plen, src_plen, use, refcnt, metric;
446 unsigned long flags;
447 char dest_str[40];
448 struct in6_addr dest_addr;
449 char device[16];
450 jboolean match = JNI_FALSE;
451
452 if (loRoutes != 0) {
453 free (loRoutes);
454 }
455 loRoutes = calloc (loRoutes_size, sizeof(struct loopback_route));
456 if (loRoutes == 0) {
457 return;
458 }
459 /*
460 * Scan /proc/net/ipv6_route looking for a matching
461 * route.
462 */
463 if ((f = fopen("/proc/net/ipv6_route", "r")) == NULL) {
464 return ;
465 }
466 while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
467 "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
468 "%4s%4s%4s%4s%4s%4s%4s%4s "
469 "%08x %08x %08x %08lx %8s",
470 dest_str, &dest_str[5], &dest_str[10], &dest_str[15],
471 &dest_str[20], &dest_str[25], &dest_str[30], &dest_str[35],
472 &dest_plen,
473 srcp[0], srcp[1], srcp[2], srcp[3],
474 srcp[4], srcp[5], srcp[6], srcp[7],
475 &src_plen,
476 hopp[0], hopp[1], hopp[2], hopp[3],
477 hopp[4], hopp[5], hopp[6], hopp[7],
478 &metric, &use, &refcnt, &flags, device) == 31) {
479
480 /*
481 * Some routes should be ignored
482 */
483 if ( (dest_plen < 0 || dest_plen > 128) ||
484 (src_plen != 0) ||
485 (flags & (RTF_POLICY | RTF_FLOW)) ||
486 ((flags & RTF_REJECT) && dest_plen == 0) ) {
487 continue;
488 }
489
490 /*
491 * Convert the destination address
492 */
493 dest_str[4] = ':';
494 dest_str[9] = ':';
495 dest_str[14] = ':';
496 dest_str[19] = ':';
497 dest_str[24] = ':';
498 dest_str[29] = ':';
499 dest_str[34] = ':';
500 dest_str[39] = '\0';
501
502 if (inet_pton(AF_INET6, dest_str, &dest_addr) < 0) {
503 /* not an Ipv6 address */
504 continue;
505 }
506 if (strcmp(device, "lo") != 0) {
507 /* Not a loopback route */
508 continue;
509 } else {
510 if (nRoutes == loRoutes_size) {
511 loRoutes = realloc (loRoutes, loRoutes_size *
512 sizeof (struct loopback_route) * 2);
513 if (loRoutes == 0) {
514 return ;
515 }
516 loRoutes_size *= 2;
517 }
518 memcpy (&loRoutes[nRoutes].addr,&dest_addr,sizeof(struct in6_addr));
519 loRoutes[nRoutes].plen = dest_plen;
520 nRoutes ++;
521 }
522 }
523
524 fclose (f);
525 {
526 /* now find the scope_id for "lo" */
527
528 char addr6[40], devname[20];
529 char addr6p[8][5];
530 int plen, scope, dad_status, if_idx;
531
532 if ((f = fopen("/proc/net/if_inet6", "r")) != NULL) {
533 while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x %02x %02x %02x %20s\n",
534 addr6p[0], addr6p[1], addr6p[2], addr6p[3],
535 addr6p[4], addr6p[5], addr6p[6], addr6p[7],
536 &if_idx, &plen, &scope, &dad_status, devname) == 13) {
537
538 if (strcmp(devname, "lo") == 0) {
539 /*
540 * Found - so just return the index
541 */
542 fclose(f);
543 lo_scope_id = if_idx;
544 return;
545 }
546 }
547 fclose(f);
548 }
549 }
550}
551
552/*
553 * Following is used for binding to local addresses. Equivalent
554 * to code above, for bind().
555 */
556
557struct localinterface {
558 int index;
559 char localaddr [16];
560};
561
562static struct localinterface *localifs = 0;
563static int localifsSize = 0; /* size of array */
564static int nifs = 0; /* number of entries used in array */
565
566/* not thread safe: make sure called once from one thread */
567
568static void initLocalIfs () {
569 FILE *f;
570 unsigned char staddr [16];
571 char ifname [32];
572 struct localinterface *lif=0;
573 int index, x1, x2, x3;
574 unsigned int u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,ua,ub,uc,ud,ue,uf;
575
576 if ((f = fopen("/proc/net/if_inet6", "r")) == NULL) {
577 return ;
578 }
579 while (fscanf (f, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x "
580 "%d %x %x %x %s",&u0,&u1,&u2,&u3,&u4,&u5,&u6,&u7,
581 &u8,&u9,&ua,&ub,&uc,&ud,&ue,&uf,
582 &index, &x1, &x2, &x3, ifname) == 21) {
583 staddr[0] = (unsigned char)u0;
584 staddr[1] = (unsigned char)u1;
585 staddr[2] = (unsigned char)u2;
586 staddr[3] = (unsigned char)u3;
587 staddr[4] = (unsigned char)u4;
588 staddr[5] = (unsigned char)u5;
589 staddr[6] = (unsigned char)u6;
590 staddr[7] = (unsigned char)u7;
591 staddr[8] = (unsigned char)u8;
592 staddr[9] = (unsigned char)u9;
593 staddr[10] = (unsigned char)ua;
594 staddr[11] = (unsigned char)ub;
595 staddr[12] = (unsigned char)uc;
596 staddr[13] = (unsigned char)ud;
597 staddr[14] = (unsigned char)ue;
598 staddr[15] = (unsigned char)uf;
599 nifs ++;
600 if (nifs > localifsSize) {
601 localifs = (struct localinterface *) realloc (
602 localifs, sizeof (struct localinterface)* (localifsSize+5));
603 if (localifs == 0) {
604 nifs = 0;
605 fclose (f);
606 return;
607 }
608 lif = localifs + localifsSize;
609 localifsSize += 5;
610 } else {
611 lif ++;
612 }
613 memcpy (lif->localaddr, staddr, 16);
614 lif->index = index;
615 }
616 fclose (f);
617}
618
619/* return the scope_id (interface index) of the
620 * interface corresponding to the given address
621 * returns 0 if no match found
622 */
623
624static int getLocalScopeID (char *addr) {
625 struct localinterface *lif;
626 int i;
627 if (localifs == 0) {
628 initLocalIfs();
629 }
630 for (i=0, lif=localifs; i<nifs; i++, lif++) {
631 if (memcmp (addr, lif->localaddr, 16) == 0) {
632 return lif->index;
633 }
634 }
635 return 0;
636}
637
638void initLocalAddrTable () {
639 initLoopbackRoutes();
640 initLocalIfs();
641}
642
643#else
644
645void initLocalAddrTable () {}
646
647#endif
648
649/* In the case of an IPv4 Inetaddress this method will return an
650 * IPv4 mapped address where IPv6 is available and v4MappedAddress is TRUE.
651 * Otherwise it will return a sockaddr_in structure for an IPv4 InetAddress.
652*/
653JNIEXPORT int JNICALL
654NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr *him,
655 int *len, jboolean v4MappedAddress) {
656 jint family;
657 family = (*env)->GetIntField(env, iaObj, ia_familyID);
658#ifdef AF_INET6
659 /* needs work. 1. family 2. clean up him6 etc deallocate memory */
660 if (ipv6_available() && !(family == IPv4 && v4MappedAddress == JNI_FALSE)) {
661 struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
662 jbyteArray ipaddress;
663 jbyte caddr[16];
664 jint address;
665
666
667 if (family == IPv4) { /* will convert to IPv4-mapped address */
668 memset((char *) caddr, 0, 16);
669 address = (*env)->GetIntField(env, iaObj, ia_addressID);
670 if (address == INADDR_ANY) {
671 /* we would always prefer IPv6 wildcard address
672 caddr[10] = 0xff;
673 caddr[11] = 0xff; */
674 } else {
675 caddr[10] = 0xff;
676 caddr[11] = 0xff;
677 caddr[12] = ((address >> 24) & 0xff);
678 caddr[13] = ((address >> 16) & 0xff);
679 caddr[14] = ((address >> 8) & 0xff);
680 caddr[15] = (address & 0xff);
681 }
682 } else {
683 ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
684 (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
685 }
686 memset((char *)him6, 0, sizeof(struct sockaddr_in6));
687 him6->sin6_port = htons(port);
688 memcpy((void *)&(him6->sin6_addr), caddr, sizeof(struct in6_addr) );
689 him6->sin6_family = AF_INET6;
690 *len = sizeof(struct sockaddr_in6) ;
691
692 /*
693 * On Linux if we are connecting to a link-local address
694 * we need to specify the interface in the scope_id (2.4 kernel only)
695 *
696 * If the scope was cached the we use the cached value. If not cached but
697 * specified in the Inet6Address we use that, but we first check if the
698 * address needs to be routed via the loopback interface. In this case,
699 * we override the specified value with that of the loopback interface.
700 * If no cached value exists and no value was specified by user, then
701 * we try to determine a value ffrom the routing table. In all these
702 * cases the used value is cached for further use.
703 */
704#ifdef __linux__
705 if (IN6_IS_ADDR_LINKLOCAL(&(him6->sin6_addr))) {
706 int cached_scope_id = 0, scope_id = 0;
707 int old_kernel = kernelIsV22();
708
709 if (ia6_cachedscopeidID && !old_kernel) {
710 cached_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);
711 /* if cached value exists then use it. Otherwise, check
712 * if scope is set in the address.
713 */
714 if (!cached_scope_id) {
715 if (ia6_scopeidID) {
716 scope_id = (int)(*env)->GetIntField(env,iaObj,ia6_scopeidID);
717 }
718 if (scope_id != 0) {
719 /* check user-specified value for loopback case
720 * that needs to be overridden
721 */
722 if (kernelIsV24() && needsLoopbackRoute (&him6->sin6_addr)) {
723 cached_scope_id = lo_scope_id;
724 (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
725 }
726 } else {
727 /*
728 * Otherwise consult the IPv6 routing tables to
729 * try determine the appropriate interface.
730 */
731 if (kernelIsV24()) {
732 cached_scope_id = getDefaultIPv6Interface( &(him6->sin6_addr) );
733 } else {
734 cached_scope_id = getLocalScopeID( (char *)&(him6->sin6_addr) );
735 if (cached_scope_id == 0) {
736 cached_scope_id = getDefaultIPv6Interface( &(him6->sin6_addr) );
737 }
738 }
739 (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
740 }
741 }
742 }
743
744 /*
745 * If we have a scope_id use the extended form
746 * of sockaddr_in6.
747 */
748
749 if (!old_kernel) {
750 struct sockaddr_in6 *him6 =
751 (struct sockaddr_in6 *)him;
752 him6->sin6_scope_id = cached_scope_id != 0 ?
753 cached_scope_id : scope_id;
754 *len = sizeof(struct sockaddr_in6);
755 }
756 }
757#else
758 /* handle scope_id for solaris */
759
760 if (family != IPv4) {
761 if (ia6_scopeidID) {
762 him6->sin6_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_scopeidID);
763 }
764 }
765#endif
766 } else
767#endif /* AF_INET6 */
768 {
769 struct sockaddr_in *him4 = (struct sockaddr_in*)him;
770 jint address;
771 if (family == IPv6) {
772 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
773 return -1;
774 }
775 memset((char *) him4, 0, sizeof(struct sockaddr_in));
776 address = (*env)->GetIntField(env, iaObj, ia_addressID);
777 him4->sin_port = htons((short) port);
778 him4->sin_addr.s_addr = (uint32_t) htonl(address);
779 him4->sin_family = AF_INET;
780 *len = sizeof(struct sockaddr_in);
781 }
782 return 0;
783}
784
785void
786NET_SetTrafficClass(struct sockaddr *him, int trafficClass) {
787#ifdef AF_INET6
788 if (him->sa_family == AF_INET6) {
789 struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
790 him6->sin6_flowinfo = htonl((trafficClass & 0xff) << 20);
791 }
792#endif /* AF_INET6 */
793}
794
795jint
796NET_GetPortFromSockaddr(struct sockaddr *him) {
797#ifdef AF_INET6
798 if (him->sa_family == AF_INET6) {
799 return ntohs(((struct sockaddr_in6*)him)->sin6_port);
800
801 } else
802#endif /* AF_INET6 */
803 {
804 return ntohs(((struct sockaddr_in*)him)->sin_port);
805 }
806}
807
808int
809NET_IsIPv4Mapped(jbyte* caddr) {
810 int i;
811 for (i = 0; i < 10; i++) {
812 if (caddr[i] != 0x00) {
813 return 0; /* false */
814 }
815 }
816
817 if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
818 return 1; /* true */
819 }
820 return 0; /* false */
821}
822
823int
824NET_IPv4MappedToIPv4(jbyte* caddr) {
825 return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
826 | (caddr[15] & 0xff);
827}
828
829int
830NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
831 int i;
832 for (i = 0; i < 16; i++) {
833 if (caddr1[i] != caddr2[i]) {
834 return 0; /* false */
835 }
836 }
837 return 1;
838}
839
840jboolean NET_addrtransAvailable() {
841 return (jboolean)(getaddrinfo_ptr != NULL);
842}
843
844/*
845 * Map the Java level socket option to the platform specific
846 * level and option name.
847 */
848int
849NET_MapSocketOption(jint cmd, int *level, int *optname) {
850 static struct {
851 jint cmd;
852 int level;
853 int optname;
854 } const opts[] = {
855 { java_net_SocketOptions_TCP_NODELAY, IPPROTO_TCP, TCP_NODELAY },
856 { java_net_SocketOptions_SO_OOBINLINE, SOL_SOCKET, SO_OOBINLINE },
857 { java_net_SocketOptions_SO_LINGER, SOL_SOCKET, SO_LINGER },
858 { java_net_SocketOptions_SO_SNDBUF, SOL_SOCKET, SO_SNDBUF },
859 { java_net_SocketOptions_SO_RCVBUF, SOL_SOCKET, SO_RCVBUF },
860 { java_net_SocketOptions_SO_KEEPALIVE, SOL_SOCKET, SO_KEEPALIVE },
861 { java_net_SocketOptions_SO_REUSEADDR, SOL_SOCKET, SO_REUSEADDR },
862 { java_net_SocketOptions_SO_BROADCAST, SOL_SOCKET, SO_BROADCAST },
863 { java_net_SocketOptions_IP_TOS, IPPROTO_IP, IP_TOS },
864 { java_net_SocketOptions_IP_MULTICAST_IF, IPPROTO_IP, IP_MULTICAST_IF },
865 { java_net_SocketOptions_IP_MULTICAST_IF2, IPPROTO_IP, IP_MULTICAST_IF },
866 { java_net_SocketOptions_IP_MULTICAST_LOOP, IPPROTO_IP, IP_MULTICAST_LOOP },
867 };
868
869 int i;
870
871 /*
872 * Different multicast options if IPv6 is enabled
873 */
874#ifdef AF_INET6
875 if (ipv6_available()) {
876 switch (cmd) {
877 case java_net_SocketOptions_IP_MULTICAST_IF:
878 case java_net_SocketOptions_IP_MULTICAST_IF2:
879 *level = IPPROTO_IPV6;
880 *optname = IPV6_MULTICAST_IF;
881 return 0;
882
883 case java_net_SocketOptions_IP_MULTICAST_LOOP:
884 *level = IPPROTO_IPV6;
885 *optname = IPV6_MULTICAST_LOOP;
886 return 0;
887 }
888 }
889#endif
890
891 /*
892 * Map the Java level option to the native level
893 */
894 for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
895 if (cmd == opts[i].cmd) {
896 *level = opts[i].level;
897 *optname = opts[i].optname;
898 return 0;
899 }
900 }
901
902 /* not found */
903 return -1;
904}
905
906/*
907 * Determine the default interface for an IPv6 address.
908 *
909 * 1. Scans /proc/net/ipv6_route for a matching route
910 * (eg: fe80::/10 or a route for the specific address).
911 * This will tell us the interface to use (eg: "eth0").
912 *
913 * 2. Lookup /proc/net/if_inet6 to map the interface
914 * name to an interface index.
915 *
916 * Returns :-
917 * -1 if error
918 * 0 if no matching interface
919 * >1 interface index to use for the link-local address.
920 */
921#if defined(__linux__) && defined(AF_INET6)
922int getDefaultIPv6Interface(struct in6_addr *target_addr) {
923 FILE *f;
924 char srcp[8][5];
925 char hopp[8][5];
926 int dest_plen, src_plen, use, refcnt, metric;
927 unsigned long flags;
928 char dest_str[40];
929 struct in6_addr dest_addr;
930 char device[16];
931 jboolean match = JNI_FALSE;
932
933 /*
934 * Scan /proc/net/ipv6_route looking for a matching
935 * route.
936 */
937 if ((f = fopen("/proc/net/ipv6_route", "r")) == NULL) {
938 return -1;
939 }
940 while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
941 "%4s%4s%4s%4s%4s%4s%4s%4s %02x "
942 "%4s%4s%4s%4s%4s%4s%4s%4s "
943 "%08x %08x %08x %08lx %8s",
944 dest_str, &dest_str[5], &dest_str[10], &dest_str[15],
945 &dest_str[20], &dest_str[25], &dest_str[30], &dest_str[35],
946 &dest_plen,
947 srcp[0], srcp[1], srcp[2], srcp[3],
948 srcp[4], srcp[5], srcp[6], srcp[7],
949 &src_plen,
950 hopp[0], hopp[1], hopp[2], hopp[3],
951 hopp[4], hopp[5], hopp[6], hopp[7],
952 &metric, &use, &refcnt, &flags, device) == 31) {
953
954 /*
955 * Some routes should be ignored
956 */
957 if ( (dest_plen < 0 || dest_plen > 128) ||
958 (src_plen != 0) ||
959 (flags & (RTF_POLICY | RTF_FLOW)) ||
960 ((flags & RTF_REJECT) && dest_plen == 0) ) {
961 continue;
962 }
963
964 /*
965 * Convert the destination address
966 */
967 dest_str[4] = ':';
968 dest_str[9] = ':';
969 dest_str[14] = ':';
970 dest_str[19] = ':';
971 dest_str[24] = ':';
972 dest_str[29] = ':';
973 dest_str[34] = ':';
974 dest_str[39] = '\0';
975
976 if (inet_pton(AF_INET6, dest_str, &dest_addr) < 0) {
977 /* not an Ipv6 address */
978 continue;
979 } else {
980 /*
981 * The prefix len (dest_plen) indicates the number of bits we
982 * need to match on.
983 *
984 * dest_plen / 8 => number of bytes to match
985 * dest_plen % 8 => number of additional bits to match
986 *
987 * eg: fe80::/10 => match 1 byte + 2 additional bits in the
988 * the next byte.
989 */
990 int byte_count = dest_plen >> 3;
991 int extra_bits = dest_plen & 0x3;
992
993 if (byte_count > 0) {
994 if (memcmp(target_addr, &dest_addr, byte_count)) {
995 continue; /* no match */
996 }
997 }
998
999 if (extra_bits > 0) {
1000 unsigned char c1 = ((unsigned char *)target_addr)[byte_count];
1001 unsigned char c2 = ((unsigned char *)&dest_addr)[byte_count];
1002 unsigned char mask = 0xff << (8 - extra_bits);
1003 if ((c1 & mask) != (c2 & mask)) {
1004 continue;
1005 }
1006 }
1007
1008 /*
1009 * We have a match
1010 */
1011 match = JNI_TRUE;
1012 break;
1013 }
1014 }
1015 fclose(f);
1016
1017 /*
1018 * If there's a match then we lookup the interface
1019 * index.
1020 */
1021 if (match) {
1022 char addr6[40], devname[20];
1023 char addr6p[8][5];
1024 int plen, scope, dad_status, if_idx;
1025
1026 if ((f = fopen("/proc/net/if_inet6", "r")) != NULL) {
1027 while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x %02x %02x %02x %20s\n",
1028 addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1029 addr6p[4], addr6p[5], addr6p[6], addr6p[7],
1030 &if_idx, &plen, &scope, &dad_status, devname) == 13) {
1031
1032 if (strcmp(devname, device) == 0) {
1033 /*
1034 * Found - so just return the index
1035 */
1036 fclose(f);
1037 return if_idx;
1038 }
1039 }
1040 fclose(f);
1041 } else {
1042 /*
1043 * Couldn't open /proc/net/if_inet6
1044 */
1045 return -1;
1046 }
1047 }
1048
1049 /*
1050 * If we get here it means we didn't there wasn't any
1051 * route or we couldn't get the index of the interface.
1052 */
1053 return 0;
1054}
1055#endif
1056
1057
1058/*
1059 * Wrapper for getsockopt system routine - does any necessary
1060 * pre/post processing to deal with OS specific oddies :-
1061 *
1062 * IP_TOS is a no-op with IPv6 sockets as it's setup when
1063 * the connection is established.
1064 *
1065 * On Linux the SO_SNDBUF/SO_RCVBUF values must be post-processed
1066 * to compensate for an incorrect value returned by the kernel.
1067 */
1068int
1069NET_GetSockOpt(int fd, int level, int opt, void *result,
1070 int *len)
1071{
1072 int rv;
1073
1074#ifdef AF_INET6
1075 if ((level == IPPROTO_IP) && (opt == IP_TOS)) {
1076 if (ipv6_available()) {
1077
1078 /*
1079 * For IPv6 socket option implemented at Java-level
1080 * so return -1.
1081 */
1082 int *tc = (int *)result;
1083 *tc = -1;
1084 return 0;
1085 }
1086 }
1087#endif
1088
1089 rv = getsockopt(fd, level, opt, result, len);
1090 if (rv < 0) {
1091 return rv;
1092 }
1093
1094#ifdef __linux__
1095 /*
1096 * On Linux SO_SNDBUF/SO_RCVBUF aren't symmetric. This
1097 * stems from additional socket structures in the send
1098 * and receive buffers.
1099 */
1100 if ((level == SOL_SOCKET) && ((opt == SO_SNDBUF)
1101 || (opt == SO_RCVBUF))) {
1102 int n = *((int *)result);
1103 n /= 2;
1104 *((int *)result) = n;
1105 }
1106#endif
1107
1108 return rv;
1109}
1110
1111
1112/*
1113 * Wrapper for setsockopt system routine - performs any
1114 * necessary pre/post processing to deal with OS specific
1115 * issue :-
1116 *
1117 * On Solaris need to limit the suggested value for SO_SNDBUF
1118 * and SO_RCVBUF to the kernel configured limit
1119 *
1120 * For IP_TOS socket option need to mask off bits as this
1121 * aren't automatically masked by the kernel and results in
1122 * an error. In addition IP_TOS is a noop with IPv6 as it
1123 * should be setup as connection time.
1124 */
1125int
1126NET_SetSockOpt(int fd, int level, int opt, const void *arg,
1127 int len)
1128{
1129#ifndef IPTOS_TOS_MASK
1130#define IPTOS_TOS_MASK 0x1e
1131#endif
1132#ifndef IPTOS_PREC_MASK
1133#define IPTOS_PREC_MASK 0xe0
1134#endif
1135
1136 /*
1137 * IPPROTO/IP_TOS :-
1138 * 1. IPv6 on Solaris: no-op and will be set in flowinfo
1139 * field when connecting TCP socket, or sending
1140 * UDP packet.
1141 * 2. IPv6 on Linux: By default Linux ignores flowinfo
1142 * field so enable IPV6_FLOWINFO_SEND so that flowinfo
1143 * will be examined.
1144 * 3. IPv4: set socket option based on ToS and Precedence
1145 * fields (otherwise get invalid argument)
1146 */
1147 if (level == IPPROTO_IP && opt == IP_TOS) {
1148 int *iptos;
1149
1150#if defined(AF_INET6) && defined(__solaris__)
1151 if (ipv6_available()) {
1152 return 0;
1153 }
1154#endif
1155
1156#if defined(AF_INET6) && defined(__linux__)
1157 if (ipv6_available()) {
1158 int optval = 1;
1159 return setsockopt(fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
1160 (void *)&optval, sizeof(optval));
1161 }
1162#endif
1163
1164 iptos = (int *)arg;
1165 *iptos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
1166 }
1167
1168 /*
1169 * SOL_SOCKET/{SO_SNDBUF,SO_RCVBUF} - On Solaris need to
1170 * ensure that value is <= max_buf as otherwise we get
1171 * an invalid argument.
1172 */
1173#ifdef __solaris__
1174 if (level == SOL_SOCKET) {
1175 if (opt == SO_SNDBUF || opt == SO_RCVBUF) {
1176 int sotype, arglen;
1177 int *bufsize, maxbuf;
1178
1179 if (!init_max_buf) {
1180 tcp_max_buf = getParam("/dev/tcp", "tcp_max_buf", 64*1024);
1181 udp_max_buf = getParam("/dev/udp", "udp_max_buf", 64*1024);
1182 init_max_buf = 1;
1183 }
1184
1185 arglen = sizeof(sotype);
1186 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype,
1187 &arglen) < 0) {
1188 return -1;
1189 }
1190
1191 maxbuf = (sotype == SOCK_STREAM) ? tcp_max_buf : udp_max_buf;
1192 bufsize = (int *)arg;
1193 if (*bufsize > maxbuf) {
1194 *bufsize = maxbuf;
1195 }
1196 }
1197 }
1198#endif
1199
1200 /*
1201 * On Linux the receive buffer is used for both socket
1202 * structures and the the packet payload. The implication
1203 * is that if SO_RCVBUF is too small then small packets
1204 * must be discard.
1205 */
1206#ifdef __linux__
1207 if (level == SOL_SOCKET && opt == SO_RCVBUF) {
1208 int *bufsize = (int *)arg;
1209 if (*bufsize < 1024) {
1210 *bufsize = 1024;
1211 }
1212 }
1213#endif
1214
1215 return setsockopt(fd, level, opt, arg, len);
1216}
1217
1218/*
1219 * Wrapper for bind system call - performs any necessary pre/post
1220 * processing to deal with OS specific issues :-
1221 *
1222 * Linux allows a socket to bind to 127.0.0.255 which must be
1223 * caught.
1224 *
1225 * On Solaris 8/9 with IPv6 enabled we must use an exclusive
1226 * bind to guaranteed a unique port number across the IPv4 and
1227 * IPv6 port spaces.
1228 *
1229 */
1230int
1231NET_Bind(int fd, struct sockaddr *him, int len)
1232{
1233#if defined(__solaris__) && defined(AF_INET6)
1234 int level = -1;
1235 int exclbind = -1;
1236#endif
1237 int rv;
1238
1239#ifdef __linux__
1240 /*
1241 * ## get bugId for this issue - goes back to 1.2.2 port ##
1242 * ## When IPv6 is enabled this will be an IPv4-mapped
1243 * ## with family set to AF_INET6
1244 */
1245 if (him->sa_family == AF_INET) {
1246 struct sockaddr_in *sa = (struct sockaddr_in *)him;
1247 if ((ntohl(sa->sin_addr.s_addr) & 0x7f0000ff) == 0x7f0000ff) {
1248 errno = EADDRNOTAVAIL;
1249 return -1;
1250 }
1251 }
1252#endif
1253
1254#if defined(__solaris__) && defined(AF_INET6)
1255 /*
1256 * Solaris 8/9 have seperate IPv4 and IPv6 port spaces so we
1257 * use an exclusive bind when SO_REUSEADDR is not used to
1258 * give the illusion of a unified port space.
1259 * This also avoid problems with IPv6 sockets connecting
1260 * to IPv4 mapped addresses whereby the socket conversion
1261 * results in a late bind that fails because the
1262 * corresponding IPv4 port is in use.
1263 */
1264 if (ipv6_available()) {
1265 int arg, len;
1266
1267 len = sizeof(arg);
1268 if (getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&arg,
1269 &len) == 0) {
1270 if (arg == 0) {
1271 /*
1272 * SO_REUSEADDR is disabled so enable TCP_EXCLBIND or
1273 * UDP_EXCLBIND
1274 */
1275 len = sizeof(arg);
1276 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&arg,
1277 &len) == 0) {
1278 if (arg == SOCK_STREAM) {
1279 level = IPPROTO_TCP;
1280 exclbind = TCP_EXCLBIND;
1281 } else {
1282 level = IPPROTO_UDP;
1283 exclbind = UDP_EXCLBIND;
1284 }
1285 }
1286
1287 arg = 1;
1288 setsockopt(fd, level, exclbind, (char *)&arg,
1289 sizeof(arg));
1290 }
1291 }
1292 }
1293
1294#endif
1295
1296 rv = bind(fd, him, len);
1297
1298#if defined(__solaris__) && defined(AF_INET6)
1299 if (rv < 0) {
1300 int en = errno;
1301 /* Restore *_EXCLBIND if the bind fails */
1302 if (exclbind != -1) {
1303 int arg = 0;
1304 setsockopt(fd, level, exclbind, (char *)&arg,
1305 sizeof(arg));
1306 }
1307 errno = en;
1308 }
1309#endif
1310
1311 return rv;
1312}
1313
1314/**
1315 * Wrapper for select/poll with timeout on a single file descriptor.
1316 *
1317 * flags (defined in net_util_md.h can be any combination of
1318 * NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
1319 *
1320 * The function will return when either the socket is ready for one
1321 * of the specified operation or the timeout expired.
1322 *
1323 * It returns the time left from the timeout (possibly 0), or -1 if it expired.
1324 */
1325
1326jint
1327NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
1328{
1329 jlong prevTime = JVM_CurrentTimeMillis(env, 0);
1330 jint read_rv;
1331
1332 while (1) {
1333 jlong newTime;
1334#ifndef USE_SELECT
1335 {
1336 struct pollfd pfd;
1337 pfd.fd = fd;
1338 pfd.events = 0;
1339 if (flags & NET_WAIT_READ)
1340 pfd.events |= POLLIN;
1341 if (flags & NET_WAIT_WRITE)
1342 pfd.events |= POLLOUT;
1343 if (flags & NET_WAIT_CONNECT)
1344 pfd.events |= POLLOUT;
1345
1346 errno = 0;
1347 read_rv = NET_Poll(&pfd, 1, timeout);
1348 }
1349#else
1350 {
1351 fd_set rd, wr, ex;
1352 struct timeval t;
1353
1354 t.tv_sec = timeout / 1000;
1355 t.tv_usec = (timeout % 1000) * 1000;
1356
1357 FD_ZERO(&rd);
1358 FD_ZERO(&wr);
1359 FD_ZERO(&ex);
1360 if (flags & NET_WAIT_READ) {
1361 FD_SET(fd, &rd);
1362 }
1363 if (flags & NET_WAIT_WRITE) {
1364 FD_SET(fd, &wr);
1365 }
1366 if (flags & NET_WAIT_CONNECT) {
1367 FD_SET(fd, &wr);
1368 FD_SET(fd, &ex);
1369 }
1370
1371 errno = 0;
1372 read_rv = NET_Select(fd+1, &rd, &wr, &ex, &t);
1373 }
1374#endif
1375
1376 newTime = JVM_CurrentTimeMillis(env, 0);
1377 timeout -= (newTime - prevTime);
1378 if (timeout <= 0) {
1379 return read_rv > 0 ? 0 : -1;
1380 }
1381 newTime = prevTime;
1382
1383 if (read_rv > 0) {
1384 break;
1385 }
1386
1387
1388 } /* while */
1389
1390 return timeout;
1391}