Search in sources :

Example 21 with NetworkIdentity

use of android.net.NetworkIdentity in project android_frameworks_base by ResurrectionRemix.

the class NetworkPolicyManagerService method getNetworkQuotaInfoUnchecked.

private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
    final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
    final NetworkPolicy policy;
    synchronized (mNetworkPoliciesSecondLock) {
        policy = findPolicyForNetworkNL(ident);
    }
    if (policy == null || !policy.hasCycle()) {
        // missing policy means we can't derive useful quota info
        return null;
    }
    final long currentTime = currentTimeMillis();
    // find total bytes used under policy
    final long start = computeLastCycleBoundary(currentTime, policy);
    final long end = currentTime;
    final long totalBytes = getTotalBytes(policy.template, start, end);
    // report soft and hard limits under policy
    final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes : NetworkQuotaInfo.NO_LIMIT;
    final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes : NetworkQuotaInfo.NO_LIMIT;
    return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
}
Also used : NetworkQuotaInfo(android.net.NetworkQuotaInfo) NetworkIdentity(android.net.NetworkIdentity) NetworkPolicy(android.net.NetworkPolicy)

Example 22 with NetworkIdentity

use of android.net.NetworkIdentity in project android_frameworks_base by ResurrectionRemix.

the class NetworkStatsCollectionTest method testAccessLevels.

public void testAccessLevels() throws Exception {
    final NetworkStatsCollection collection = new NetworkStatsCollection(HOUR_IN_MILLIS);
    final NetworkStats.Entry entry = new NetworkStats.Entry();
    final NetworkIdentitySet identSet = new NetworkIdentitySet();
    identSet.add(new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, TEST_IMSI, null, false, true));
    int myUid = Process.myUid();
    int otherUidInSameUser = Process.myUid() + 1;
    int uidInDifferentUser = Process.myUid() + UserHandle.PER_USER_RANGE;
    // Record one entry for the current UID.
    entry.rxBytes = 32;
    collection.recordData(identSet, myUid, SET_DEFAULT, TAG_NONE, 0, 60 * MINUTE_IN_MILLIS, entry);
    // Record one entry for another UID in this user.
    entry.rxBytes = 64;
    collection.recordData(identSet, otherUidInSameUser, SET_DEFAULT, TAG_NONE, 0, 60 * MINUTE_IN_MILLIS, entry);
    // Record one entry for the system UID.
    entry.rxBytes = 128;
    collection.recordData(identSet, Process.SYSTEM_UID, SET_DEFAULT, TAG_NONE, 0, 60 * MINUTE_IN_MILLIS, entry);
    // Record one entry for a UID in a different user.
    entry.rxBytes = 256;
    collection.recordData(identSet, uidInDifferentUser, SET_DEFAULT, TAG_NONE, 0, 60 * MINUTE_IN_MILLIS, entry);
    // Verify the set of relevant UIDs for each access level.
    MoreAsserts.assertEquals(new int[] { myUid }, collection.getRelevantUids(NetworkStatsAccess.Level.DEFAULT));
    MoreAsserts.assertEquals(new int[] { Process.SYSTEM_UID, myUid, otherUidInSameUser }, collection.getRelevantUids(NetworkStatsAccess.Level.USER));
    MoreAsserts.assertEquals(new int[] { Process.SYSTEM_UID, myUid, otherUidInSameUser, uidInDifferentUser }, collection.getRelevantUids(NetworkStatsAccess.Level.DEVICE));
    // Verify security check in getHistory.
    assertNotNull(collection.getHistory(buildTemplateMobileAll(TEST_IMSI), myUid, SET_DEFAULT, TAG_NONE, 0, NetworkStatsAccess.Level.DEFAULT));
    try {
        collection.getHistory(buildTemplateMobileAll(TEST_IMSI), otherUidInSameUser, SET_DEFAULT, TAG_NONE, 0, NetworkStatsAccess.Level.DEFAULT);
        fail("Should have thrown SecurityException for accessing different UID");
    } catch (SecurityException e) {
    // expected
    }
    // Verify appropriate aggregation in getSummary.
    assertSummaryTotal(collection, buildTemplateMobileAll(TEST_IMSI), 32, 0, 0, 0, NetworkStatsAccess.Level.DEFAULT);
    assertSummaryTotal(collection, buildTemplateMobileAll(TEST_IMSI), 32 + 64 + 128, 0, 0, 0, NetworkStatsAccess.Level.USER);
    assertSummaryTotal(collection, buildTemplateMobileAll(TEST_IMSI), 32 + 64 + 128 + 256, 0, 0, 0, NetworkStatsAccess.Level.DEVICE);
}
Also used : NetworkIdentity(android.net.NetworkIdentity) NetworkStats(android.net.NetworkStats)

Example 23 with NetworkIdentity

use of android.net.NetworkIdentity 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 24 with NetworkIdentity

use of android.net.NetworkIdentity 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)

Example 25 with NetworkIdentity

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

the class NetworkPolicyManagerService method setNetworkTemplateEnabled.

/**
     * Proactively disable networks that match the given
     * {@link NetworkTemplate}.
     */
private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
    if (template.getMatchRule() == MATCH_MOBILE_ALL) {
        // If mobile data usage hits the limit or if the user resumes the data, we need to
        // notify telephony.
        final SubscriptionManager sm = SubscriptionManager.from(mContext);
        final TelephonyManager tm = TelephonyManager.from(mContext);
        final int[] subIds = sm.getActiveSubscriptionIdList();
        for (int subId : subIds) {
            final String subscriberId = tm.getSubscriberId(subId);
            final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
            // Template is matched when subscriber id matches.
            if (template.matches(probeIdent)) {
                tm.setPolicyDataEnabled(enabled, subId);
            }
        }
    }
}
Also used : NetworkIdentity(android.net.NetworkIdentity) TelephonyManager(android.telephony.TelephonyManager) SubscriptionManager(android.telephony.SubscriptionManager) NetworkPolicyManager.uidRulesToString(android.net.NetworkPolicyManager.uidRulesToString)

Aggregations

NetworkIdentity (android.net.NetworkIdentity)82 NetworkStats (android.net.NetworkStats)32 DataUsageRequest (android.net.DataUsageRequest)28 NetworkPolicy (android.net.NetworkPolicy)24 NetworkPolicyManager.uidRulesToString (android.net.NetworkPolicyManager.uidRulesToString)20 NetworkState (android.net.NetworkState)11 RemoteException (android.os.RemoteException)11 TelephonyManager (android.telephony.TelephonyManager)11 LinkProperties (android.net.LinkProperties)10 SubscriptionManager (android.telephony.SubscriptionManager)10 ArraySet (android.util.ArraySet)10 NetworkQuotaInfo (android.net.NetworkQuotaInfo)6 NetworkTemplate (android.net.NetworkTemplate)6 Time (android.text.format.Time)6 NtpTrustedTime (android.util.NtpTrustedTime)6 TrustedTime (android.util.TrustedTime)6 Pair (android.util.Pair)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)1 Map (java.util.Map)1