Search in sources :

Example 81 with NetworkTemplate

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

the class NetworkPolicyManagerService method writePolicyAL.

void writePolicyAL() {
    if (LOGV)
        Slog.v(TAG, "writePolicyAL()");
    FileOutputStream fos = null;
    try {
        fos = mPolicyFile.startWrite();
        XmlSerializer out = new FastXmlSerializer();
        out.setOutput(fos, StandardCharsets.UTF_8.name());
        out.startDocument(null, true);
        out.startTag(null, TAG_POLICY_LIST);
        writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
        writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
        // write all known network policies
        for (int i = 0; i < mNetworkPolicy.size(); i++) {
            final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
            final NetworkTemplate template = policy.template;
            if (!template.isPersistable())
                continue;
            out.startTag(null, TAG_NETWORK_POLICY);
            writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
            final String subscriberId = template.getSubscriberId();
            if (subscriberId != null) {
                out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
            }
            final String networkId = template.getNetworkId();
            if (networkId != null) {
                out.attribute(null, ATTR_NETWORK_ID, networkId);
            }
            writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
            out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
            writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
            writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
            writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
            writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
            writeBooleanAttribute(out, ATTR_METERED, policy.metered);
            writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
            out.endTag(null, TAG_NETWORK_POLICY);
        }
        // write all known uid policies
        for (int i = 0; i < mUidPolicy.size(); i++) {
            final int uid = mUidPolicy.keyAt(i);
            final int policy = mUidPolicy.valueAt(i);
            // skip writing empty policies
            if (policy == POLICY_NONE)
                continue;
            out.startTag(null, TAG_UID_POLICY);
            writeIntAttribute(out, ATTR_UID, uid);
            writeIntAttribute(out, ATTR_POLICY, policy);
            out.endTag(null, TAG_UID_POLICY);
        }
        out.endTag(null, TAG_POLICY_LIST);
        // write all whitelists
        out.startTag(null, TAG_WHITELIST);
        // restrict background whitelist
        int size = mRestrictBackgroundWhitelistUids.size();
        for (int i = 0; i < size; i++) {
            final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
            out.startTag(null, TAG_RESTRICT_BACKGROUND);
            writeIntAttribute(out, ATTR_UID, uid);
            out.endTag(null, TAG_RESTRICT_BACKGROUND);
        }
        // revoked restrict background whitelist
        size = mRestrictBackgroundWhitelistRevokedUids.size();
        for (int i = 0; i < size; i++) {
            final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
            out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
            writeIntAttribute(out, ATTR_UID, uid);
            out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
        }
        out.endTag(null, TAG_WHITELIST);
        out.endDocument();
        mPolicyFile.finishWrite(fos);
    } catch (IOException e) {
        if (fos != null) {
            mPolicyFile.failWrite(fos);
        }
    }
}
Also used : FastXmlSerializer(com.android.internal.util.FastXmlSerializer) NetworkTemplate(android.net.NetworkTemplate) NetworkPolicy(android.net.NetworkPolicy) FileOutputStream(java.io.FileOutputStream) NetworkPolicyManager.uidRulesToString(android.net.NetworkPolicyManager.uidRulesToString) IOException(java.io.IOException) XmlSerializer(org.xmlpull.v1.XmlSerializer) FastXmlSerializer(com.android.internal.util.FastXmlSerializer)

Example 82 with NetworkTemplate

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

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 83 with NetworkTemplate

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

the class NetworkPolicyManagerService method factoryReset.

@Override
public void factoryReset(String subscriber) {
    mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
    if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
        return;
    }
    // Turn mobile data limit off
    NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
    NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
    for (NetworkPolicy policy : policies) {
        if (policy.template.equals(template)) {
            policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
            policy.inferred = false;
            policy.clearSnooze();
        }
    }
    setNetworkPolicies(policies);
    // Turn restrict background data off
    setRestrictBackground(false);
    if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
        // Remove app's "restrict background data" flag
        for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
            setUidPolicy(uid, POLICY_NONE);
        }
    }
}
Also used : NetworkTemplate(android.net.NetworkTemplate) NetworkPolicy(android.net.NetworkPolicy)

Example 84 with NetworkTemplate

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

the class NetworkStatsManager method registerUsageCallback.

/**
     * Registers to receive notifications about data usage on specified networks.
     *
     * <p>The callbacks will continue to be called as long as the process is live or
     * {@link #unregisterUsageCallback} is called.
     *
     * @param networkType Type of network to monitor. Either
                  {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
     * @param subscriberId If applicable, the subscriber id of the network interface.
     * @param thresholdBytes Threshold in bytes to be notified on.
     * @param callback The {@link UsageCallback} that the system will call when data usage
     *            has exceeded the specified threshold.
     * @param handler to dispatch callback events through, otherwise if {@code null} it uses
     *            the calling thread.
     */
