android.net.LinkAddress Java Examples

The following examples show how to use android.net.LinkAddress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Nat464Xlat.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private LinkProperties makeLinkProperties(LinkAddress clatAddress) {
    LinkProperties stacked = new LinkProperties();
    stacked.setInterfaceName(mIface);

    // Although the clat interface is a point-to-point tunnel, we don't
    // point the route directly at the interface because some apps don't
    // understand routes without gateways (see, e.g., http://b/9597256
    // http://b/9597516). Instead, set the next hop of the route to the
    // clat IPv4 address itself (for those apps, it doesn't matter what
    // the IP of the gateway is, only that there is one).
    RouteInfo ipv4Default = new RouteInfo(
            new LinkAddress(Inet4Address.ANY, 0),
            clatAddress.getAddress(), mIface);
    stacked.addRoute(ipv4Default);
    stacked.addLinkAddress(clatAddress);
    return stacked;
}
 
Example #2
Source File: XLinkProperties.java    From XPrivacy with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void after(XParam param) throws Throwable {
	switch (mMethod) {
	case getAddresses:
	case getAllAddresses:
		if (param.getResult() != null)
			if (isRestricted(param))
				param.setResult(new ArrayList<InetAddress>());
		break;

	case getAllLinkAddresses:
	case getLinkAddresses:
		if (param.getResult() != null)
			if (isRestricted(param))
				param.setResult(new ArrayList<LinkAddress>());
		break;

	case getStackedLinks:
		if (param.getResult() != null)
			if (isRestricted(param))
				param.setResult(new ArrayList<LinkProperties>());
		break;
	}
}
 
Example #3
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a new local address from the tunnel interface. After removal, the address will no
 * longer be available to send from, or receive on.
 */
@Override
public synchronized void removeAddressFromTunnelInterface(
        int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
    enforceTunnelPermissions(callingPackage);

    UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
    // Get tunnelInterface record; if no such interface is found, will throw
    // IllegalArgumentException
    TunnelInterfaceRecord tunnelInterfaceInfo =
            userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);

    try {
        // We can assume general validity of the IP address, since we get them as a
        // LinkAddress, which does some validation.
        mSrvConfig
                .getNetdInstance()
                .interfaceDelAddress(
                        tunnelInterfaceInfo.mInterfaceName,
                        localAddr.getAddress().getHostAddress(),
                        localAddr.getPrefixLength());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #4
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new local address to the tunnel interface. This allows packets to be sent and received
 * from multiple local IP addresses over the same tunnel.
 */
@Override
public synchronized void addAddressToTunnelInterface(
        int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
    enforceTunnelPermissions(callingPackage);
    UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());

    // Get tunnelInterface record; if no such interface is found, will throw
    // IllegalArgumentException
    TunnelInterfaceRecord tunnelInterfaceInfo =
            userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);

    try {
        // We can assume general validity of the IP address, since we get them as a
        // LinkAddress, which does some validation.
        mSrvConfig
                .getNetdInstance()
                .interfaceAddAddress(
                        tunnelInterfaceInfo.mInterfaceName,
                        localAddr.getAddress().getHostAddress(),
                        localAddr.getPrefixLength());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #5
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
    mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

    final Command cmd = new Command("network", "route", "legacy", uid, "add", netId);

    // create triplet: interface dest-ip-addr/prefixlength gateway-ip-addr
    final LinkAddress la = routeInfo.getDestinationLinkAddress();
    cmd.appendArg(routeInfo.getInterface());
    cmd.appendArg(la.getAddress().getHostAddress() + "/" + la.getPrefixLength());
    if (routeInfo.hasGateway()) {
        cmd.appendArg(routeInfo.getGateway().getHostAddress());
    }

    try {
        mConnector.execute(cmd);
    } catch (NativeDaemonConnectorException e) {
        throw e.rethrowAsParcelableException();
    }
}
 
