Home | History | Annotate | Download | only in net
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.net;
     18 
     19 import java.io.FileDescriptor;
     20 import java.net.InetAddress;
     21 import java.net.Inet4Address;
     22 import java.net.Inet6Address;
     23 import java.net.SocketException;
     24 import java.net.UnknownHostException;
     25 import java.util.Collection;
     26 import java.util.Locale;
     27 
     28 import android.os.Parcel;
     29 import android.util.Log;
     30 import android.util.Pair;
     31 
     32 
     33 /**
     34  * Native methods for managing network interfaces.
     35  *
     36  * {@hide}
     37  */
     38 public class NetworkUtils {
     39 
     40     private static final String TAG = "NetworkUtils";
     41 
     42     /** Setting bit 0 indicates reseting of IPv4 addresses required */
     43     public static final int RESET_IPV4_ADDRESSES = 0x01;
     44 
     45     /** Setting bit 1 indicates reseting of IPv4 addresses required */
     46     public static final int RESET_IPV6_ADDRESSES = 0x02;
     47 
     48     /** Reset all addresses */
     49     public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
     50 
     51     /**
     52      * Reset IPv6 or IPv4 sockets that are connected via the named interface.
     53      *
     54      * @param interfaceName is the interface to reset
     55      * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
     56      */
     57     public native static int resetConnections(String interfaceName, int mask);
     58 
     59     /**
     60      * Start the DHCP client daemon, in order to have it request addresses
     61      * for the named interface.  This returns {@code true} if the DHCPv4 daemon
     62      * starts, {@code false} otherwise.  This call blocks until such time as a
     63      * result is available or the default discovery timeout has been reached.
     64      * Callers should check {@link #getDhcpResults} to determine whether DHCP
     65      * succeeded or failed, and if it succeeded, to fetch the {@link DhcpResults}.
     66      * @param interfaceName the name of the interface to configure
     67      * @return {@code true} for success, {@code false} for failure
     68      */
     69     public native static boolean startDhcp(String interfaceName);
     70 
     71     /**
     72      * Initiate renewal on the DHCP client daemon for the named interface.  This
     73      * returns {@code true} if the DHCPv4 daemon has been notified, {@code false}
     74      * otherwise.  This call blocks until such time as a result is available or
     75      * the default renew timeout has been reached.  Callers should check
     76      * {@link #getDhcpResults} to determine whether DHCP succeeded or failed,
     77      * and if it succeeded, to fetch the {@link DhcpResults}.
     78      * @param interfaceName the name of the interface to configure
     79      * @return {@code true} for success, {@code false} for failure
     80      */
     81     public native static boolean startDhcpRenew(String interfaceName);
     82 
     83     /**
     84      * Start the DHCP client daemon, in order to have it request addresses
     85      * for the named interface, and then configure the interface with those
     86      * addresses. This call blocks until it obtains a result (either success
     87      * or failure) from the daemon.
     88      * @param interfaceName the name of the interface to configure
     89      * @param dhcpResults if the request succeeds, this object is filled in with
     90      * the IP address information.
     91      * @return {@code true} for success, {@code false} for failure
     92      */
     93     public static boolean runDhcp(String interfaceName, DhcpResults dhcpResults) {
     94         return startDhcp(interfaceName) && getDhcpResults(interfaceName, dhcpResults);
     95     }
     96 
     97     /**
     98      * Initiate renewal on the DHCP client daemon. This call blocks until it obtains
     99      * a result (either success or failure) from the daemon.
    100      * @param interfaceName the name of the interface to configure
    101      * @param dhcpResults if the request succeeds, this object is filled in with
    102      * the IP address information.
    103      * @return {@code true} for success, {@code false} for failure
    104      */
    105     public static boolean runDhcpRenew(String interfaceName, DhcpResults dhcpResults) {
    106         return startDhcpRenew(interfaceName) && getDhcpResults(interfaceName, dhcpResults);
    107     }
    108 
    109     /**
    110      * Fetch results from the DHCP client daemon. This call returns {@code true} if
    111      * if there are results available to be read, {@code false} otherwise.
    112      * @param interfaceName the name of the interface to configure
    113      * @param dhcpResults if the request succeeds, this object is filled in with
    114      * the IP address information.
    115      * @return {@code true} for success, {@code false} for failure
    116      */
    117     public native static boolean getDhcpResults(String interfaceName, DhcpResults dhcpResults);
    118 
    119     /**
    120      * Shut down the DHCP client daemon.
    121      * @param interfaceName the name of the interface for which the daemon
    122      * should be stopped
    123      * @return {@code true} for success, {@code false} for failure
    124      */
    125     public native static boolean stopDhcp(String interfaceName);
    126 
    127     /**
    128      * Release the current DHCP lease.
    129      * @param interfaceName the name of the interface for which the lease should
    130      * be released
    131      * @return {@code true} for success, {@code false} for failure
    132      */
    133     public native static boolean releaseDhcpLease(String interfaceName);
    134 
    135     /**
    136      * Return the last DHCP-related error message that was recorded.
    137      * <p/>NOTE: This string is not localized, but currently it is only
    138      * used in logging.
    139      * @return the most recent error message, if any
    140      */
    141     public native static String getDhcpError();
    142 
    143     /**
    144      * Attaches a socket filter that accepts DHCP packets to the given socket.
    145      */
    146     public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
    147 
    148     /**
    149      * Binds the current process to the network designated by {@code netId}.  All sockets created
    150      * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
    151      * {@link Network#getSocketFactory}) will be bound to this network.  Note that if this
    152      * {@code Network} ever disconnects all sockets created in this way will cease to work.  This
    153      * is by design so an application doesn't accidentally use sockets it thinks are still bound to
    154      * a particular {@code Network}.  Passing NETID_UNSET clears the binding.
    155      */
    156     public native static boolean bindProcessToNetwork(int netId);
    157 
    158     /**
    159      * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
    160      * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
    161      */
    162     public native static int getBoundNetworkForProcess();
    163 
    164     /**
    165      * Binds host resolutions performed by this process to the network designated by {@code netId}.
    166      * {@link #bindProcessToNetwork} takes precedence over this setting.  Passing NETID_UNSET clears
    167      * the binding.
    168      *
    169      * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
    170      */
    171     public native static boolean bindProcessToNetworkForHostResolution(int netId);
    172 
    173     /**
    174      * Explicitly binds {@code socketfd} to the network designated by {@code netId}.  This
    175      * overrides any binding via {@link #bindProcessToNetwork}.
    176      * @return 0 on success or negative errno on failure.
    177      */
    178     public native static int bindSocketToNetwork(int socketfd, int netId);
    179 
    180     /**
    181      * Protect {@code fd} from VPN connections.  After protecting, data sent through
    182      * this socket will go directly to the underlying network, so its traffic will not be
    183      * forwarded through the VPN.
    184      */
    185     public static boolean protectFromVpn(FileDescriptor fd) {
    186         return protectFromVpn(fd.getInt$());
    187     }
    188 
    189     /**
    190      * Protect {@code socketfd} from VPN connections.  After protecting, data sent through
    191      * this socket will go directly to the underlying network, so its traffic will not be
    192      * forwarded through the VPN.
    193      */
    194     public native static boolean protectFromVpn(int socketfd);
    195 
    196     /**
    197      * Determine if {@code uid} can access network designated by {@code netId}.
    198      * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
    199      */
    200     public native static boolean queryUserAccess(int uid, int netId);
    201 
    202     /**
    203      * Convert a IPv4 address from an integer to an InetAddress.
    204      * @param hostAddress an int corresponding to the IPv4 address in network byte order
    205      */
    206     public static InetAddress intToInetAddress(int hostAddress) {
    207         byte[] addressBytes = { (byte)(0xff & hostAddress),
    208                                 (byte)(0xff & (hostAddress >> 8)),
    209                                 (byte)(0xff & (hostAddress >> 16)),
    210                                 (byte)(0xff & (hostAddress >> 24)) };
    211 
    212         try {
    213            return InetAddress.getByAddress(addressBytes);
    214         } catch (UnknownHostException e) {
    215            throw new AssertionError();
    216         }
    217     }
    218 
    219     /**
    220      * Convert a IPv4 address from an InetAddress to an integer
    221      * @param inetAddr is an InetAddress corresponding to the IPv4 address
    222      * @return the IP address as an integer in network byte order
    223      */
    224     public static int inetAddressToInt(Inet4Address inetAddr)
    225             throws IllegalArgumentException {
    226         byte [] addr = inetAddr.getAddress();
    227         return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
    228                 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
    229     }
    230 
    231     /**
    232      * Convert a network prefix length to an IPv4 netmask integer
    233      * @param prefixLength
    234      * @return the IPv4 netmask as an integer in network byte order
    235      */
    236     public static int prefixLengthToNetmaskInt(int prefixLength)
    237             throws IllegalArgumentException {
    238         if (prefixLength < 0 || prefixLength > 32) {
    239             throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
    240         }
    241         int value = 0xffffffff << (32 - prefixLength);
    242         return Integer.reverseBytes(value);
    243     }
    244 
    245     /**
    246      * Convert a IPv4 netmask integer to a prefix length
    247      * @param netmask as an integer in network byte order
    248      * @return the network prefix length
    249      */
    250     public static int netmaskIntToPrefixLength(int netmask) {
    251         return Integer.bitCount(netmask);
    252     }
    253 
    254     /**
    255      * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
    256      * @param netmask as a {@code Inet4Address}.
    257      * @return the network prefix length
    258      * @throws IllegalArgumentException the specified netmask was not contiguous.
    259      * @hide
    260      */
    261     public static int netmaskToPrefixLength(Inet4Address netmask) {
    262         // inetAddressToInt returns an int in *network* byte order.
    263         int i = Integer.reverseBytes(inetAddressToInt(netmask));
    264         int prefixLength = Integer.bitCount(i);
    265         int trailingZeros = Integer.numberOfTrailingZeros(i);
    266         if (trailingZeros != 32 - prefixLength) {
    267             throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
    268         }
    269         return prefixLength;
    270     }
    271 
    272 
    273     /**
    274      * Create an InetAddress from a string where the string must be a standard
    275      * representation of a V4 or V6 address.  Avoids doing a DNS lookup on failure
    276      * but it will throw an IllegalArgumentException in that case.
    277      * @param addrString
    278      * @return the InetAddress
    279      * @hide
    280      */
    281     public static InetAddress numericToInetAddress(String addrString)
    282             throws IllegalArgumentException {
    283         return InetAddress.parseNumericAddress(addrString);
    284     }
    285 
    286     /**
    287      * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
    288      * calling writeSerializable.
    289      */
    290     protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
    291         byte[] addressArray = (address != null) ? address.getAddress() : null;
    292         parcel.writeByteArray(addressArray);
    293     }
    294 
    295     /**
    296      * Reads an InetAddress from a parcel. Returns null if the address that was written was null
    297      * or if the data is invalid.
    298      */
    299     protected static InetAddress unparcelInetAddress(Parcel in) {
    300         byte[] addressArray = in.createByteArray();
    301         if (addressArray == null) {
    302             return null;
    303         }
    304         try {
    305             return InetAddress.getByAddress(addressArray);
    306         } catch (UnknownHostException e) {
    307             return null;
    308         }
    309     }
    310 
    311 
    312     /**
    313      *  Masks a raw IP address byte array with the specified prefix length.
    314      */
    315     public static void maskRawAddress(byte[] array, int prefixLength) {
    316         if (prefixLength < 0 || prefixLength > array.length * 8) {
    317             throw new RuntimeException("IP address with " + array.length +
    318                     " bytes has invalid prefix length " + prefixLength);
    319         }
    320 
    321         int offset = prefixLength / 8;
    322         int remainder = prefixLength % 8;
    323         byte mask = (byte)(0xFF << (8 - remainder));
    324 
    325         if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
    326 
    327         offset++;
    328 
    329         for (; offset < array.length; offset++) {
    330             array[offset] = 0;
    331         }
    332     }
    333 
    334     /**
    335      * Get InetAddress masked with prefixLength.  Will never return null.
    336      * @param address the IP address to mask with
    337      * @param prefixLength the prefixLength used to mask the IP
    338      */
    339     public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    340         byte[] array = address.getAddress();
    341         maskRawAddress(array, prefixLength);
    342 
    343         InetAddress netPart = null;
    344         try {
    345             netPart = InetAddress.getByAddress(array);
    346         } catch (UnknownHostException e) {
    347             throw new RuntimeException("getNetworkPart error - " + e.toString());
    348         }
    349         return netPart;
    350     }
    351 
    352     /**
    353      * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
    354      */
    355     public static int getImplicitNetmask(Inet4Address address) {
    356         int firstByte = address.getAddress()[0] & 0xff;  // Convert to an unsigned value.
    357         if (firstByte < 128) {
    358             return 8;
    359         } else if (firstByte < 192) {
    360             return 16;
    361         } else if (firstByte < 224) {
    362             return 24;
    363         } else {
    364             return 32;  // Will likely not end well for other reasons.
    365         }
    366     }
    367 
    368     /**
    369      * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
    370      * @hide
    371      */
    372     public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
    373         InetAddress address = null;
    374         int prefixLength = -1;
    375         try {
    376             String[] pieces = ipAndMaskString.split("/", 2);
    377             prefixLength = Integer.parseInt(pieces[1]);
    378             address = InetAddress.parseNumericAddress(pieces[0]);
    379         } catch (NullPointerException e) {            // Null string.
    380         } catch (ArrayIndexOutOfBoundsException e) {  // No prefix length.
    381         } catch (NumberFormatException e) {           // Non-numeric prefix.
    382         } catch (IllegalArgumentException e) {        // Invalid IP address.
    383         }
    384 
    385         if (address == null || prefixLength == -1) {
    386             throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
    387         }
    388 
    389         return new Pair<InetAddress, Integer>(address, prefixLength);
    390     }
    391 
    392     /**
    393      * Check if IP address type is consistent between two InetAddress.
    394      * @return true if both are the same type.  False otherwise.
    395      */
    396     public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
    397         return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
    398                 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
    399     }
    400 
    401     /**
    402      * Convert a 32 char hex string into a Inet6Address.
    403      * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
    404      * made into an Inet6Address
    405      * @param addrHexString a 32 character hex string representing an IPv6 addr
    406      * @return addr an InetAddress representation for the string
    407      */
    408     public static InetAddress hexToInet6Address(String addrHexString)
    409             throws IllegalArgumentException {
    410         try {
    411             return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
    412                     addrHexString.substring(0,4),   addrHexString.substring(4,8),
    413                     addrHexString.substring(8,12),  addrHexString.substring(12,16),
    414                     addrHexString.substring(16,20), addrHexString.substring(20,24),
    415                     addrHexString.substring(24,28), addrHexString.substring(28,32)));
    416         } catch (Exception e) {
    417             Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
    418             throw new IllegalArgumentException(e);
    419         }
    420     }
    421 
    422     /**
    423      * Create a string array of host addresses from a collection of InetAddresses
    424      * @param addrs a Collection of InetAddresses
    425      * @return an array of Strings containing their host addresses
    426      */
    427     public static String[] makeStrings(Collection<InetAddress> addrs) {
    428         String[] result = new String[addrs.size()];
    429         int i = 0;
    430         for (InetAddress addr : addrs) {
    431             result[i++] = addr.getHostAddress();
    432         }
    433         return result;
    434     }
    435 
    436     /**
    437      * Trim leading zeros from IPv4 address strings
    438      * Our base libraries will interpret that as octel..
    439      * Must leave non v4 addresses and host names alone.
    440      * For example, 192.168.000.010 -> 192.168.0.10
    441      * TODO - fix base libraries and remove this function
    442      * @param addr a string representing an ip addr
    443      * @return a string propertly trimmed
    444      */
    445     public static String trimV4AddrZeros(String addr) {
    446         if (addr == null) return null;
    447         String[] octets = addr.split("\\.");
    448         if (octets.length != 4) return addr;
    449         StringBuilder builder = new StringBuilder(16);
    450         String result = null;
    451         for (int i = 0; i < 4; i++) {
    452             try {
    453                 if (octets[i].length() > 3) return addr;
    454                 builder.append(Integer.parseInt(octets[i]));
    455             } catch (NumberFormatException e) {
    456                 return addr;
    457             }
    458             if (i < 3) builder.append('.');
    459         }
    460         result = builder.toString();
    461         return result;
    462     }
    463 }
    464