Search in sources :

Example 66 with ArraySet

use of android.util.ArraySet in project android_frameworks_base by DirtyUnicorns.

the class ManagedServices method rebindServices.

/**
     * Called whenever packages change, the user switches, or the secure setting
     * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
     */
private void rebindServices(boolean forceRebind) {
    if (DEBUG)
        Slog.d(TAG, "rebindServices");
    final int[] userIds = mUserProfiles.getCurrentProfileIds();
    final int nUserIds = userIds.length;
    final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
    for (int i = 0; i < nUserIds; ++i) {
        componentsByUser.put(userIds[i], loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
        if (mConfig.secondarySettingName != null) {
            componentsByUser.get(userIds[i]).addAll(loadComponentNamesFromSetting(mConfig.secondarySettingName, userIds[i]));
        }
    }
    final ArrayList<ManagedServiceInfo> removableBoundServices = new ArrayList<>();
    final SparseArray<Set<ComponentName>> toAdd = new SparseArray<>();
    synchronized (mMutex) {
        // Rebind to non-system services if user switched
        for (ManagedServiceInfo service : mServices) {
            if (!service.isSystem && !service.isGuest(this)) {
                removableBoundServices.add(service);
            }
        }
        mEnabledServicesForCurrentProfiles.clear();
        mEnabledServicesPackageNames.clear();
        for (int i = 0; i < nUserIds; ++i) {
            // decode the list of components
            final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
            if (null == userComponents) {
                toAdd.put(userIds[i], new ArraySet<ComponentName>());
                continue;
            }
            final Set<ComponentName> add = new HashSet<>(userComponents);
            add.removeAll(mSnoozingForCurrentProfiles);
            toAdd.put(userIds[i], add);
            mEnabledServicesForCurrentProfiles.addAll(userComponents);
            for (int j = 0; j < userComponents.size(); j++) {
                final ComponentName component = userComponents.valueAt(j);
                mEnabledServicesPackageNames.add(component.getPackageName());
            }
        }
    }
    for (ManagedServiceInfo info : removableBoundServices) {
        final ComponentName component = info.component;
        final int oldUser = info.userid;
        final Set<ComponentName> allowedComponents = toAdd.get(info.userid);
        if (allowedComponents != null) {
            if (allowedComponents.contains(component) && !forceRebind) {
                // Already bound, don't need to bind again.
                allowedComponents.remove(component);
            } else {
                // No longer allowed to be bound, or must rebind.
                Slog.v(TAG, "disabling " + getCaption() + " for user " + oldUser + ": " + component);
                unregisterService(component, oldUser);
            }
        }
    }
    for (int i = 0; i < nUserIds; ++i) {
        final Set<ComponentName> add = toAdd.get(userIds[i]);
        for (ComponentName component : add) {
            Slog.v(TAG, "enabling " + getCaption() + " for " + userIds[i] + ": " + component);
            registerService(component, userIds[i]);
        }
    }
    mLastSeenProfileIds = userIds;
}
Also used : ArraySet(android.util.ArraySet) HashSet(java.util.HashSet) ArraySet(android.util.ArraySet) Set(java.util.Set) ArrayList(java.util.ArrayList) SparseArray(android.util.SparseArray) ComponentName(android.content.ComponentName) HashSet(java.util.HashSet)

Example 67 with ArraySet

use of android.util.ArraySet 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 68 with ArraySet

use of android.util.ArraySet 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 69 with ArraySet

use of android.util.ArraySet in project android_frameworks_base by DirtyUnicorns.

the class CalendarTracker method getPrimaryCalendars.

private ArraySet<Long> getPrimaryCalendars() {
    final long start = System.currentTimeMillis();
    final ArraySet<Long> rt = new ArraySet<>();
    final String primary = "\"primary\"";
    final String[] projection = { Calendars._ID, "(" + Calendars.ACCOUNT_NAME + "=" + Calendars.OWNER_ACCOUNT + ") AS " + primary };
    final String selection = primary + " = 1";
    Cursor cursor = null;
    try {
        cursor = mUserContext.getContentResolver().query(Calendars.CONTENT_URI, projection, selection, null, null);
        while (cursor != null && cursor.moveToNext()) {
            rt.add(cursor.getLong(0));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    if (DEBUG)
        Log.d(TAG, "getPrimaryCalendars took " + (System.currentTimeMillis() - start));
    return rt;
}
Also used : ArraySet(android.util.ArraySet) Cursor(android.database.Cursor)

Example 70 with ArraySet

use of android.util.ArraySet in project android_frameworks_base by DirtyUnicorns.

the class BackupAgent method onFullBackup.

/**
     * The application is having its entire file system contents backed up.  {@code data}
     * points to the backup destination, and the app has the opportunity to choose which
     * files are to be stored.  To commit a file as part of the backup, call the
     * {@link #fullBackupFile(File, FullBackupDataOutput)} helper method.  After all file
     * data is written to the output, the agent returns from this method and the backup
     * operation concludes.
     *
     * <p>Certain parts of the app's data are never backed up even if the app explicitly
     * sends them to the output:
     *
     * <ul>
     * <li>The contents of the {@link #getCacheDir()} directory</li>
     * <li>The contents of the {@link #getCodeCacheDir()} directory</li>
     * <li>The contents of the {@link #getNoBackupFilesDir()} directory</li>
     * <li>The contents of the app's shared library directory</li>
     * </ul>
     *
     * <p>The default implementation of this method backs up the entirety of the
     * application's "owned" file system trees to the output other than the few exceptions
     * listed above.  Apps only need to override this method if they need to impose special
     * limitations on which files are being stored beyond the control that
     * {@link #getNoBackupFilesDir()} offers.
     * Alternatively they can provide an xml resource to specify what data to include or exclude.
     *
     *
     * @param data A structured wrapper pointing to the backup destination.
     * @throws IOException
     *
     * @see Context#getNoBackupFilesDir()
     * @see ApplicationInfo#fullBackupContent
     * @see #fullBackupFile(File, FullBackupDataOutput)
     * @see #onRestoreFile(ParcelFileDescriptor, long, File, int, long, long)
     */
public void onFullBackup(FullBackupDataOutput data) throws IOException {
    FullBackup.BackupScheme backupScheme = FullBackup.getBackupScheme(this);
    if (!backupScheme.isFullBackupContentEnabled()) {
        return;
    }
    Map<String, Set<String>> manifestIncludeMap;
    ArraySet<String> manifestExcludeSet;
    try {
        manifestIncludeMap = backupScheme.maybeParseAndGetCanonicalIncludePaths();
        manifestExcludeSet = backupScheme.maybeParseAndGetCanonicalExcludePaths();
    } catch (IOException | XmlPullParserException e) {
        if (Log.isLoggable(FullBackup.TAG_XML_PARSER, Log.VERBOSE)) {
            Log.v(FullBackup.TAG_XML_PARSER, "Exception trying to parse fullBackupContent xml file!" + " Aborting full backup.", e);
        }
        return;
    }
    final String packageName = getPackageName();
    final ApplicationInfo appInfo = getApplicationInfo();
    // System apps have control over where their default storage context
    // is pointed, so we're always explicit when building paths.
    final Context ceContext = createCredentialProtectedStorageContext();
    final String rootDir = ceContext.getDataDir().getCanonicalPath();
    final String filesDir = ceContext.getFilesDir().getCanonicalPath();
    final String noBackupDir = ceContext.getNoBackupFilesDir().getCanonicalPath();
    final String databaseDir = ceContext.getDatabasePath("foo").getParentFile().getCanonicalPath();
    final String sharedPrefsDir = ceContext.getSharedPreferencesPath("foo").getParentFile().getCanonicalPath();
    final String cacheDir = ceContext.getCacheDir().getCanonicalPath();
    final String codeCacheDir = ceContext.getCodeCacheDir().getCanonicalPath();
    final Context deContext = createDeviceProtectedStorageContext();
    final String deviceRootDir = deContext.getDataDir().getCanonicalPath();
    final String deviceFilesDir = deContext.getFilesDir().getCanonicalPath();
    final String deviceNoBackupDir = deContext.getNoBackupFilesDir().getCanonicalPath();
    final String deviceDatabaseDir = deContext.getDatabasePath("foo").getParentFile().getCanonicalPath();
    final String deviceSharedPrefsDir = deContext.getSharedPreferencesPath("foo").getParentFile().getCanonicalPath();
    final String deviceCacheDir = deContext.getCacheDir().getCanonicalPath();
    final String deviceCodeCacheDir = deContext.getCodeCacheDir().getCanonicalPath();
    final String libDir = (appInfo.nativeLibraryDir != null) ? new File(appInfo.nativeLibraryDir).getCanonicalPath() : null;
    // Maintain a set of excluded directories so that as we traverse the tree we know we're not
    // going places we don't expect, and so the manifest includes can't take precedence over
    // what the framework decides is not to be included.
    final ArraySet<String> traversalExcludeSet = new ArraySet<String>();
    // Add the directories we always exclude.
    traversalExcludeSet.add(filesDir);
    traversalExcludeSet.add(noBackupDir);
    traversalExcludeSet.add(databaseDir);
    traversalExcludeSet.add(sharedPrefsDir);
    traversalExcludeSet.add(cacheDir);
    traversalExcludeSet.add(codeCacheDir);
    traversalExcludeSet.add(deviceFilesDir);
    traversalExcludeSet.add(deviceNoBackupDir);
    traversalExcludeSet.add(deviceDatabaseDir);
    traversalExcludeSet.add(deviceSharedPrefsDir);
    traversalExcludeSet.add(deviceCacheDir);
    traversalExcludeSet.add(deviceCodeCacheDir);
    if (libDir != null) {
        traversalExcludeSet.add(libDir);
    }
    // Root dir first.
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.ROOT_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(rootDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.DEVICE_ROOT_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(deviceRootDir);
    // Data dir next.
    traversalExcludeSet.remove(filesDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.FILES_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(filesDir);
    traversalExcludeSet.remove(deviceFilesDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.DEVICE_FILES_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(deviceFilesDir);
    // Database directory.
    traversalExcludeSet.remove(databaseDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.DATABASE_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(databaseDir);
    traversalExcludeSet.remove(deviceDatabaseDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.DEVICE_DATABASE_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(deviceDatabaseDir);
    // SharedPrefs.
    traversalExcludeSet.remove(sharedPrefsDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.SHAREDPREFS_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(sharedPrefsDir);
    traversalExcludeSet.remove(deviceSharedPrefsDir);
    applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.DEVICE_SHAREDPREFS_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
    traversalExcludeSet.add(deviceSharedPrefsDir);
    // the log.
    if (Process.myUid() != Process.SYSTEM_UID) {
        File efLocation = getExternalFilesDir(null);
        if (efLocation != null) {
            applyXmlFiltersAndDoFullBackupForDomain(packageName, FullBackup.MANAGED_EXTERNAL_TREE_TOKEN, manifestIncludeMap, manifestExcludeSet, traversalExcludeSet, data);
        }
    }
}
Also used : Context(android.content.Context) ArraySet(android.util.ArraySet) Set(java.util.Set) ArraySet(android.util.ArraySet) ApplicationInfo(android.content.pm.ApplicationInfo) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) File(java.io.File)

Aggregations

ArraySet (android.util.ArraySet)521 PublicKey (java.security.PublicKey)94 ArrayList (java.util.ArrayList)87 ComponentName (android.content.ComponentName)82 ArrayMap (android.util.ArrayMap)73 Pair (android.util.Pair)47 RemoteException (android.os.RemoteException)43 ResolveInfo (android.content.pm.ResolveInfo)39 Intent (android.content.Intent)38 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)35 File (java.io.File)33 SSLContext (javax.net.ssl.SSLContext)32 IOException (java.io.IOException)31 PackageManager (android.content.pm.PackageManager)29 UserInfo (android.content.pm.UserInfo)28 ApplicationInfo (android.content.pm.ApplicationInfo)24 Point (android.graphics.Point)24 X509Certificate (java.security.cert.X509Certificate)20 PackageInfo (android.content.pm.PackageInfo)19 Test (org.junit.Test)19