Example #6
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
    mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
    LinkAddress linkAddr = cfg.getLinkAddress();
    if (linkAddr == null || linkAddr.getAddress() == null) {
        throw new IllegalStateException("Null LinkAddress given");
    }

    final Command cmd = new Command("interface", "setcfg", iface,
            linkAddr.getAddress().getHostAddress(),
            linkAddr.getPrefixLength());
    for (String flag : cfg.getFlags()) {
        cmd.appendArg(flag);
    }

    try {
        mConnector.execute(cmd);
    } catch (NativeDaemonConnectorException e) {
        throw e.rethrowAsParcelableException();
    }
}
 
Example #7
Source File: Nat464Xlat.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Adds stacked link on base link and transitions to RUNNING state.
 */
private void handleInterfaceLinkStateChanged(String iface, boolean up) {
    if (!isStarting() || !up || !Objects.equals(mIface, iface)) {
        return;
    }

    LinkAddress clatAddress = getLinkAddress(iface);
    if (clatAddress == null) {
        Slog.e(TAG, "clatAddress was null for stacked iface " + iface);
        return;
    }

    Slog.i(TAG, String.format("interface %s is up, adding stacked link %s on top of %s",
            mIface, mIface, mBaseIface));
    enterRunningState();
    LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
    lp.addStackedLink(makeLinkProperties(clatAddress));
    mNetwork.connService().handleUpdateLinkProperties(mNetwork, lp);
}
 
Example #8
Source File: NetworkDiagnostics.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void prepareExplicitSourceIcmpMeasurements(InetAddress target) {
    for (LinkAddress l : mLinkProperties.getLinkAddresses()) {
        InetAddress source = l.getAddress();
        if (source instanceof Inet6Address && l.isGlobalPreferred()) {
            Pair<InetAddress, InetAddress> srcTarget = new Pair<>(source, target);
            if (!mExplicitSourceIcmpChecks.containsKey(srcTarget)) {
                Measurement measurement = new Measurement();
                measurement.thread = new Thread(new IcmpCheck(source, target, measurement));
                mExplicitSourceIcmpChecks.put(srcTarget, measurement);
            }
        }
    }
}
 
Example #9
Source File: NetworkMonitorAutoDetect.java    From webrtc_android with MIT License 5 votes vote down vote up
@SuppressLint("NewApi")
IPAddress[] getIPAddresses(LinkProperties linkProperties) {
  IPAddress[] ipAddresses = new IPAddress[linkProperties.getLinkAddresses().size()];
  int i = 0;
  for (LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
    ipAddresses[i] = new IPAddress(linkAddress.getAddress().getAddress());
    ++i;
  }
  return ipAddresses;
}
 
Example #10
Source File: ProxyStaticIpConfiguration.java    From astrobee_android with Apache License 2.0 5 votes vote down vote up
public static void initialize() throws ReflectiveOperationException {
    if (s_linkAddrCtor != null)
        return;

    s_staticConfigCls = Class.forName("android.net.StaticIpConfiguration");
    s_ipAddressFld = s_staticConfigCls.getField("ipAddress");
    s_gatewayFld = s_staticConfigCls.getField("gateway");
    s_dnsServersFld = s_staticConfigCls.getField("dnsServers");
    s_domainsFld = s_staticConfigCls.getField("domains");

    s_linkAddrCtor = LinkAddress.class.getConstructor(InetAddress.class, int.class);
}
 
Example #11
Source File: GnirehtetService.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
private Network findVpnNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Network[] networks = cm.getAllNetworks();
    for (Network network : networks) {
        LinkProperties linkProperties = cm.getLinkProperties(network);
        List<LinkAddress> addresses = linkProperties.getLinkAddresses();
        for (LinkAddress addr : addresses) {
            if (addr.getAddress().equals(VPN_ADDRESS)) {
                return network;
            }
        }
    }
    return null;
}
 
Example #12
Source File: LocalIPUtil.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private String getIp(LinkProperties lp) {
    List<LinkAddress> linkAddresses = lp.getLinkAddresses();
    for(LinkAddress linkAddress: linkAddresses) {
        InetAddress inetAddress = linkAddress.getAddress();
        if (inetAddress instanceof Inet4Address) {
            return inetAddress.getHostAddress();
        }
    }
    return null;
}
 
