Search in sources :

Example 21 with NetworkState

use of android.net.NetworkState in project android_frameworks_base by DirtyUnicorns.

the class ConnectivityService method getActiveNetworkInfoForUid.

@Override
public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
    enforceConnectivityInternalPermission();
    final NetworkState state = getUnfilteredActiveNetworkState(uid);
    filterNetworkStateForUid(state, uid, ignoreBlocked);
    return state.networkInfo;
}
Also used : NetworkState(android.net.NetworkState)

Example 22 with NetworkState

use of android.net.NetworkState in project android_frameworks_base by DirtyUnicorns.

the class ConnectivityService method getActiveNetworkQuotaInfo.

@Override
public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
    enforceAccessPermission();
    final int uid = Binder.getCallingUid();
    final long token = Binder.clearCallingIdentity();
    try {
        final NetworkState state = getUnfilteredActiveNetworkState(uid);
        if (state.networkInfo != null) {
            try {
                return mPolicyManager.getNetworkQuotaInfo(state);
            } catch (RemoteException e) {
            }
        }
        return null;
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
Also used : NetworkState(android.net.NetworkState) RemoteException(android.os.RemoteException)

Example 23 with NetworkState

use of android.net.NetworkState in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsServiceTest method buildMobile4gState.

private static NetworkState buildMobile4gState(String iface) {
    final NetworkInfo info = new NetworkInfo(TYPE_WIMAX, 0, null, null);
    info.setDetailedState(DetailedState.CONNECTED, null, null);
    final LinkProperties prop = new LinkProperties();
    prop.setInterfaceName(iface);
    return new NetworkState(info, prop, null, null, null, null);
}
Also used : NetworkInfo(android.net.NetworkInfo) NetworkState(android.net.NetworkState) LinkProperties(android.net.LinkProperties)

Example 24 with NetworkState

use of android.net.NetworkState in project android_frameworks_base by DirtyUnicorns.

the class NetworkPolicyManagerService method updateNetworkRulesNL.

/**
     * Examine all connected {@link NetworkState}, looking for
     * {@link NetworkPolicy} that need to be enforced. When matches found, set
     * remaining quota based on usage cycle and historical stats.
     */
void updateNetworkRulesNL() {
    if (LOGV)
        Slog.v(TAG, "updateNetworkRulesNL()");
    final NetworkState[] states;
    try {
        states = mConnManager.getAllNetworkState();
    } catch (RemoteException e) {
        // ignored; service lives in system_server
        return;
    }
    // First, generate identities of all connected networks so we can
    // quickly compare them against all defined policies below.
    final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
    final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
    for (NetworkState state : states) {
        if (state.networkInfo != null && state.networkInfo.isConnected()) {
            final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
            final String baseIface = state.linkProperties.getInterfaceName();
            if (baseIface != null) {
                connIdents.add(Pair.create(baseIface, ident));
            }
            // Stacked interfaces are considered to have same identity as
            // their parent network.
            final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
            for (LinkProperties stackedLink : stackedLinks) {
                final String stackedIface = stackedLink.getInterfaceName();
                if (stackedIface != null) {
                    connIdents.add(Pair.create(stackedIface, ident));
                }
            }
        }
    }
    // Apply policies against all connected interfaces found above
    mNetworkRules.clear();
    final ArrayList<String> ifaceList = Lists.newArrayList();
    for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
        final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
        ifaceList.clear();
        for (int j = connIdents.size() - 1; j >= 0; j--) {
            final Pair<String, NetworkIdentity> ident = connIdents.get(j);
            if (policy.template.matches(ident.second)) {
                ifaceList.add(ident.first);
            }
        }
        if (ifaceList.size() > 0) {
            final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
            mNetworkRules.put(policy, ifaces);
        }
    }
    long lowestRule = Long.MAX_VALUE;
    final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
    // apply each policy that we found ifaces for; compute remaining data
    // based on current cycle and historical stats, and push to kernel.
    final long currentTime = currentTimeMillis();
    for (int i = mNetworkRules.size() - 1; i >= 0; i--) {
        final NetworkPolicy policy = mNetworkRules.keyAt(i);
        final String[] ifaces = mNetworkRules.valueAt(i);
        final long start;
        final long totalBytes;
        if (policy.hasCycle()) {
            start = computeLastCycleBoundary(currentTime, policy);
            totalBytes = getTotalBytes(policy.template, start, currentTime);
        } else {
            start = Long.MAX_VALUE;
            totalBytes = 0;
        }
        if (LOGD) {
            Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
        }
        final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
        final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
        if (hasLimit || policy.metered) {
            final long quotaBytes;
            if (!hasLimit) {
                // metered network, but no policy limit; we still need to
                // restrict apps, so push really high quota.
                quotaBytes = Long.MAX_VALUE;
            } else if (policy.lastLimitSnooze >= start) {
                // snoozing past quota, but we still need to restrict apps,
                // so push really high quota.
                quotaBytes = Long.MAX_VALUE;
            } else {
                // remaining "quota" bytes are based on total usage in
                // current cycle. kernel doesn't like 0-byte rules, so we
                // set 1-byte quota and disable the radio later.
                quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
            }
            if (ifaces.length > 1) {
                // TODO: switch to shared quota once NMS supports
                Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
            }
            for (String iface : ifaces) {
                // long quotaBytes split up into two ints to fit in message
                mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
                newMeteredIfaces.add(iface);
            }
        }
        // keep track of lowest warning or limit of active policies
        if (hasWarning && policy.warningBytes < lowestRule) {
            lowestRule = policy.warningBytes;
        }
        if (hasLimit && policy.limitBytes < lowestRule) {
            lowestRule = policy.limitBytes;
        }
    }
    for (int i = connIfaces.size() - 1; i >= 0; i--) {
        String iface = connIfaces.valueAt(i);
        // long quotaBytes split up into two ints to fit in message
        mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface).sendToTarget();
        newMeteredIfaces.add(iface);
    }
    mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
    // remove quota on any trailing interfaces
    for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
        final String iface = mMeteredIfaces.valueAt(i);
        if (!newMeteredIfaces.contains(iface)) {
            mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
        }
    }
    mMeteredIfaces = newMeteredIfaces;
    final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
    mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
}
Also used : ArraySet(android.util.ArraySet) NetworkIdentity(android.net.NetworkIdentity) NetworkPolicy(android.net.NetworkPolicy) ArrayList(java.util.ArrayList) NetworkPolicyManager.uidRulesToString(android.net.NetworkPolicyManager.uidRulesToString) LinkProperties(android.net.LinkProperties) NetworkState(android.net.NetworkState) RemoteException(android.os.RemoteException) Pair(android.util.Pair)

