Search in sources :

Example 66 with NetworkIdentity

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

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)

Example 67 with NetworkIdentity

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

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() && (state.networkCapabilities == null || !state.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || state.networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET))) {
            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 68 with NetworkIdentity

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

the class NetworkPolicyManagerService method isNetworkMetered.

@Override
public boolean isNetworkMetered(NetworkState state) {
    if (state.networkInfo == null) {
        return false;
    }
    final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
    final NetworkPolicy policy;
    synchronized (mNetworkPoliciesSecondLock) {
        policy = findPolicyForNetworkNL(ident);
    }
    if (policy != null) {
        return policy.metered;
    } else {
        final int type = state.networkInfo.getType();
        if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
            return true;
        }
        return false;
    }
}
Also used : NetworkIdentity(android.net.NetworkIdentity) NetworkPolicy(android.net.NetworkPolicy)

Example 69 with NetworkIdentity

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

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)

Example 70 with NetworkIdentity

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

the class NetworkStatsObserversTest method testUpdateStats_initialSample_doesNotNotify.

public void testUpdateStats_initialSample_doesNotNotify() throws Exception {
    DataUsageRequest inputRequest = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, sTemplateImsi1, THRESHOLD_BYTES);
    DataUsageRequest request = mStatsObservers.register(inputRequest, mMessenger, mockBinder, Process.SYSTEM_UID, NetworkStatsAccess.Level.DEVICE);
    assertTrue(request.requestId > 0);
    assertTrue(Objects.equals(sTemplateImsi1, request.template));
    assertEquals(THRESHOLD_BYTES, request.thresholdInBytes);
    NetworkIdentitySet identSet = new NetworkIdentitySet();
    identSet.add(new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, IMSI_1, null, /* networkId */
    false, /* roaming */
    true));
    mActiveIfaces.put(TEST_IFACE, identSet);
    // Baseline
    NetworkStats xtSnapshot = new NetworkStats(TEST_START, 1).addIfaceValues(TEST_IFACE, BASE_BYTES, 8L, BASE_BYTES, 16L);
    NetworkStats uidSnapshot = null;
    mStatsObservers.updateStats(xtSnapshot, uidSnapshot, mActiveIfaces, mActiveUidIfaces, VPN_INFO, TEST_START);
    waitForObserverToIdle();
    assertTrue(mCv.block(WAIT_TIMEOUT));
    assertEquals(INVALID_TYPE, mHandler.mLastMessageType);
}
Also used : DataUsageRequest(android.net.DataUsageRequest) NetworkIdentity(android.net.NetworkIdentity) NetworkStats(android.net.NetworkStats)

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