Example #13
Source File: Nat464Xlat.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private LinkAddress getLinkAddress(String iface) {
    try {
        InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
        return config.getLinkAddress();
    } catch(RemoteException|IllegalStateException e) {
        Slog.e(TAG, "Error getting link properties: " + e);
        return null;
    }
}
 
Example #14
Source File: OffloadController.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static Set<String> computeLocalPrefixStrings(
        Set<IpPrefix> localPrefixes, LinkProperties upstreamLinkProperties) {
    // Create an editable copy.
    final Set<IpPrefix> prefixSet = new HashSet<>(localPrefixes);

    // TODO: If a downstream interface (not currently passed in) is reusing
    // the /64 of the upstream (64share) then:
    //
    //     [a] remove that /64 from the local prefixes
    //     [b] add in /128s for IP addresses on the downstream interface
    //     [c] add in /128s for IP addresses on the upstream interface
    //
    // Until downstream information is available here, simply add /128s from
    // the upstream network; they'll just be redundant with their /64.
    if (upstreamLinkProperties != null) {
        for (LinkAddress linkAddr : upstreamLinkProperties.getLinkAddresses()) {
            if (!linkAddr.isGlobalPreferred()) continue;
            final InetAddress ip = linkAddr.getAddress();
            if (!(ip instanceof Inet6Address)) continue;
            prefixSet.add(new IpPrefix(ip, 128));
        }
    }

    final HashSet<String> localPrefixStrs = new HashSet<>();
    for (IpPrefix pfx : prefixSet) localPrefixStrs.add(pfx.toString());
    return localPrefixStrs;
}
 
Example #15
Source File: TetherInterfaceStateMachine.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
    if (mRaDaemon == null) return;

    // Avoid unnecessary work on spurious updates.
    if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
        return;
    }

    RaParams params = null;

    if (v6only != null) {
        params = new RaParams();
        params.mtu = v6only.getMtu();
        params.hasDefaultRoute = v6only.hasIPv6DefaultRoute();

        for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
            if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;

            final IpPrefix prefix = new IpPrefix(
                    linkAddr.getAddress(), linkAddr.getPrefixLength());
            params.prefixes.add(prefix);

            final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
            if (dnsServer != null) {
                params.dnses.add(dnsServer);
            }
        }
    }
    // If v6only is null, we pass in null to setRaParams(), which handles
    // deprecation of any existing RA data.

    setRaParams(params);
    mLastIPv6LinkProperties = v6only;
}
 
Example #16
Source File: Tethering.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void sendOffloadExemptPrefixes(final Set<IpPrefix> localPrefixes) {
    // Add in well-known minimum set.
    PrefixUtils.addNonForwardablePrefixes(localPrefixes);
    // Add tragically hardcoded prefixes.
    localPrefixes.add(PrefixUtils.DEFAULT_WIFI_P2P_PREFIX);

    // Maybe add prefixes or addresses for downstreams, depending on
    // the IP serving mode of each.
    for (TetherInterfaceStateMachine tism : mNotifyList) {
        final LinkProperties lp = tism.linkProperties();

        switch (tism.servingMode()) {
            case IControlsTethering.STATE_UNAVAILABLE:
            case IControlsTethering.STATE_AVAILABLE:
                // No usable LinkProperties in these states.
                continue;
            case IControlsTethering.STATE_TETHERED:
                // Only add IPv4 /32 and IPv6 /128 prefixes. The
                // directly-connected prefixes will be sent as
                // downstream "offload-able" prefixes.
                for (LinkAddress addr : lp.getAllLinkAddresses()) {
                    final InetAddress ip = addr.getAddress();
                    if (ip.isLinkLocalAddress()) continue;
                    localPrefixes.add(PrefixUtils.ipAddressAsPrefix(ip));
                }
                break;
            case IControlsTethering.STATE_LOCAL_ONLY:
                // Add prefixes covering all local IPs.
                localPrefixes.addAll(PrefixUtils.localPrefixesFrom(lp));
                break;
        }
    }

    mOffloadController.setLocalPrefixes(localPrefixes);
}
 
