Search in sources :

Example 31 with NetworkIdentity

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

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 32 with NetworkIdentity

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

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 33 with NetworkIdentity

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

the class NetworkPolicyManagerService method ensureActiveMobilePolicyNL.

private void ensureActiveMobilePolicyNL(String subscriberId) {
    // Poke around to see if we already have a policy
    final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
    for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
        final NetworkTemplate template = mNetworkPolicy.keyAt(i);
        if (template.matches(probeIdent)) {
            if (LOGD) {
                Slog.d(TAG, "Found template " + template + " which matches subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId));
            }
            return;
        }
    }
    Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId) + "; generating default policy");
    // Build default mobile policy, and assume usage cycle starts today
    final int dataWarningConfig = mContext.getResources().getInteger(com.android.internal.R.integer.config_networkPolicyDefaultWarning);
    final long warningBytes;
    if (dataWarningConfig == WARNING_DISABLED) {
        warningBytes = WARNING_DISABLED;
    } else {
        warningBytes = dataWarningConfig * MB_IN_BYTES;
    }
    final Time time = new Time();
    time.setToNow();
    final int cycleDay = time.monthDay;
    final String cycleTimezone = time.timezone;
    final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
    final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone, warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
    addNetworkPolicyNL(policy);
}
Also used : NetworkTemplate(android.net.NetworkTemplate) NetworkIdentity(android.net.NetworkIdentity) NetworkPolicy(android.net.NetworkPolicy) Time(android.text.format.Time) TrustedTime(android.util.TrustedTime) NtpTrustedTime(android.util.NtpTrustedTime) NetworkPolicyManager.uidRulesToString(android.net.NetworkPolicyManager.uidRulesToString)

Example 34 with NetworkIdentity

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

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 35 with NetworkIdentity

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

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

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