1 /*
   2  * Copyright (c) 2000, 2016, 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 <strings.h>
  28 #if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
  29 #include <sys/types.h>
  30 #endif
  31 #include <netinet/in.h>
  32 #include <stdlib.h>
  33 #include <string.h>
  34 #include <sys/types.h>
  35 #include <sys/socket.h>
  36 #include <arpa/inet.h>
  37 #include <net/if.h>
  38 #include <net/if_arp.h>
  39 
  40 #if defined(__solaris__)
  41 #include <sys/dlpi.h>
  42 #include <fcntl.h>
  43 #include <stropts.h>
  44 #include <sys/sockio.h>
  45 #endif
  46 
  47 #if defined(__linux__)
  48 #include <sys/ioctl.h>
  49 #include <bits/ioctls.h>
  50 #include <sys/utsname.h>
  51 #include <stdio.h>
  52 #endif
  53 
  54 #if defined(_AIX)
  55 #include <sys/ioctl.h>
  56 #include <netinet/in6_var.h>
  57 #include <sys/ndd_var.h>
  58 #include <sys/kinfo.h>
  59 #endif
  60 
  61 #if defined(_ALLBSD_SOURCE)
  62 #include <sys/param.h>
  63 #include <sys/ioctl.h>
  64 #include <sys/sockio.h>
  65 #if defined(__APPLE__)
  66 #include <net/ethernet.h>
  67 #include <net/if_var.h>
  68 #include <net/if_dl.h>
  69 #include <netinet/in_var.h>
  70 #include <ifaddrs.h>
  71 #endif
  72 #endif
  73 
  74 #include "jvm.h"
  75 #include "jni_util.h"
  76 #include "net_util.h"
  77 
  78 #if defined(__linux__)
  79 #define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
  80 #endif
  81 
  82 typedef struct _netaddr  {
  83     struct sockaddr *addr;
  84     struct sockaddr *brdcast;
  85     short mask;
  86     int family; /* to make searches simple */
  87     struct _netaddr *next;
  88 } netaddr;
  89 
  90 typedef struct _netif {
  91     char *name;
  92     int index;
  93     char virtual;
  94     netaddr *addr;
  95     struct _netif *childs;
  96     struct _netif *next;
  97 } netif;
  98 
  99 /************************************************************************
 100  * NetworkInterface
 101  */
 102 
 103 #include "java_net_NetworkInterface.h"
 104 
 105 /************************************************************************
 106  * NetworkInterface
 107  */
 108 jclass ni_class;
 109 jfieldID ni_nameID;
 110 jfieldID ni_indexID;
 111 jfieldID ni_descID;
 112 jfieldID ni_addrsID;
 113 jfieldID ni_bindsID;
 114 jfieldID ni_virutalID;
 115 jfieldID ni_childsID;
 116 jfieldID ni_parentID;
 117 jfieldID ni_defaultIndexID;
 118 jmethodID ni_ctrID;
 119 
 120 static jclass ni_ibcls;
 121 static jmethodID ni_ibctrID;
 122 static jfieldID ni_ibaddressID;
 123 static jfieldID ni_ib4broadcastID;
 124 static jfieldID ni_ib4maskID;
 125 
 126 /** Private methods declarations **/
 127 static jobject createNetworkInterface(JNIEnv *env, netif *ifs);
 128 static int     getFlags0(JNIEnv *env, jstring  ifname);
 129 
 130 static netif  *enumInterfaces(JNIEnv *env);
 131 static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
 132 
 133 #ifdef AF_INET6
 134 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 135 #endif
 136 
 137 static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
 138                      struct sockaddr *ifr_addrP, struct sockaddr *ifr_broadaddrP,
 139                      struct sockaddr *ifr_subnetaddrP, int family, short prefix);
 140 static void    freeif(netif *ifs);
 141 
 142 static int     openSocket(JNIEnv *env, int proto);
 143 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 144 
 145 
 146 static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name,
 147                                       struct sockaddr *brdcast_store);
 148 static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
 149 static short   computeMaskFromAddress(struct sockaddr *ifr_subnetaddrP);
 150 static int     getIndex(int sock, const char *ifname);
 151 
 152 static int     getFlags(int sock, const char *ifname, int *flags);
 153 static int     getMacAddress(JNIEnv *env, int sock,  const char *ifname,
 154                              const struct in_addr *addr, unsigned char *buf);
 155 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 156 
 157 
 158 #if defined(__solaris__)
 159 static netif  *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
 160 static int     getMacFromDevice(JNIEnv *env, const char *ifname,
 161                                 unsigned char *retbuf);
 162 
 163 #ifndef SIOCGLIFHWADDR
 164 #define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
 165 #endif
 166 
 167 #endif
 168 
 169 /******************* Java entry points *****************************/
 170 
 171 /*
 172  * Class:     java_net_NetworkInterface
 173  * Method:    init
 174  * Signature: ()V
 175  */
 176 JNIEXPORT void JNICALL Java_java_net_NetworkInterface_init
 177   (JNIEnv *env, jclass cls)
 178 {
 179     ni_class = (*env)->FindClass(env, "java/net/NetworkInterface");
 180     CHECK_NULL(ni_class);
 181     ni_class = (*env)->NewGlobalRef(env, ni_class);
 182     CHECK_NULL(ni_class);
 183     ni_nameID = (*env)->GetFieldID(env, ni_class, "name", "Ljava/lang/String;");
 184     CHECK_NULL(ni_nameID);
 185     ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
 186     CHECK_NULL(ni_indexID);
 187     ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs",
 188                                     "[Ljava/net/InetAddress;");
 189     CHECK_NULL(ni_addrsID);
 190     ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings",
 191                                     "[Ljava/net/InterfaceAddress;");
 192     CHECK_NULL(ni_bindsID);
 193     ni_descID = (*env)->GetFieldID(env, ni_class, "displayName",
 194                                    "Ljava/lang/String;");
 195     CHECK_NULL(ni_descID);
 196     ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
 197     CHECK_NULL(ni_virutalID);
 198     ni_childsID = (*env)->GetFieldID(env, ni_class, "childs",
 199                                      "[Ljava/net/NetworkInterface;");
 200     CHECK_NULL(ni_childsID);
 201     ni_parentID = (*env)->GetFieldID(env, ni_class, "parent",
 202                                      "Ljava/net/NetworkInterface;");
 203     CHECK_NULL(ni_parentID);
 204     ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
 205     CHECK_NULL(ni_ctrID);
 206     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
 207     CHECK_NULL(ni_ibcls);
 208     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
 209     CHECK_NULL(ni_ibcls);
 210     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
 211     CHECK_NULL(ni_ibctrID);
 212     ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address",
 213                                         "Ljava/net/InetAddress;");
 214     CHECK_NULL(ni_ibaddressID);
 215     ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast",
 216                                            "Ljava/net/Inet4Address;");
 217     CHECK_NULL(ni_ib4broadcastID);
 218     ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
 219     CHECK_NULL(ni_ib4maskID);
 220     ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex",
 221                                                  "I");
 222     CHECK_NULL(ni_defaultIndexID);
 223     initInetAddressIDs(env);
 224 }
 225 
 226 /*
 227  * Class:     java_net_NetworkInterface
 228  * Method:    getByName0
 229  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 230  */
 231 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
 232   (JNIEnv *env, jclass cls, jstring name)
 233 {
 234     netif *ifs, *curr;
 235     jboolean isCopy;
 236     const char* name_utf;
 237     jobject obj = NULL;
 238 
 239     ifs = enumInterfaces(env);
 240     if (ifs == NULL) {
 241         return NULL;
 242     }
 243 
 244     name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 245     if (name_utf == NULL) {
 246        if (!(*env)->ExceptionCheck(env))
 247            JNU_ThrowOutOfMemoryError(env, NULL);
 248        freeif(ifs);
 249        return NULL;
 250     }
 251 
 252     // Search the list of interface based on name
 253     curr = ifs;
 254     while (curr != NULL) {
 255         if (strcmp(name_utf, curr->name) == 0) {
 256             break;
 257         }
 258         curr = curr->next;
 259     }
 260 
 261     // if found create a NetworkInterface
 262     if (curr != NULL) {;
 263         obj = createNetworkInterface(env, curr);
 264     }
 265 
 266     // release the UTF string and interface list
 267     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 268     freeif(ifs);
 269 
 270     return obj;
 271 }
 272 
 273 /*
 274  * Class:     java_net_NetworkInterface
 275  * Method:    getByIndex0
 276  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 277  */
 278 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
 279   (JNIEnv *env, jclass cls, jint index)
 280 {
 281     netif *ifs, *curr;
 282     jobject obj = NULL;
 283 
 284     if (index <= 0) {
 285         return NULL;
 286     }
 287     ifs = enumInterfaces(env);
 288     if (ifs == NULL) {
 289         return NULL;
 290     }
 291 
 292     // Search the list of interface based on index
 293     curr = ifs;
 294     while (curr != NULL) {
 295         if (index == curr->index) {
 296             break;
 297         }
 298         curr = curr->next;
 299     }
 300 
 301     // if found create a NetworkInterface
 302     if (curr != NULL) {;
 303         obj = createNetworkInterface(env, curr);
 304     }
 305 
 306     freeif(ifs);
 307     return obj;
 308 }
 309 
 310 /*
 311  * Class:     java_net_NetworkInterface
 312  * Method:    getByInetAddress0
 313  * Signature: (Ljava/net/InetAddress;)Ljava/net/NetworkInterface;
 314  */
 315 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
 316   (JNIEnv *env, jclass cls, jobject iaObj)
 317 {
 318     netif *ifs, *curr;
 319 
 320 #ifdef AF_INET6
 321     int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
 322 #else
 323     int family =  AF_INET;
 324 #endif
 325 
 326     jobject obj = NULL;
 327     jboolean match = JNI_FALSE;
 328 
 329     ifs = enumInterfaces(env);
 330     if (ifs == NULL) {
 331         return NULL;
 332     }
 333 
 334     curr = ifs;
 335     while (curr != NULL) {
 336         netaddr *addrP = curr->addr;
 337 
 338         // Iterate through each address on the interface
 339         while (addrP != NULL) {
 340 
 341             if (family == addrP->family) {
 342                 if (family == AF_INET) {
 343                     int address1 = htonl(
 344                         ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
 345                     int address2 = getInetAddress_addr(env, iaObj);
 346 
 347                     if (address1 == address2) {
 348                         match = JNI_TRUE;
 349                         break;
 350                     }
 351                 }
 352 
 353 #ifdef AF_INET6
 354                 if (family == AF_INET6) {
 355                     jbyte *bytes = (jbyte *)&(
 356                         ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
 357                     jbyte caddr[16];
 358                     int i;
 359                     getInet6Address_ipaddress(env, iaObj, (char *)caddr);
 360                     i = 0;
 361                     while (i < 16) {
 362                         if (caddr[i] != bytes[i]) {
 363                             break;
 364                         }
 365                         i++;
 366                     }
 367                     if (i >= 16) {
 368                         match = JNI_TRUE;
 369                         break;
 370                     }
 371                 }
 372 #endif
 373             }
 374 
 375             if (match) {
 376                 break;
 377             }
 378             addrP = addrP->next;
 379         }
 380 
 381         if (match) {
 382             break;
 383         }
 384         curr = curr->next;
 385     }
 386 
 387     // if found create a NetworkInterface
 388     if (match) {;
 389         obj = createNetworkInterface(env, curr);
 390     }
 391 
 392     freeif(ifs);
 393     return obj;
 394 }
 395 
 396 /*
 397  * Class:     java_net_NetworkInterface
 398  * Method:    getAll
 399  * Signature: ()[Ljava/net/NetworkInterface;
 400  */
 401 JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
 402   (JNIEnv *env, jclass cls)
 403 {
 404     netif *ifs, *curr;
 405     jobjectArray netIFArr;
 406     jint arr_index, ifCount;
 407 
 408     ifs = enumInterfaces(env);
 409     if (ifs == NULL) {
 410         return NULL;
 411     }
 412 
 413     // count the interface
 414     ifCount = 0;
 415     curr = ifs;
 416     while (curr != NULL) {
 417         ifCount++;
 418         curr = curr->next;
 419     }
 420 
 421     // allocate a NetworkInterface array
 422     netIFArr = (*env)->NewObjectArray(env, ifCount, cls, NULL);
 423     if (netIFArr == NULL) {
 424         freeif(ifs);
 425         return NULL;
 426     }
 427 
 428     // Iterate through the interfaces, create a NetworkInterface instance
 429     // for each array element and populate the object.
 430     curr = ifs;
 431     arr_index = 0;
 432     while (curr != NULL) {
 433         jobject netifObj;
 434 
 435         netifObj = createNetworkInterface(env, curr);
 436         if (netifObj == NULL) {
 437             freeif(ifs);
 438             return NULL;
 439         }
 440 
 441         // put the NetworkInterface into the array
 442         (*env)->SetObjectArrayElement(env, netIFArr, arr_index++, netifObj);
 443 
 444         curr = curr->next;
 445     }
 446 
 447     freeif(ifs);
 448     return netIFArr;
 449 }
 450 
 451 /*
 452  * Class:     java_net_NetworkInterface
 453  * Method:    isUp0
 454  * Signature: (Ljava/lang/String;I)Z
 455  */
 456 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0
 457   (JNIEnv *env, jclass cls, jstring name, jint index)
 458 {
 459     int ret = getFlags0(env, name);
 460     return ((ret & IFF_UP) && (ret & IFF_RUNNING)) ? JNI_TRUE :  JNI_FALSE;
 461 }
 462 
 463 /*
 464  * Class:     java_net_NetworkInterface
 465  * Method:    isP2P0
 466  * Signature: (Ljava/lang/String;I)Z
 467  */
 468 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
 469   (JNIEnv *env, jclass cls, jstring name, jint index)
 470 {
 471     int ret = getFlags0(env, name);
 472     return (ret & IFF_POINTOPOINT) ? JNI_TRUE :  JNI_FALSE;
 473 }
 474 
 475 /*
 476  * Class:     java_net_NetworkInterface
 477  * Method:    isLoopback0
 478  * Signature: (Ljava/lang/String;I)Z
 479  */
 480 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0
 481   (JNIEnv *env, jclass cls, jstring name, jint index)
 482 {
 483     int ret = getFlags0(env, name);
 484     return (ret & IFF_LOOPBACK) ? JNI_TRUE :  JNI_FALSE;
 485 }
 486 
 487 /*
 488  * Class:     java_net_NetworkInterface
 489  * Method:    supportsMulticast0
 490  * Signature: (Ljava/lang/String;I)Z
 491  */
 492 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0
 493   (JNIEnv *env, jclass cls, jstring name, jint index)
 494 {
 495     int ret = getFlags0(env, name);
 496     return (ret & IFF_MULTICAST) ? JNI_TRUE :  JNI_FALSE;
 497 }
 498 
 499 /*
 500  * Class:     java_net_NetworkInterface
 501  * Method:    getMacAddr0
 502  * Signature: ([bLjava/lang/String;I)[b
 503  */
 504 JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
 505   (JNIEnv *env, jclass cls, jbyteArray addrArray, jstring name, jint index)
 506 {
 507     jint addr;
 508     jbyte caddr[4];
 509     struct in_addr iaddr;
 510     jbyteArray ret = NULL;
 511     unsigned char mac[16];
 512     int len;
 513     int sock;
 514     jboolean isCopy;
 515     const char* name_utf;
 516 
 517     name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 518     if (name_utf == NULL) {
 519        if (!(*env)->ExceptionCheck(env))
 520            JNU_ThrowOutOfMemoryError(env, NULL);
 521        return NULL;
 522     }
 523     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
 524        (*env)->ReleaseStringUTFChars(env, name, name_utf);
 525        return NULL;
 526     }
 527 
 528     if (!IS_NULL(addrArray)) {
 529        (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 530        addr = ((caddr[0]<<24) & 0xff000000);
 531        addr |= ((caddr[1] <<16) & 0xff0000);
 532        addr |= ((caddr[2] <<8) & 0xff00);
 533        addr |= (caddr[3] & 0xff);
 534        iaddr.s_addr = htonl(addr);
 535        len = getMacAddress(env, sock, name_utf, &iaddr, mac);
 536     } else {
 537        len = getMacAddress(env, sock, name_utf, NULL, mac);
 538     }
 539     if (len > 0) {
 540        ret = (*env)->NewByteArray(env, len);
 541        if (IS_NULL(ret)) {
 542           /* we may have memory to free at the end of this */
 543           goto fexit;
 544        }
 545        (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
 546     }
 547  fexit:
 548    // release the UTF string and interface list
 549    (*env)->ReleaseStringUTFChars(env, name, name_utf);
 550 
 551    close(sock);
 552    return ret;
 553 }
 554 
 555 /*
 556  * Class:       java_net_NetworkInterface
 557  * Method:      getMTU0
 558  * Signature:   ([bLjava/lang/String;I)I
 559  */
 560 JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
 561   (JNIEnv *env, jclass cls, jstring name, jint index)
 562 {
 563     jboolean isCopy;
 564     int ret = -1;
 565     int sock;
 566     const char* name_utf = NULL;
 567 
 568     if (name != NULL) {
 569         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 570     } else {
 571         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 572         return ret;
 573     }
 574     if (name_utf == NULL) {
 575        if (!(*env)->ExceptionCheck(env))
 576            JNU_ThrowOutOfMemoryError(env, NULL);
 577        return ret;
 578     }
 579 
 580     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
 581        (*env)->ReleaseStringUTFChars(env, name, name_utf);
 582        return JNI_FALSE;
 583     }
 584 
 585     ret = getMTU(env, sock, name_utf);
 586 
 587     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 588 
 589     close(sock);
 590     return ret;
 591 }
 592 
 593 /*** Private methods definitions ****/
 594 
 595 static int getFlags0(JNIEnv *env, jstring name) {
 596     jboolean isCopy;
 597     int ret, sock;
 598     const char* name_utf;
 599     int flags = 0;
 600 
 601     if (name != NULL) {
 602         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 603     } else {
 604         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 605         return -1;
 606     }
 607 
 608     if (name_utf == NULL) {
 609        if (!(*env)->ExceptionCheck(env))
 610            JNU_ThrowOutOfMemoryError(env, NULL);
 611        return -1;
 612     }
 613     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
 614         (*env)->ReleaseStringUTFChars(env, name, name_utf);
 615         return -1;
 616     }
 617 
 618     ret = getFlags(sock, name_utf, &flags);
 619 
 620     close(sock);
 621     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 622 
 623     if (ret < 0) {
 624         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 625                                      "ioctl SIOCGLIFFLAGS failed");
 626         return -1;
 627     }
 628 
 629     return flags;
 630 }
 631 
 632 /*
 633  * Creates a NetworkInterface object, populates the name, the index, and
 634  * populates the InetAddress array based on the IP addresses for this
 635  * interface.
 636  */
 637 jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
 638     jobject netifObj;
 639     jobject name;
 640     jobjectArray addrArr;
 641     jobjectArray bindArr;
 642     jobjectArray childArr;
 643     netaddr *addrs;
 644     jint addr_index, addr_count, bind_index;
 645     jint child_count, child_index;
 646     netaddr *addrP;
 647     netif *childP;
 648     jobject tmp;
 649 
 650     // Create a NetworkInterface object and populate it
 651     netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
 652     CHECK_NULL_RETURN(netifObj, NULL);
 653     name = (*env)->NewStringUTF(env, ifs->name);
 654     CHECK_NULL_RETURN(name, NULL);
 655     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
 656     (*env)->SetObjectField(env, netifObj, ni_descID, name);
 657     (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);
 658     (*env)->SetBooleanField(env, netifObj, ni_virutalID,
 659                             ifs->virtual ? JNI_TRUE : JNI_FALSE);
 660 
 661     //Count the number of address on this interface
 662     addr_count = 0;
 663     addrP = ifs->addr;
 664     while (addrP != NULL) {
 665         addr_count++;
 666         addrP = addrP->next;
 667     }
 668 
 669     // Create the array of InetAddresses
 670     addrArr = (*env)->NewObjectArray(env, addr_count, ia_class, NULL);
 671     if (addrArr == NULL) {
 672         return NULL;
 673     }
 674 
 675     bindArr = (*env)->NewObjectArray(env, addr_count, ni_ibcls, NULL);
 676     if (bindArr == NULL) {
 677        return NULL;
 678     }
 679     addrP = ifs->addr;
 680     addr_index = 0;
 681     bind_index = 0;
 682     while (addrP != NULL) {
 683         jobject iaObj = NULL;
 684         jobject ibObj = NULL;
 685 
 686         if (addrP->family == AF_INET) {
 687             iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 688             if (iaObj) {
 689                  setInetAddress_addr(env, iaObj, htonl(
 690                      ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
 691             } else {
 692                 return NULL;
 693             }
 694             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
 695             if (ibObj) {
 696                  (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
 697                  if (addrP->brdcast) {
 698                     jobject ia2Obj = NULL;
 699                     ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 700                     if (ia2Obj) {
 701                        setInetAddress_addr(env, ia2Obj, htonl(
 702                            ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
 703                        (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
 704                     } else {
 705                         return NULL;
 706                     }
 707                  }
 708                  (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
 709                  (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
 710             } else {
 711                 return NULL;
 712             }
 713         }
 714 
 715 #ifdef AF_INET6
 716         if (addrP->family == AF_INET6) {
 717             int scope=0;
 718             iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
 719             if (iaObj) {
 720                 jboolean ret = setInet6Address_ipaddress(env, iaObj,
 721                     (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
 722                 if (ret == JNI_FALSE) {
 723                     return NULL;
 724                 }
 725 
 726                 scope = ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id;
 727 
 728                 if (scope != 0) { /* zero is default value, no need to set */
 729                     setInet6Address_scopeid(env, iaObj, scope);
 730                     setInet6Address_scopeifname(env, iaObj, netifObj);
 731                 }
 732             } else {
 733                 return NULL;
 734             }
 735             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
 736             if (ibObj) {
 737                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
 738                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
 739                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
 740             } else {
 741                 return NULL;
 742             }
 743         }
 744 #endif
 745 
 746         (*env)->SetObjectArrayElement(env, addrArr, addr_index++, iaObj);
 747         addrP = addrP->next;
 748     }
 749 
 750     // See if there is any virtual interface attached to this one.
 751     child_count = 0;
 752     childP = ifs->childs;
 753     while (childP) {
 754         child_count++;
 755         childP = childP->next;
 756     }
 757 
 758     childArr = (*env)->NewObjectArray(env, child_count, ni_class, NULL);
 759     if (childArr == NULL) {
 760         return NULL;
 761     }
 762 
 763     // Create the NetworkInterface instances for the sub-interfaces as well.
 764     child_index = 0;
 765     childP = ifs->childs;
 766     while(childP) {
 767       tmp = createNetworkInterface(env, childP);
 768       if (tmp == NULL) {
 769          return NULL;
 770       }
 771       (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
 772       (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
 773       childP = childP->next;
 774     }
 775     (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
 776     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
 777     (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);
 778 
 779     // return the NetworkInterface
 780     return netifObj;
 781 }
 782 
 783 /*
 784  * Enumerates all interfaces
 785  */
 786 static netif *enumInterfaces(JNIEnv *env) {
 787     netif *ifs;
 788     int sock;
 789 
 790     // Enumerate IPv4 addresses
 791     sock = openSocket(env, AF_INET);
 792     if (sock < 0 && (*env)->ExceptionOccurred(env)) {
 793         return NULL;
 794     }
 795 
 796     ifs = enumIPv4Interfaces(env, sock, NULL);
 797     close(sock);
 798 
 799     if (ifs == NULL && (*env)->ExceptionOccurred(env)) {
 800         return NULL;
 801     }
 802 
 803     // return partial list if an exception occurs in the middle of process ???
 804 
 805     // If IPv6 is available then enumerate IPv6 addresses.
 806 #ifdef AF_INET6
 807 
 808         // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
 809         // so we have to call ipv6_available()
 810         if (ipv6_available()) {
 811 
 812            sock = openSocket(env, AF_INET6);
 813            if (sock < 0 && (*env)->ExceptionOccurred(env)) {
 814                freeif(ifs);
 815                return NULL;
 816            }
 817 
 818            ifs = enumIPv6Interfaces(env, sock, ifs);
 819            close(sock);
 820 
 821            if ((*env)->ExceptionOccurred(env)) {
 822               freeif(ifs);
 823               return NULL;
 824            }
 825 
 826        }
 827 #endif
 828 
 829     return ifs;
 830 }
 831 
 832 #define CHECKED_MALLOC3(_pointer, _type, _size) \
 833     do { \
 834         _pointer = (_type)malloc(_size); \
 835         if (_pointer == NULL) { \
 836             JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
 837             return ifs; /* return untouched list */ \
 838         } \
 839     } while(0)
 840 
 841 
 842 /*
 843  * Frees an interface list (including any attached addresses)
 844  */
 845 void freeif(netif *ifs) {
 846     netif *currif = ifs;
 847     netif *child = NULL;
 848 
 849     while (currif != NULL) {
 850         netaddr *addrP = currif->addr;
 851         while (addrP != NULL) {
 852             netaddr *next = addrP->next;
 853             free(addrP);
 854             addrP = next;
 855         }
 856 
 857         // Don't forget to free the sub-interfaces.
 858         if (currif->childs != NULL) {
 859             freeif(currif->childs);
 860         }
 861 
 862         ifs = currif->next;
 863         free(currif);
 864         currif = ifs;
 865     }
 866 }
 867 
 868 netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
 869              struct sockaddr *ifr_addrP, struct sockaddr *ifr_broadaddrP,
 870              struct sockaddr *ifr_subnetaddrP, int family, short prefix)
 871 {
 872     netif *currif = ifs, *parent;
 873     netaddr *addrP;
 874 
 875 #ifdef LIFNAMSIZ
 876     int ifnam_size = LIFNAMSIZ;
 877     char name[LIFNAMSIZ], vname[LIFNAMSIZ];
 878 #else
 879     int ifnam_size = IFNAMSIZ;
 880     char name[IFNAMSIZ], vname[IFNAMSIZ];
 881 #endif
 882 
 883     char *name_colonP;
 884     int mask;
 885     int isVirtual = 0;
 886     int addr_size;
 887     int flags = 0;
 888 
 889     // If the interface name is a logical interface then we remove the unit
 890     // number so that we have the physical interface (eg: hme0:1 -> hme0).
 891     // NetworkInterface currently doesn't have any concept of physical vs.
 892     // logical interfaces.
 893     strncpy(name, if_name, ifnam_size);
 894     name[ifnam_size - 1] = '\0';
 895     *vname = 0;
 896 
 897      // Create and populate the netaddr node. If allocation fails
 898      // return an un-updated list.
 899 
 900      // Allocate for addr and brdcast at once
 901 
 902 #ifdef AF_INET6
 903     addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
 904                                     : sizeof(struct sockaddr_in6);
 905 #else
 906     addr_size = sizeof(struct sockaddr_in);
 907 #endif
 908 
 909     CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr) + 2 * addr_size);
 910     addrP->addr = (struct sockaddr *)((char *)addrP + sizeof(netaddr));
 911     memcpy(addrP->addr, ifr_addrP, addr_size);
 912 
 913     addrP->family = family;
 914     addrP->brdcast = NULL;
 915     addrP->mask = prefix;
 916     addrP->next = 0;
 917     if (family == AF_INET) {
 918         // Deal with broadcast addr & subnet mask
 919         if (ifr_broadaddrP != NULL) {  // just set it, if already known
 920             addrP->brdcast =
 921                 (struct sockaddr *)((char *)addrP + sizeof(netaddr) + addr_size);
 922             memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
 923         } else {  // otherwise look it up
 924             struct sockaddr *brdcast_to =
 925                 (struct sockaddr *)((char *)addrP + sizeof(netaddr) + addr_size);
 926             addrP->brdcast = getBroadcast(env, sock, name, brdcast_to);
 927             if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
 928                 return ifs;
 929             }
 930         }
 931 
 932         if (ifr_subnetaddrP != NULL) {  // just compute the mask, if already known
 933             addrP->mask = computeMaskFromAddress(ifr_subnetaddrP);
 934         } else {   // otherwise look it up
 935             if ((mask = getSubnet(env, sock, name)) != -1) {
 936                 addrP->mask = mask;
 937             } else if((*env)->ExceptionCheck(env)) {
 938                 return ifs;
 939             }
 940         }
 941     }
 942 
 943     // Deal with virtual interface with colon notation e.g. eth0:1
 944     name_colonP = strchr(name, ':');
 945     if (name_colonP != NULL) {
 946         // This is a virtual interface. If we are able to access the parent
 947         // we need to create a new entry if it doesn't exist yet *and* update
 948         // the 'parent' interface with the new records.
 949         *name_colonP = 0;
 950         if (getFlags(sock, name, &flags) < 0 || flags < 0) {
 951              // failed to access parent interface do not create parent.
 952              // We are a virtual interface with no parent.
 953              isVirtual = 1;
 954              *name_colonP = ':';
 955         } else {
 956              // Got access to parent, so create it if necessary.
 957              // Save original name to vname and truncate name by ':'
 958              memcpy(vname, name, sizeof(vname) );
 959              vname[name_colonP - name] = ':';
 960         }
 961     }
 962 
 963     // Check if this is a "new" interface. Use the interface name for
 964     // matching because index isn't supported on Solaris 2.6 & 7.
 965     while (currif != NULL) {
 966         if (strcmp(name, currif->name) == 0) {
 967             break;
 968         }
 969         currif = currif->next;
 970     }
 971 
 972     // If "new" then create an netif structure and insert it into the list.
 973     if (currif == NULL) {
 974          CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
 975          currif->name = (char *)currif + sizeof(netif);
 976          strncpy(currif->name, name, ifnam_size);
 977          currif->name[ifnam_size - 1] = '\0';
 978          currif->index = getIndex(sock, name);
 979          currif->addr = NULL;
 980          currif->childs = NULL;
 981          currif->virtual = isVirtual;
 982          currif->next = ifs;
 983          ifs = currif;
 984     }
 985 
 986     // Finally insert the address on the interface
 987     addrP->next = currif->addr;
 988     currif->addr = addrP;
 989 
 990     parent = currif;
 991 
 992     // Deal with the virtual interface now.
 993     if (vname[0]) {
 994         netaddr *tmpaddr;
 995 
 996         currif = parent->childs;
 997 
 998         while (currif != NULL) {
 999             if (strcmp(vname, currif->name) == 0) {
1000                 break;
1001             }
1002             currif = currif->next;
1003         }
1004 
1005         if (currif == NULL) {
1006             CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
1007             currif->name = (char *)currif + sizeof(netif);
1008             strncpy(currif->name, vname, ifnam_size);
1009             currif->name[ifnam_size - 1] = '\0';
1010             currif->index = getIndex(sock, vname);
1011             currif->addr = NULL;
1012             // Need to duplicate the addr entry?
1013             currif->virtual = 1;
1014             currif->childs = NULL;
1015             currif->next = parent->childs;
1016             parent->childs = currif;
1017         }
1018 
1019         CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr) + 2 * addr_size);
1020         memcpy(tmpaddr, addrP, sizeof(netaddr));
1021         if (addrP->addr != NULL) {
1022             tmpaddr->addr = (struct sockaddr *)
1023                 ((char*)tmpaddr + sizeof(netaddr));
1024             memcpy(tmpaddr->addr, addrP->addr, addr_size);
1025         }
1026 
1027         if (addrP->brdcast != NULL) {
1028             tmpaddr->brdcast = (struct sockaddr *)
1029                 ((char *)tmpaddr + sizeof(netaddr) + addr_size);
1030             memcpy(tmpaddr->brdcast, addrP->brdcast, addr_size);
1031         }
1032 
1033         tmpaddr->next = currif->addr;
1034         currif->addr = tmpaddr;
1035     }
1036 
1037     return ifs;
1038 }
1039 
1040 static short computeMaskFromAddress(struct sockaddr *ifr_subnetaddrP) {
1041     short ret = 0;
1042     unsigned int mask;
1043 
1044     mask = ntohl(((struct sockaddr_in*)ifr_subnetaddrP)->sin_addr.s_addr);
1045 
1046     while (mask) {
1047        mask <<= 1;
1048        ret++;
1049     }
1050 
1051     return ret;
1052 }
1053 
1054 /*
1055  * Opens a socket for further ioct calls. proto is one of AF_INET or AF_INET6.
1056  */
1057 static int openSocket(JNIEnv *env, int proto) {
1058     int sock;
1059 
1060     if ((sock = socket(proto, SOCK_DGRAM, 0)) < 0) {
1061         // If EPROTONOSUPPORT is returned it means we don't have
1062         // support for this proto so don't throw an exception.
1063         if (errno != EPROTONOSUPPORT) {
1064             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1065                                          "Socket creation failed");
1066         }
1067         return -1;
1068     }
1069 
1070     return sock;
1071 }
1072 
1073 
1074 /** Linux, AIX **/
1075 #if defined(__linux__) || defined(_AIX)
1076 
1077 #ifdef AF_INET6
1078 /*
1079  * Opens a socket for further ioct calls. Tries AF_INET socket first and
1080  * if it falls return AF_INET6 socket.
1081  */
1082 // unused arg ifname and struct if2
1083 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1084     int sock;
1085     struct ifreq if2;
1086 
1087     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1088         if (errno == EPROTONOSUPPORT) {
1089             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1090                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1091                                              "IPV6 Socket creation failed");
1092                 return -1;
1093             }
1094         } else { // errno is not NOSUPPORT
1095             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1096                                          "IPV4 Socket creation failed");
1097             return -1;
1098         }
1099     }
1100 
1101     // Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or
1102     // IPv6 socket regardless of type of address of an interface.
1103     return sock;
1104 }
1105 
1106 #else
1107 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1108     return openSocket(env,AF_INET);
1109 }
1110 #endif
1111 
1112 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1113     struct ifconf ifc;
1114     struct ifreq *ifreqP;
1115     char *buf = NULL;
1116     int numifs;
1117     unsigned i;
1118     int siocgifconfRequest = SIOCGIFCONF;
1119 
1120 #if defined(__linux__)
1121     // need to do a dummy SIOCGIFCONF to determine the buffer size.
1122     // SIOCGIFCOUNT doesn't work
1123     ifc.ifc_buf = NULL;
1124     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
1125         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1126                                      "ioctl SIOCGIFCONF failed");
1127         return ifs;
1128     }
1129 #elif defined(_AIX)
1130     ifc.ifc_buf = NULL;
1131     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
1132         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1133                                      "ioctl SIOCGSIZIFCONF failed");
1134         return ifs;
1135     }
1136 #endif /* __linux__ */
1137 
1138     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
1139 
1140     ifc.ifc_buf = buf;
1141 #if defined(_AIX)
1142     siocgifconfRequest = CSIOCGIFCONF;
1143 #endif
1144     if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
1145         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1146                                      "ioctl SIOCGIFCONF failed");
1147         free(buf);
1148         return ifs;
1149     }
1150 
1151     // Iterate through each interface
1152     ifreqP = ifc.ifc_req;
1153     struct sockaddr addr, broadaddr, netmask;
1154     for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
1155         struct sockaddr* broadaddrP = NULL;
1156         struct sockaddr* subnetaddrP = NULL;
1157 
1158         // Ignore non IPv4 Interfaces
1159         if ((struct sockaddr *)&(ifreqP->ifr_addr) != NULL &&
1160             ((struct sockaddr *)&(ifreqP->ifr_addr))->sa_family != AF_INET) {
1161             continue;
1162         }
1163 
1164         memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
1165 
1166         // set broadaddrP, if applicable
1167         if ((ifreqP->ifr_flags & IFF_POINTOPOINT) == 0 &&
1168             ifreqP->ifr_flags & IFF_BROADCAST) {
1169 
1170             if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
1171                 memcpy(&broadaddr, &(ifreqP->ifr_broadaddr), sizeof(struct sockaddr));
1172                 broadaddrP = &broadaddr;
1173             }
1174             // restore the address, for subsequent calls
1175             memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
1176         }
1177 
1178         if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
1179 #if defined(_AIX)
1180             memcpy(&netmask, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
1181 #else
1182             memcpy(&netmask, &(ifreqP->ifr_netmask), sizeof(struct sockaddr));
1183 #endif
1184             subnetaddrP = &netmask;
1185         }
1186 
1187         // Add to the list
1188         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
1189                     &addr, broadaddrP, subnetaddrP, AF_INET, 0);
1190 
1191         // If an exception occurred then free the list
1192         if ((*env)->ExceptionOccurred(env)) {
1193             free(buf);
1194             freeif(ifs);
1195             return NULL;
1196         }
1197     }
1198 
1199     // Free socket and buffer
1200     free(buf);
1201     return ifs;
1202 }
1203 
1204 
1205 #if defined(AF_INET6) && defined(__linux__)
1206 
1207 /*
1208  * Enumerates and returns all IPv6 interfaces on Linux.
1209  */
1210 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1211     FILE *f;
1212     char addr6[40], devname[21];
1213     char addr6p[8][5];
1214     int prefix, scope, dad_status, if_idx;
1215     uint8_t ipv6addr[16];
1216 
1217     if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
1218         while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
1219                       addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1220                       addr6p[4], addr6p[5], addr6p[6], addr6p[7],
1221                       &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
1222 
1223             struct netif *ifs_ptr = NULL;
1224             struct netif *last_ptr = NULL;
1225             struct sockaddr_in6 addr;
1226 
1227             sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
1228                     addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1229                     addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
1230             inet_pton(AF_INET6, addr6, ipv6addr);
1231 
1232             memset(&addr, 0, sizeof(struct sockaddr_in6));
1233             memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
1234 
1235             addr.sin6_scope_id = if_idx;
1236 
1237             ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
1238                         NULL, NULL, AF_INET6, (short)prefix);
1239 
1240             // If an exception occurred then return the list as is.
1241             if ((*env)->ExceptionOccurred(env)) {
1242                 fclose(f);
1243                 return ifs;
1244             }
1245        }
1246        fclose(f);
1247     }
1248     return ifs;
1249 }
1250 #endif
1251 
1252 
1253 #if defined(AF_INET6) && defined(_AIX)
1254 
1255 /*
1256  * Enumerates and returns all IPv6 interfaces on AIX.
1257  */
1258 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1259     struct ifconf ifc;
1260     struct ifreq *ifreqP;
1261     char *buf;
1262     int numifs;
1263     unsigned i;
1264     unsigned bufsize;
1265     char *cp, *cplimit;
1266 
1267     // use SIOCGSIZIFCONF to get size for  SIOCGIFCONF
1268 
1269     ifc.ifc_buf = NULL;
1270     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
1271         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1272                                     "ioctl SIOCGSIZIFCONF failed");
1273         return ifs;
1274     }
1275     bufsize = ifc.ifc_len;
1276 
1277     buf = (char *)malloc(bufsize);
1278     if (!buf) {
1279         JNU_ThrowOutOfMemoryError(env, "Network interface native buffer allocation failed");
1280         return ifs;
1281     }
1282     ifc.ifc_len = bufsize;
1283     ifc.ifc_buf = buf;
1284     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
1285         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1286                                      "ioctl CSIOCGIFCONF failed");
1287         free(buf);
1288         return ifs;
1289     }
1290 
1291     // Iterate through each interface
1292     ifreqP = ifc.ifc_req;
1293     cp = (char *)ifc.ifc_req;
1294     cplimit = cp + ifc.ifc_len;
1295 
1296     for (; cp < cplimit;
1297         cp += (sizeof(ifreqP->ifr_name) +
1298                MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
1299     {
1300         ifreqP = (struct ifreq *)cp;
1301         struct ifreq if2;
1302         memset((char *)&if2, 0, sizeof(if2));
1303         strncpy(if2.ifr_name, ifreqP->ifr_name, sizeof(if2.ifr_name) - 1);
1304 
1305         // Skip interface that aren't UP
1306         if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
1307             if (!(if2.ifr_flags & IFF_UP)) {
1308                 continue;
1309             }
1310         }
1311 
1312         if (ifreqP->ifr_addr.sa_family != AF_INET6)
1313             continue;
1314 
1315         if (ioctl(sock, SIOCGIFSITE6, (char *)&if2) >= 0) {
1316             struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifreqP->ifr_addr);
1317             s6->sin6_scope_id = if2.ifr_site6;
1318         }
1319 
1320         // Add to the list
1321         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
1322                     (struct sockaddr *)&(ifreqP->ifr_addr),
1323                     NULL, NULL, AF_INET6, 0);
1324 
1325         // If an exception occurred then free the list
1326         if ((*env)->ExceptionOccurred(env)) {
1327             free(buf);
1328             freeif(ifs);
1329             return NULL;
1330         }
1331     }
1332 
1333     // Free socket and buffer
1334     free(buf);
1335     return ifs;
1336 }
1337 #endif
1338 
1339 
1340 static int getIndex(int sock, const char *name) {
1341      // Try to get the interface index
1342 #if defined(_AIX)
1343     return if_nametoindex(name);
1344 #else
1345     struct ifreq if2;
1346     memset((char *)&if2, 0, sizeof(if2));
1347     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
1348 
1349     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
1350         return -1;
1351     }
1352 
1353     return if2.ifr_ifindex;
1354 #endif
1355 }
1356 
1357 /*
1358  * Returns the IPv4 broadcast address of a named interface, if it exists.
1359  * Returns 0 if it doesn't have one.
1360  */
1361 static struct sockaddr *getBroadcast
1362   (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
1363 {
1364     struct sockaddr *ret = NULL;
1365     struct ifreq if2;
1366     memset((char *)&if2, 0, sizeof(if2));
1367     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1368 
1369     // Let's make sure the interface does have a broadcast address.
1370     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
1371         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1372                                      "ioctl SIOCGIFFLAGS failed");
1373         return ret;
1374     }
1375 
1376     if (if2.ifr_flags & IFF_BROADCAST) {
1377         // It does, let's retrieve it
1378         if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
1379             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1380                                          "ioctl SIOCGIFBRDADDR failed");
1381             return ret;
1382         }
1383 
1384         ret = brdcast_store;
1385         memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
1386     }
1387 
1388     return ret;
1389 }
1390 
1391 /*
1392  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
1393  * interface, if it has one, otherwise return -1.
1394  */
1395 static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
1396     unsigned int mask;
1397     short ret;
1398     struct ifreq if2;
1399     memset((char *)&if2, 0, sizeof(if2));
1400     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1401 
1402     if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
1403         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1404                                      "ioctl SIOCGIFNETMASK failed");
1405         return -1;
1406     }
1407 
1408     return computeMaskFromAddress(&(if2.ifr_addr));
1409 }
1410 
1411 /*
1412  * Gets the Hardware address (usually MAC address) for the named interface.
1413  * On return puts the data in buf, and returns the length, in byte, of the
1414  * MAC address. Returns -1 if there is no hardware address on that interface.
1415  */
1416 static int getMacAddress
1417   (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
1418    unsigned char *buf)
1419 {
1420 #if defined (_AIX)
1421     int size;
1422     struct kinfo_ndd *nddp;
1423     void *end;
1424 
1425     size = getkerninfo(KINFO_NDD, 0, 0, 0);
1426     if (size == 0) {
1427         return -1;
1428     }
1429 
1430     if (size < 0) {
1431         perror("getkerninfo 1");
1432         return -1;
1433     }
1434 
1435     nddp = (struct kinfo_ndd *)malloc(size);
1436 
1437     if (!nddp) {
1438         JNU_ThrowOutOfMemoryError(env,
1439             "Network interface getMacAddress native buffer allocation failed");
1440         return -1;
1441     }
1442 
1443     if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
1444         perror("getkerninfo 2");
1445         return -1;
1446     }
1447 
1448     end = (void *)nddp + size;
1449     while ((void *)nddp < end) {
1450         if (!strcmp(nddp->ndd_alias, ifname) ||
1451                 !strcmp(nddp->ndd_name, ifname)) {
1452             bcopy(nddp->ndd_addr, buf, 6);
1453             return 6;
1454         } else {
1455             nddp++;
1456         }
1457     }
1458 
1459     return -1;
1460 #elif defined(__linux__)
1461     static struct ifreq ifr;
1462     int i;
1463     memset((char *)&ifr, 0, sizeof(ifr));
1464     strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
1465     if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
1466         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1467                                      "ioctl SIOCGIFHWADDR failed");
1468         return -1;
1469     }
1470 
1471     memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
1472 
1473     // All bytes to 0 means no hardware address.
1474 
1475     for (i = 0; i < IFHWADDRLEN; i++) {
1476         if (buf[i] != 0)
1477             return IFHWADDRLEN;
1478     }
1479 
1480     return -1;
1481 #endif
1482 }
1483 
1484 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
1485     struct ifreq if2;
1486     memset((char *)&if2, 0, sizeof(if2));
1487 
1488     if (ifname != NULL) {
1489         strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1490     } else {
1491         JNU_ThrowNullPointerException(env, "network interface name is NULL");
1492         return -1;
1493     }
1494 
1495     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
1496         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1497                                      "ioctl SIOCGIFMTU failed");
1498         return -1;
1499     }
1500 
1501     return  if2.ifr_mtu;
1502 }
1503 
1504 static int getFlags(int sock, const char *ifname, int *flags) {
1505   struct ifreq if2;
1506   memset((char *)&if2, 0, sizeof(if2));
1507   strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1508 
1509   if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
1510       return -1;
1511   }
1512 
1513   if (sizeof(if2.ifr_flags) == sizeof(short)) {
1514       *flags = (if2.ifr_flags & 0xffff);
1515   } else {
1516       *flags = if2.ifr_flags;
1517   }
1518   return 0;
1519 }
1520 
1521 #endif  /* defined(__linux__) || defined(_AIX) */
1522 
1523 /** Solaris **/
1524 #if defined(__solaris__)
1525 
1526 /*
1527  * Opens a socket for further ioct calls. Tries AF_INET socket first and
1528  * if it falls return AF_INET6 socket.
1529  */
1530 #ifdef AF_INET6
1531 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1532     int sock, alreadyV6 = 0;
1533     struct lifreq if2;
1534 
1535     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1536         if (errno == EPROTONOSUPPORT) {
1537             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1538                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1539                                              "IPV6 Socket creation failed");
1540                 return -1;
1541             }
1542 
1543             alreadyV6=1;
1544         } else { // errno is not NOSUPPORT
1545             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1546                                          "IPV4 Socket creation failed");
1547             return -1;
1548         }
1549     }
1550 
1551 
1552     // Solaris requires that we have an IPv6 socket to query an  interface
1553     // without an IPv4 address - check it here. POSIX 1 require the kernel to
1554     // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
1555     // for a device having IPv6 only address but not all devices follow the
1556     // standard so fall back on any error. It's not an ecologically friendly
1557     // gesture but more reliable.
1558 
1559     if (!alreadyV6) {
1560         memset((char *)&if2, 0, sizeof(if2));
1561         strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1562         if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
1563             close(sock);
1564             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1565                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1566                                              "IPV6 Socket creation failed");
1567                 return -1;
1568             }
1569         }
1570     }
1571 
1572     return sock;
1573 }
1574 
1575 #else
1576 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1577     return openSocket(env,AF_INET);
1578 }
1579 #endif
1580 
1581 /*
1582  * Enumerates and returns all IPv4 interfaces.
1583  */
1584 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1585     return enumIPvXInterfaces(env,sock, ifs, AF_INET);
1586 }
1587 
1588 #ifdef AF_INET6
1589 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1590     return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
1591 }
1592 #endif
1593 
1594 /*
1595  * Enumerates and returns all interfaces on Solaris.
1596  * Uses the same code for IPv4 and IPv6.
1597  */
1598 static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
1599     struct lifconf ifc;
1600     struct lifreq *ifr;
1601     int n;
1602     char *buf;
1603     struct lifnum numifs;
1604     unsigned bufsize;
1605 
1606     // Get the interface count
1607     numifs.lifn_family = family;
1608     numifs.lifn_flags = 0;
1609     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
1610         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1611                                      "ioctl SIOCGLIFNUM failed");
1612         return ifs;
1613     }
1614 
1615     //  Enumerate the interface configurations
1616     bufsize = numifs.lifn_count * sizeof (struct lifreq);
1617     CHECKED_MALLOC3(buf, char *, bufsize);
1618 
1619     ifc.lifc_family = family;
1620     ifc.lifc_flags = 0;
1621     ifc.lifc_len = bufsize;
1622     ifc.lifc_buf = buf;
1623     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
1624         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1625                                      "ioctl SIOCGLIFCONF failed");
1626         free(buf);
1627         return ifs;
1628     }
1629 
1630     // Iterate through each interface
1631     ifr = ifc.lifc_req;
1632     for (n=0; n<numifs.lifn_count; n++, ifr++) {
1633         int index = -1;
1634         struct lifreq if2;
1635 
1636         // Ignore either IPv4 or IPv6 addresses
1637         if (ifr->lifr_addr.ss_family != family) {
1638             continue;
1639         }
1640 
1641 #ifdef AF_INET6
1642         if (ifr->lifr_addr.ss_family == AF_INET6) {
1643             struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
1644             s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
1645         }
1646 #endif
1647 
1648         // add to the list
1649         ifs = addif(env, sock,ifr->lifr_name, ifs,
1650                     (struct sockaddr *)&(ifr->lifr_addr),
1651                     NULL, NULL, family, (short)ifr->lifr_addrlen);
1652 
1653         // If an exception occurred we return immediately
1654         if ((*env)->ExceptionOccurred(env)) {
1655             free(buf);
1656             return ifs;
1657         }
1658 
1659    }
1660 
1661     free(buf);
1662     return ifs;
1663 }
1664 
1665 static int getIndex(int sock, const char *name) {
1666     // Try to get the interface index.  (Not supported on Solaris 2.6 or 7)
1667     struct lifreq if2;
1668     memset((char *)&if2, 0, sizeof(if2));
1669     strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
1670 
1671     if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
1672         return -1;
1673     }
1674 
1675     return if2.lifr_index;
1676 }
1677 
1678 /*
1679  * Returns the IPv4 broadcast address of a named interface, if it exists.
1680  * Returns 0 if it doesn't have one.
1681  */
1682 static struct sockaddr *getBroadcast
1683   (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
1684 {
1685     struct sockaddr *ret = NULL;
1686     struct lifreq if2;
1687     memset((char *)&if2, 0, sizeof(if2));
1688     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1689 
1690     // Let's make sure the interface does have a broadcast address
1691     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
1692         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1693                                      "ioctl SIOCGLIFFLAGS failed");
1694         return ret;
1695     }
1696 
1697     if (if2.lifr_flags & IFF_BROADCAST) {
1698         // It does, let's retrieve it
1699         if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
1700             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1701                                          "ioctl SIOCGLIFBRDADDR failed");
1702             return ret;
1703         }
1704 
1705         ret = brdcast_store;
1706         memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
1707     }
1708 
1709     return ret;
1710 }
1711 
1712 /*
1713  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
1714  * interface, if it has one, otherwise return -1.
1715  */
1716 static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
1717     unsigned int mask;
1718     short ret;
1719     struct lifreq if2;
1720     memset((char *)&if2, 0, sizeof(if2));
1721     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1722 
1723     if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
1724         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1725                                      "ioctl SIOCGLIFNETMASK failed");
1726         return -1;
1727     }
1728 
1729     return computeMaskFromAddress(&(if2.lifr_addr));
1730 }
1731 
1732 
1733 #define DEV_PREFIX  "/dev/"
1734 
1735 /*
1736  * Solaris specific DLPI code to get hardware address from a device.
1737  * Unfortunately, at least up to Solaris X, you have to have special
1738  * privileges (i.e. be root).
1739  */
1740 static int getMacFromDevice
1741   (JNIEnv *env, const char* ifname, unsigned char* retbuf)
1742 {
1743     char style1dev[MAXPATHLEN];
1744     int fd;
1745     dl_phys_addr_req_t dlpareq;
1746     dl_phys_addr_ack_t *dlpaack;
1747     struct strbuf msg;
1748     char buf[128];
1749     int flags = 0;
1750 
1751     // Device is in /dev.  e.g.: /dev/bge0
1752     strcpy(style1dev, DEV_PREFIX);
1753     strcat(style1dev, ifname);
1754     if ((fd = open(style1dev, O_RDWR)) < 0) {
1755          // Can't open it. We probably are missing the privilege.
1756          // We'll have to try something else
1757          return 0;
1758     }
1759 
1760     dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
1761     dlpareq.dl_addr_type = DL_CURR_PHYS_ADDR;
1762 
1763     msg.buf = (char *)&dlpareq;
1764     msg.len = DL_PHYS_ADDR_REQ_SIZE;
1765 
1766     if (putmsg(fd, &msg, NULL, 0) < 0) {
1767         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1768                                      "putmsg failed");
1769         return -1;
1770     }
1771 
1772     dlpaack = (dl_phys_addr_ack_t *)buf;
1773 
1774     msg.buf = (char *)buf;
1775     msg.len = 0;
1776     msg.maxlen = sizeof (buf);
1777     if (getmsg(fd, &msg, NULL, &flags) < 0) {
1778         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1779                                      "getmsg failed");
1780         return -1;
1781     }
1782 
1783     if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
1784         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
1785                         "Couldn't obtain phys addr\n");
1786         return -1;
1787     }
1788 
1789     memcpy(retbuf, &buf[dlpaack->dl_addr_offset], dlpaack->dl_addr_length);
1790     return dlpaack->dl_addr_length;
1791 }
1792 
1793 /*
1794  * Gets the Hardware address (usually MAC address) for the named interface.
1795  * On return puts the data in buf, and returns the length, in byte, of the
1796  * MAC address. Returns -1 if there is no hardware address on that interface.
1797  */
1798 static int getMacAddress
1799   (JNIEnv *env, int sock, const char *ifname, const struct in_addr* addr,
1800    unsigned char *buf)
1801 {
1802     struct arpreq arpreq;
1803     struct sockaddr_in* sin;
1804     struct sockaddr_in ipAddr;
1805     int len, i;
1806     struct lifreq lif;
1807 
1808     // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
1809     // try the old way.
1810     memset(&lif, 0, sizeof(lif));
1811     strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
1812 
1813     if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
1814         struct sockaddr_dl *sp;
1815         sp = (struct sockaddr_dl *)&lif.lifr_addr;
1816         memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
1817         return sp->sdl_alen;
1818     }
1819 
1820     // On Solaris we have to use DLPI, but it will only work if we have
1821     // privileged access (i.e. root). If that fails, we try a lookup
1822     // in the ARP table, which requires an IPv4 address.
1823     if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
1824         // DLPI failed - trying to do arp lookup
1825 
1826         if (addr == NULL) {
1827              // No IPv4 address for that interface, so can't do an ARP lookup.
1828              return -1;
1829          }
1830 
1831          len = 6; //???
1832 
1833          sin = (struct sockaddr_in *) &arpreq.arp_pa;
1834          memset((char *) &arpreq, 0, sizeof(struct arpreq));
1835          ipAddr.sin_port = 0;
1836          ipAddr.sin_family = AF_INET;
1837          memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
1838          memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
1839          arpreq.arp_flags= ATF_PUBL;
1840 
1841          if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
1842              return -1;
1843          }
1844 
1845          memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
1846     }
1847 
1848     // All bytes to 0 means no hardware address.
1849     for (i = 0; i < len; i++) {
1850       if (buf[i] != 0)
1851          return len;
1852     }
1853 
1854     return -1;
1855 }
1856 
1857 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
1858     struct lifreq if2;
1859     memset((char *)&if2, 0, sizeof(if2));
1860     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1861 
1862     if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
1863         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1864                                     "ioctl SIOCGLIFMTU failed");
1865         return -1;
1866     }
1867 
1868     return if2.lifr_mtu;
1869 }
1870 
1871 static int getFlags(int sock, const char *ifname, int *flags) {
1872     struct lifreq if2;
1873     memset((char *)&if2, 0, sizeof(if2));
1874     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1875 
1876     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
1877         return -1;
1878     }
1879 
1880     *flags = if2.lifr_flags;
1881     return 0;
1882 }
1883 
1884 
1885 #endif  /* __solaris__ */
1886 
1887 
1888 /** BSD **/
1889 #ifdef _ALLBSD_SOURCE
1890 
1891 /*
1892  * Opens a socket for further ioct calls. Tries AF_INET socket first and
1893  * if it falls return AF_INET6 socket.
1894  */
1895 #ifdef AF_INET6
1896 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1897     int sock;
1898     struct ifreq if2;
1899 
1900      if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1901          if (errno == EPROTONOSUPPORT) {
1902               if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1903                  NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1904                                               "IPV6 Socket creation failed");
1905                  return -1;
1906               }
1907          } else { // errno is not NOSUPPORT
1908              NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1909                                           "IPV4 Socket creation failed");
1910              return -1;
1911          }
1912    }
1913 
1914    return sock;
1915 }
1916 
1917 #else
1918 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1919     return openSocket(env,AF_INET);
1920 }
1921 #endif
1922 
1923 /*
1924  * Enumerates and returns all IPv4 interfaces.
1925  */
1926 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1927     struct ifaddrs *ifa, *origifa;
1928 
1929     if (getifaddrs(&origifa) != 0) {
1930         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1931                                      "getifaddrs() function failed");
1932         return ifs;
1933     }
1934 
1935     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
1936         struct sockaddr* ifa_broadaddr = NULL;
1937 
1938         // Skip non-AF_INET entries.
1939         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
1940             continue;
1941 
1942         // set ifa_broadaddr, if there is one
1943         if ((ifa->ifa_flags & IFF_POINTOPOINT) == 0 &&
1944             ifa->ifa_flags & IFF_BROADCAST) {
1945             ifa_broadaddr = ifa->ifa_broadaddr;
1946         }
1947 
1948         // Add to the list.
1949         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr,
1950                     ifa_broadaddr, ifa->ifa_netmask, AF_INET, 0);
1951 
1952         // If an exception occurred then free the list.
1953         if ((*env)->ExceptionOccurred(env)) {
1954             freeifaddrs(origifa);
1955             freeif(ifs);
1956             return NULL;
1957         }
1958     }
1959 
1960     // Free socket and buffer
1961     freeifaddrs(origifa);
1962     return ifs;
1963 }
1964 
1965 #ifdef AF_INET6
1966 /*
1967  * Determines the prefix on BSD for IPv6 interfaces.
1968  */
1969 static int prefix(void *val, int size) {
1970     u_char *name = (u_char *)val;
1971     int byte, bit, prefix = 0;
1972 
1973     for (byte = 0; byte < size; byte++, prefix += 8)
1974         if (name[byte] != 0xff)
1975             break;
1976     if (byte == size)
1977         return prefix;
1978     for (bit = 7; bit != 0; bit--, prefix++)
1979         if (!(name[byte] & (1 << bit)))
1980             break;
1981     for (; bit != 0; bit--)
1982         if (name[byte] & (1 << bit))
1983             return (0);
1984     byte++;
1985     for (; byte < size; byte++)
1986         if (name[byte])
1987             return (0);
1988     return prefix;
1989 }
1990 
1991 /*
1992  * Enumerates and returns all IPv6 interfaces on BSD.
1993  */
1994 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1995     struct ifaddrs *ifa, *origifa;
1996     struct sockaddr_in6 *sin6;
1997     struct in6_ifreq ifr6;
1998 
1999     if (getifaddrs(&origifa) != 0) {
2000         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2001                                      "getifaddrs() function failed");
2002         return ifs;
2003     }
2004 
2005     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
2006 
2007         // Skip non-AF_INET6 entries.
2008         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
2009             continue;
2010 
2011         memset(&ifr6, 0, sizeof(ifr6));
2012         strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
2013         memcpy(&ifr6.ifr_addr, ifa->ifa_addr,
2014                MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
2015 
2016         if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
2017             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2018                                          "ioctl SIOCGIFNETMASK_IN6 failed");
2019             freeifaddrs(origifa);
2020             freeif(ifs);
2021             return NULL;
2022         }
2023 
2024         // Add to the list.
2025         sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
2026         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL, NULL,
2027                     AF_INET6,
2028                     (short)prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
2029 
2030         // If an exception occurred then free the list.
2031         if ((*env)->ExceptionOccurred(env)) {
2032             freeifaddrs(origifa);
2033             freeif(ifs);
2034             return NULL;
2035         }
2036     }
2037 
2038     // Free socket and ifaddrs buffer
2039     freeifaddrs(origifa);
2040     return ifs;
2041 }
2042 #endif
2043 
2044 static int getIndex(int sock, const char *name) {
2045 #ifdef __FreeBSD__
2046     // Try to get the interface index
2047     // (Not supported on Solaris 2.6 or 7)
2048     struct ifreq if2;
2049     memset((char *)&if2, 0, sizeof(if2));
2050     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
2051 
2052     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
2053         return -1;
2054     }
2055 
2056     return if2.ifr_index;
2057 #else
2058     // Try to get the interface index using BSD specific if_nametoindex
2059     int index = if_nametoindex(name);
2060     return (index == 0) ? -1 : index;
2061 #endif
2062 }
2063 
2064 /*
2065  * Returns the IPv4 broadcast address of a named interface, if it exists.
2066  * Returns 0 if it doesn't have one.
2067  */
2068 static struct sockaddr *getBroadcast
2069   (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
2070 {
2071     struct sockaddr *ret = NULL;
2072     struct ifreq if2;
2073     memset((char *)&if2, 0, sizeof(if2));
2074     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2075 
2076     // Make sure the interface does have a broadcast address
2077     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
2078         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2079                                      "ioctl SIOCGIFFLAGS failed");
2080         return ret;
2081     }
2082 
2083     if (if2.ifr_flags & IFF_BROADCAST) {
2084         // It does, let's retrieve it
2085         if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
2086             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2087                                          "ioctl SIOCGIFBRDADDR failed");
2088             return ret;
2089         }
2090 
2091         ret = brdcast_store;
2092         memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
2093     }
2094 
2095     return ret;
2096 }
2097 
2098 /*
2099  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
2100  * interface, if it has one, otherwise return -1.
2101  */
2102 static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
2103     unsigned int mask;
2104     short ret;
2105     struct ifreq if2;
2106     memset((char *)&if2, 0, sizeof(if2));
2107     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2108 
2109     if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
2110         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2111                                      "ioctl SIOCGIFNETMASK failed");
2112         return -1;
2113     }
2114 
2115     return computeMaskFromAddress(&(if2.ifr_addr));
2116 }
2117 
2118 /*
2119  * Gets the Hardware address (usually MAC address) for the named interface.
2120  * return puts the data in buf, and returns the length, in byte, of the
2121  * MAC address. Returns -1 if there is no hardware address on that interface.
2122  */
2123 static int getMacAddress
2124   (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
2125    unsigned char *buf)
2126 {
2127     struct ifaddrs *ifa0, *ifa;
2128     struct sockaddr *saddr;
2129     int i;
2130 
2131     // Grab the interface list
2132     if (!getifaddrs(&ifa0)) {
2133         // Cycle through the interfaces
2134         for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
2135             saddr = ifa->ifa_addr;
2136             // Link layer contains the MAC address
2137             if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
2138                 struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
2139                 // Check the address is the correct length
2140                 if (sadl->sdl_alen == ETHER_ADDR_LEN) {
2141                     memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
2142                     freeifaddrs(ifa0);
2143                     return ETHER_ADDR_LEN;
2144                 }
2145             }
2146         }
2147         freeifaddrs(ifa0);
2148     }
2149 
2150     return -1;
2151 }
2152 
2153 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
2154     struct ifreq if2;
2155     memset((char *)&if2, 0, sizeof(if2));
2156     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2157 
2158     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
2159         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
2160                                      "ioctl SIOCGIFMTU failed");
2161         return -1;
2162     }
2163 
2164     return  if2.ifr_mtu;
2165 }
2166 
2167 static int getFlags(int sock, const char *ifname, int *flags) {
2168     struct ifreq if2;
2169     int ret = -1;
2170     memset((char *)&if2, 0, sizeof(if2));
2171     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2172 
2173     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
2174         return -1;
2175     }
2176 
2177     if (sizeof(if2.ifr_flags) == sizeof(short)) {
2178         *flags = (if2.ifr_flags & 0xffff);
2179     } else {
2180         *flags = if2.ifr_flags;
2181     }
2182     return 0;
2183 }
2184 #endif /* __ALLBSD_SOURCE__ */