Example #17
Source File: IPv6TetheringCoordinator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static LinkProperties getUniqueLocalConfig(byte[] ulp, short subnetId) {
    final LinkProperties lp = new LinkProperties();

    final IpPrefix local48 = makeUniqueLocalPrefix(ulp, (short) 0, 48);
    lp.addRoute(new RouteInfo(local48, null, null));

    final IpPrefix local64 = makeUniqueLocalPrefix(ulp, subnetId, 64);
    // Because this is a locally-generated ULA, we don't have an upstream
    // address. But because the downstream IP address management code gets
    // its prefix from the upstream's IP address, we create a fake one here.
    lp.addLinkAddress(new LinkAddress(local64.getAddress(), 64));

    lp.setMtu(NetworkConstants.ETHER_MTU);
    return lp;
}
 
Example #18
Source File: IPv6TetheringCoordinator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static LinkProperties getIPv6OnlyLinkProperties(LinkProperties lp) {
    final LinkProperties v6only = new LinkProperties();
    if (lp == null) {
        return v6only;
    }

    // NOTE: At this time we don't copy over any information about any
    // stacked links. No current stacked link configuration has IPv6.

    v6only.setInterfaceName(lp.getInterfaceName());

    v6only.setMtu(lp.getMtu());

    for (LinkAddress linkAddr : lp.getLinkAddresses()) {
        if (linkAddr.isGlobalPreferred() && linkAddr.getPrefixLength() == 64) {
            v6only.addLinkAddress(linkAddr);
        }
    }

    for (RouteInfo routeInfo : lp.getRoutes()) {
        final IpPrefix destination = routeInfo.getDestination();
        if ((destination.getAddress() instanceof Inet6Address) &&
            (destination.getPrefixLength() <= 64)) {
            v6only.addRoute(routeInfo);
        }
    }

    for (InetAddress dnsServer : lp.getDnsServers()) {
        if (isIPv6GlobalAddress(dnsServer)) {
            // For now we include ULAs.
            v6only.addDnsServer(dnsServer);
        }
    }

    v6only.setDomains(lp.getDomains());

    return v6only;
}
 
Example #19
Source File: LockdownVpnTracker.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Watch for state changes to both active egress network, kicking off a VPN
 * connection when ready, or setting firewall rules once VPN is connected.
 */