Example 25 with NetworkState

use of android.net.NetworkState in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsService method updateIfacesLocked.

/**
     * Inspect all current {@link NetworkState} to derive mapping from {@code
     * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
     * are active on a single {@code iface}, they are combined under a single
     * {@link NetworkIdentitySet}.
     */
private void updateIfacesLocked() {
    if (!mSystemReady)
        return;
    if (LOGV)
        Slog.v(TAG, "updateIfacesLocked()");
    // take one last stats snapshot before updating iface mapping. this
    // isn't perfect, since the kernel may already be counting traffic from
    // the updated network.
    // poll, but only persist network stats to keep codepath fast. UID stats
    // will be persisted during next alarm poll event.
    performPollLocked(FLAG_PERSIST_NETWORK);
    final NetworkState[] states;
    final LinkProperties activeLink;
    try {
        states = mConnManager.getAllNetworkState();
        activeLink = mConnManager.getActiveLinkProperties();
    } catch (RemoteException e) {
        // ignored; service lives in system_server
        return;
    }
    mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
    // Rebuild active interfaces based on connected networks
    mActiveIfaces.clear();
    mActiveUidIfaces.clear();
    final ArraySet<String> mobileIfaces = new ArraySet<>();
    for (NetworkState state : states) {
        if (state.networkInfo.isConnected()) {
            final boolean isMobile = isNetworkTypeMobile(state.networkInfo.getType());
            final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
            // Traffic occurring on the base interface is always counted for
            // both total usage and UID details.
            final String baseIface = state.linkProperties.getInterfaceName();
            if (baseIface != null) {
                findOrCreateNetworkIdentitySet(mActiveIfaces, baseIface).add(ident);
                findOrCreateNetworkIdentitySet(mActiveUidIfaces, baseIface).add(ident);
                // per carrier's policy, modem will report 0 usage for VT calls.
                if (state.networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.getMetered()) {
                    // Copy the identify from IMS one but mark it as metered.
                    NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(), ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(), ident.getRoaming(), true);
                    findOrCreateNetworkIdentitySet(mActiveIfaces, VT_INTERFACE).add(vtIdent);
                    findOrCreateNetworkIdentitySet(mActiveUidIfaces, VT_INTERFACE).add(vtIdent);
                }
                if (isMobile) {
                    mobileIfaces.add(baseIface);
                }
            }
            // Traffic occurring on stacked interfaces is usually clatd,
            // which is already accounted against its final egress interface
            // by the kernel. Thus, we only need to collect stacked
            // interface stats at the UID level.
            final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
            for (LinkProperties stackedLink : stackedLinks) {
                final String stackedIface = stackedLink.getInterfaceName();
                if (stackedIface != null) {
                    findOrCreateNetworkIdentitySet(mActiveUidIfaces, stackedIface).add(ident);
                    if (isMobile) {
                        mobileIfaces.add(stackedIface);
                    }
                }
            }
        }
    }
    mMobileIfaces = mobileIfaces.toArray(new String[mobileIfaces.size()]);
}
Also used : ArraySet(android.util.ArraySet) NetworkIdentity(android.net.NetworkIdentity) NetworkState(android.net.NetworkState) RemoteException(android.os.RemoteException) LinkProperties(android.net.LinkProperties)

Aggregations

NetworkState (android.net.NetworkState)101 LinkProperties (android.net.LinkProperties)36 NetworkInfo (android.net.NetworkInfo)26 NetworkPolicy (android.net.NetworkPolicy)21 RemoteException (android.os.RemoteException)18 NetworkStats (android.net.NetworkStats)15 NetworkAgentInfo (com.android.server.connectivity.NetworkAgentInfo)15 NetworkIdentity (android.net.NetworkIdentity)11 Intent (android.content.Intent)10 ArraySet (android.util.ArraySet)10 Suppress (android.test.suitebuilder.annotation.Suppress)9 NetworkCapabilities (android.net.NetworkCapabilities)8 Network (android.net.Network)5 NetworkPolicyManager.uidRulesToString (android.net.NetworkPolicyManager.uidRulesToString)5 Pair (android.util.Pair)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)3 Matchers.anyString (org.mockito.Matchers.anyString)2 NetworkStateTracker (android.net.NetworkStateTracker)1 HashMap (java.util.HashMap)1