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