private void handleStateChangedLocked() {

    final NetworkInfo egressInfo = mConnService.getActiveNetworkInfoUnfiltered();
    final LinkProperties egressProp = mConnService.getActiveLinkProperties();

    final NetworkInfo vpnInfo = mVpn.getNetworkInfo();
    final VpnConfig vpnConfig = mVpn.getLegacyVpnConfig();

    // Restart VPN when egress network disconnected or changed
    final boolean egressDisconnected = egressInfo == null
            || State.DISCONNECTED.equals(egressInfo.getState());
    final boolean egressChanged = egressProp == null
            || !TextUtils.equals(mAcceptedEgressIface, egressProp.getInterfaceName());

    final String egressTypeName = (egressInfo == null) ?
            null : ConnectivityManager.getNetworkTypeName(egressInfo.getType());
    final String egressIface = (egressProp == null) ?
            null : egressProp.getInterfaceName();
    Slog.d(TAG, "handleStateChanged: egress=" + egressTypeName +
            " " + mAcceptedEgressIface + "->" + egressIface);

    if (egressDisconnected || egressChanged) {
        mAcceptedEgressIface = null;
        mVpn.stopLegacyVpnPrivileged();
    }
    if (egressDisconnected) {
        hideNotification();
        return;
    }

    final int egressType = egressInfo.getType();
    if (vpnInfo.getDetailedState() == DetailedState.FAILED) {
        EventLogTags.writeLockdownVpnError(egressType);
    }

    if (mErrorCount > MAX_ERROR_COUNT) {
        showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);

    } else if (egressInfo.isConnected() && !vpnInfo.isConnectedOrConnecting()) {
        if (mProfile.isValidLockdownProfile()) {
            Slog.d(TAG, "Active network connected; starting VPN");
            EventLogTags.writeLockdownVpnConnecting(egressType);
            showNotification(R.string.vpn_lockdown_connecting, R.drawable.vpn_disconnected);

            mAcceptedEgressIface = egressProp.getInterfaceName();
            try {
                // Use the privileged method because Lockdown VPN is initiated by the system, so
                // no additional permission checks are necessary.
                mVpn.startLegacyVpnPrivileged(mProfile, KeyStore.getInstance(), egressProp);
            } catch (IllegalStateException e) {
                mAcceptedEgressIface = null;
                Slog.e(TAG, "Failed to start VPN", e);
                showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);
            }
        } else {
            Slog.e(TAG, "Invalid VPN profile; requires IP-based server and DNS");
            showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);
        }

    } else if (vpnInfo.isConnected() && vpnConfig != null) {
        final String iface = vpnConfig.interfaze;
        final List<LinkAddress> sourceAddrs = vpnConfig.addresses;

        if (TextUtils.equals(iface, mAcceptedIface)
              && sourceAddrs.equals(mAcceptedSourceAddr)) {
            return;
        }

        Slog.d(TAG, "VPN connected using iface=" + iface +
                ", sourceAddr=" + sourceAddrs.toString());
        EventLogTags.writeLockdownVpnConnected(egressType);
        showNotification(R.string.vpn_lockdown_connected, R.drawable.vpn_connected);

        final NetworkInfo clone = new NetworkInfo(egressInfo);
        augmentNetworkInfo(clone);
        mConnService.sendConnectedBroadcast(clone);
    }
}
 
Example #20
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public InterfaceConfiguration getInterfaceConfig(String iface) {
    mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

    final NativeDaemonEvent event;
    try {
        event = mConnector.execute("interface", "getcfg", iface);
    } catch (NativeDaemonConnectorException e) {
        throw e.rethrowAsParcelableException();
    }

    event.checkCode(InterfaceGetCfgResult);

    // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
    final StringTokenizer st = new StringTokenizer(event.getMessage());

    InterfaceConfiguration cfg;
    try {
        cfg = new InterfaceConfiguration();
        cfg.setHardwareAddress(st.nextToken(" "));
        InetAddress addr = null;
        int prefixLength = 0;
        try {
            addr = NetworkUtils.numericToInetAddress(st.nextToken());
        } catch (IllegalArgumentException iae) {
            Slog.e(TAG, "Failed to parse ipaddr", iae);
        }

        try {
            prefixLength = Integer.parseInt(st.nextToken());
        } catch (NumberFormatException nfe) {
            Slog.e(TAG, "Failed to parse prefixLength", nfe);
        }

        cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
        while (st.hasMoreTokens()) {
            cfg.setFlag(st.nextToken());
        }
    } catch (NoSuchElementException nsee) {
        throw new IllegalStateException("Invalid response from daemon: " + event);
    }
    return cfg;
}
 
Example #21
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Notify our observers of a deleted interface address.
 */
private void notifyAddressRemoved(String iface, LinkAddress address) {
    invokeForAllObservers(o -> o.addressRemoved(iface, address));
}
 
Example #22
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Notify our observers of a new or updated interface address.
 */
private void notifyAddressUpdated(String iface, LinkAddress address) {
    invokeForAllObservers(o -> o.addressUpdated(iface, address));
}
 
Example #23
Source File: ProxyStaticIpConfiguration.java    From astrobee_android with Apache License 2.0 4 votes vote down vote up
public void setIpAddress(final LinkAddress addr) throws IllegalAccessException {
    s_ipAddressFld.set(m_staticIpConfig, addr);
}