public void registerUsageCallback(int networkType, String subscriberId, long thresholdBytes, UsageCallback callback, @Nullable Handler handler) {
    checkNotNull(callback, "UsageCallback cannot be null");
    final Looper looper;
    if (handler == null) {
        looper = Looper.myLooper();
    } else {
        looper = handler.getLooper();
    }
    if (DBG) {
        Log.d(TAG, "registerUsageCallback called with: {" + " networkType=" + networkType + " subscriberId=" + subscriberId + " thresholdBytes=" + thresholdBytes + " }");
    }
    NetworkTemplate template = createTemplate(networkType, subscriberId);
    DataUsageRequest request = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, template, thresholdBytes);
    try {
        CallbackHandler callbackHandler = new CallbackHandler(looper, networkType, subscriberId, callback);
        callback.request = mService.registerUsageCallback(mContext.getOpPackageName(), request, new Messenger(callbackHandler), new Binder());
        if (DBG)
            Log.d(TAG, "registerUsageCallback returned " + callback.request);
        if (callback.request == null) {
            Log.e(TAG, "Request from callback is null; should not happen");
        }
    } catch (RemoteException e) {
        if (DBG)
            Log.d(TAG, "Remote exception when registering callback");
        throw e.rethrowFromSystemServer();
    }
}
Also used : Looper(android.os.Looper) DataUsageRequest(android.net.DataUsageRequest) Binder(android.os.Binder) NetworkTemplate(android.net.NetworkTemplate) Messenger(android.os.Messenger) RemoteException(android.os.RemoteException)

Example 85 with NetworkTemplate

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

the class NetworkStatsManager method queryDetailsForUidTag.

/**
     * Query network usage statistics details for a given uid and tag. Only usable for uids
     * belonging to calling user. Result is aggregated over state but not aggregated over time.
     * This means buckets' start and end timestamps are going to be between 'startTime' and
     * 'endTime' parameters. State is going to be {@link NetworkStats.Bucket#STATE_ALL}, uid the
     * same as the 'uid' parameter and tag the same as 'tag' parameter.
     * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
     * interpolate across partial buckets. Since bucket length is in the order of hours, this
     * method cannot be used to measure data usage on a fine grained time scale.
     *
     * @param networkType As defined in {@link ConnectivityManager}, e.g.
     *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
     *            etc.
     * @param subscriberId If applicable, the subscriber id of the network interface.
     * @param startTime Start of period. Defined in terms of "Unix time", see
     *            {@link java.lang.System#currentTimeMillis}.
     * @param endTime End of period. Defined in terms of "Unix time", see
     *            {@link java.lang.System#currentTimeMillis}.
     * @param uid UID of app
     * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for no tags.
     * @return Statistics object or null if an error happened during statistics collection.
     * @throws SecurityException if permissions are insufficient to read network statistics.
     */
public NetworkStats queryDetailsForUidTag(int networkType, String subscriberId, long startTime, long endTime, int uid, int tag) throws SecurityException {
    NetworkTemplate template;
    template = createTemplate(networkType, subscriberId);
    NetworkStats result;
    try {
        result = new NetworkStats(mContext, template, startTime, endTime);
        result.startHistoryEnumeration(uid, tag);
    } catch (RemoteException e) {
        Log.e(TAG, "Error while querying stats for uid=" + uid + " tag=" + tag, e);
        return null;
    }
    return result;
}
Also used : NetworkTemplate(android.net.NetworkTemplate) RemoteException(android.os.RemoteException)

Aggregations

NetworkTemplate (android.net.NetworkTemplate)111 NetworkPolicy (android.net.NetworkPolicy)33 RemoteException (android.os.RemoteException)21 NetworkPolicyManager.uidRulesToString (android.net.NetworkPolicyManager.uidRulesToString)15 NetworkStats (android.net.NetworkStats)12 IOException (java.io.IOException)12 AlertDialog (android.app.AlertDialog)6 Dialog (android.app.Dialog)6 DialogInterface (android.content.DialogInterface)6 NetworkIdentity (android.net.NetworkIdentity)6 Time (android.text.format.Time)6 NtpTrustedTime (android.util.NtpTrustedTime)6 TrustedTime (android.util.TrustedTime)6 FastXmlSerializer (com.android.internal.util.FastXmlSerializer)6 AppItem (com.android.settingslib.AppItem)6 FileInputStream (java.io.FileInputStream)6 FileNotFoundException (java.io.FileNotFoundException)6 FileOutputStream (java.io.FileOutputStream)6 XmlSerializer (org.xmlpull.v1.XmlSerializer)6 Bucket (android.app.usage.NetworkStats.Bucket)5