Search in sources :

Example 36 with UserHandle

use of android.os.UserHandle in project platform_frameworks_base by android.

the class Vpn method updateAlwaysOnNotificationInternal.

@VisibleForTesting
protected void updateAlwaysOnNotificationInternal(boolean visible) {
    final UserHandle user = UserHandle.of(mUserHandle);
    final long token = Binder.clearCallingIdentity();
    try {
        final NotificationManager notificationManager = NotificationManager.from(mContext);
        if (!visible) {
            notificationManager.cancelAsUser(TAG, 0, user);
            return;
        }
        final Intent intent = new Intent(Settings.ACTION_VPN_SETTINGS);
        final PendingIntent configIntent = PendingIntent.getActivityAsUser(mContext, /* request */
        0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, null, user);
        final Notification.Builder builder = new Notification.Builder(mContext).setDefaults(0).setSmallIcon(R.drawable.vpn_connected).setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected)).setContentText(mContext.getString(R.string.vpn_lockdown_config)).setContentIntent(configIntent).setCategory(Notification.CATEGORY_SYSTEM).setPriority(Notification.PRIORITY_LOW).setVisibility(Notification.VISIBILITY_PUBLIC).setOngoing(true).setColor(mContext.getColor(R.color.system_notification_accent_color));
        notificationManager.notifyAsUser(TAG, 0, builder.build(), user);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
Also used : NotificationManager(android.app.NotificationManager) UserHandle(android.os.UserHandle) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Notification(android.app.Notification) VisibleForTesting(com.android.internal.annotations.VisibleForTesting)

Example 37 with UserHandle

use of android.os.UserHandle in project platform_frameworks_base by android.

the class Vpn method establish.

/**
     * Establish a VPN network and return the file descriptor of the VPN
     * interface. This methods returns {@code null} if the application is
     * revoked or not prepared.
     *
     * @param config The parameters to configure the network.
     * @return The file descriptor of the VPN interface.
     */
public synchronized ParcelFileDescriptor establish(VpnConfig config) {
    // Check if the caller is already prepared.
    UserManager mgr = UserManager.get(mContext);
    if (Binder.getCallingUid() != mOwnerUID) {
        return null;
    }
    // Check to ensure consent hasn't been revoked since we were prepared.
    if (!isVpnUserPreConsented(mPackage)) {
        return null;
    }
    // Check if the service is properly declared.
    Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
    intent.setClassName(mPackage, config.user);
    long token = Binder.clearCallingIdentity();
    try {
        // Restricted users are not allowed to create VPNs, they are tied to Owner
        UserInfo user = mgr.getUserInfo(mUserHandle);
        if (user.isRestricted()) {
            throw new SecurityException("Restricted users cannot establish VPNs");
        }
        ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent, null, 0, mUserHandle);
        if (info == null) {
            throw new SecurityException("Cannot find " + config.user);
        }
        if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
            throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
        }
    } catch (RemoteException e) {
        throw new SecurityException("Cannot find " + config.user);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
    // Save the old config in case we need to go back.
    VpnConfig oldConfig = mConfig;
    String oldInterface = mInterface;
    Connection oldConnection = mConnection;
    NetworkAgent oldNetworkAgent = mNetworkAgent;
    mNetworkAgent = null;
    Set<UidRange> oldUsers = mVpnUsers;
    // Configure the interface. Abort if any of these steps fails.
    ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
    try {
        updateState(DetailedState.CONNECTING, "establish");
        String interfaze = jniGetName(tun.getFd());
        // TEMP use the old jni calls until there is support for netd address setting
        StringBuilder builder = new StringBuilder();
        for (LinkAddress address : config.addresses) {
            builder.append(" " + address);
        }
        if (jniSetAddresses(interfaze, builder.toString()) < 1) {
            throw new IllegalArgumentException("At least one address must be specified");
        }
        Connection connection = new Connection();
        if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE, new UserHandle(mUserHandle))) {
            throw new IllegalStateException("Cannot bind " + config.user);
        }
        mConnection = connection;
        mInterface = interfaze;
        // Fill more values.
        config.user = mPackage;
        config.interfaze = mInterface;
        config.startTime = SystemClock.elapsedRealtime();
        mConfig = config;
        // Set up forwarding and DNS rules.
        agentConnect();
        if (oldConnection != null) {
            mContext.unbindService(oldConnection);
        }
        // Remove the old tun's user forwarding rules
        // The new tun's user rules have already been added so they will take over
        // as rules are deleted. This prevents data leakage as the rules are moved over.
        agentDisconnect(oldNetworkAgent);
        if (oldInterface != null && !oldInterface.equals(interfaze)) {
            jniReset(oldInterface);
        }
        try {
            IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot set tunnel's fd as blocking=" + config.blocking, e);
        }
    } catch (RuntimeException e) {
        IoUtils.closeQuietly(tun);
        agentDisconnect();
        // restore old state
        mConfig = oldConfig;
        mConnection = oldConnection;
        mVpnUsers = oldUsers;
        mNetworkAgent = oldNetworkAgent;
        mInterface = oldInterface;
        throw e;
    }
    Log.i(TAG, "Established by " + config.user + " on " + mInterface);
    return tun;
}
Also used : LinkAddress(android.net.LinkAddress) NetworkAgent(android.net.NetworkAgent) VpnConfig(com.android.internal.net.VpnConfig) UidRange(android.net.UidRange) ServiceConnection(android.content.ServiceConnection) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) UserInfo(android.content.pm.UserInfo) IOException(java.io.IOException) ResolveInfo(android.content.pm.ResolveInfo) UserManager(android.os.UserManager) UserHandle(android.os.UserHandle) ParcelFileDescriptor(android.os.ParcelFileDescriptor) RemoteException(android.os.RemoteException)

Example 38 with UserHandle

use of android.os.UserHandle in project platform_frameworks_base by android.

the class NotificationManagerService method enqueueNotificationInternal.

void enqueueNotificationInternal(final String pkg, final String opPkg, final int callingUid, final int callingPid, final String tag, final int id, final Notification notification, int[] idOut, int incomingUserId) {
    if (DBG) {
        Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
    }
    checkCallerIsSystemOrSameApp(pkg);
    final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
    final boolean isNotificationFromListener = mListeners.isListenerPackage(pkg);
    final int userId = ActivityManager.handleIncomingUser(callingPid, callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
    final UserHandle user = new UserHandle(userId);
    // Fix the notification as best we can.
    try {
        final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfoAsUser(pkg, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
        Notification.addFieldsFromContext(ai, userId, notification);
    } catch (NameNotFoundException e) {
        Slog.e(TAG, "Cannot create a context for sending app", e);
        return;
    }
    mUsageStats.registerEnqueuedByApp(pkg);
    if (pkg == null || notification == null) {
        throw new IllegalArgumentException("null not allowed: pkg=" + pkg + " id=" + id + " notification=" + notification);
    }
    final StatusBarNotification n = new StatusBarNotification(pkg, opPkg, id, tag, callingUid, callingPid, 0, notification, user);
    // package or a registered listener can enqueue.  Prevents DOS attacks and deals with leaks.
    if (!isSystemNotification && !isNotificationFromListener) {
        synchronized (mNotificationList) {
            if (mNotificationsByKey.get(n.getKey()) != null) {
                // this is an update, rate limit updates only
                final float appEnqueueRate = mUsageStats.getAppEnqueueRate(pkg);
                if (appEnqueueRate > mMaxPackageEnqueueRate) {
                    mUsageStats.registerOverRateQuota(pkg);
                    final long now = SystemClock.elapsedRealtime();
                    if ((now - mLastOverRateLogTime) > MIN_PACKAGE_OVERRATE_LOG_INTERVAL) {
                        Slog.e(TAG, "Package enqueue rate is " + appEnqueueRate + ". Shedding events. package=" + pkg);
                        mLastOverRateLogTime = now;
                    }
                    return;
                }
            }
            int count = 0;
            final int N = mNotificationList.size();
            for (int i = 0; i < N; i++) {
                final NotificationRecord r = mNotificationList.get(i);
                if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
                    if (r.sbn.getId() == id && TextUtils.equals(r.sbn.getTag(), tag)) {
                        // Allow updating existing notification
                        break;
                    }
                    count++;
                    if (count >= MAX_PACKAGE_NOTIFICATIONS) {
                        mUsageStats.registerOverCountQuota(pkg);
                        Slog.e(TAG, "Package has already posted " + count + " notifications.  Not showing more.  package=" + pkg);
                        return;
                    }
                }
            }
        }
    }
    // Whitelist pending intents.
    if (notification.allPendingIntents != null) {
        final int intentCount = notification.allPendingIntents.size();
        if (intentCount > 0) {
            final ActivityManagerInternal am = LocalServices.getService(ActivityManagerInternal.class);
            final long duration = LocalServices.getService(DeviceIdleController.LocalService.class).getNotificationWhitelistDuration();
            for (int i = 0; i < intentCount; i++) {
                PendingIntent pendingIntent = notification.allPendingIntents.valueAt(i);
                if (pendingIntent != null) {
                    am.setPendingIntentWhitelistDuration(pendingIntent.getTarget(), duration);
                }
            }
        }
    }
    // Sanitize inputs
    notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
    // setup local book-keeping
    final NotificationRecord r = new NotificationRecord(getContext(), n);
    mHandler.post(new EnqueueNotificationRunnable(userId, r));
    idOut[0] = id;
}
Also used : NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ActivityManagerInternal(android.app.ActivityManagerInternal) ApplicationInfo(android.content.pm.ApplicationInfo) StatusBarNotification(android.service.notification.StatusBarNotification) UserHandle(android.os.UserHandle) PendingIntent(android.app.PendingIntent)

Example 39 with UserHandle

use of android.os.UserHandle in project platform_frameworks_base by android.

the class EventConditionProvider method reloadTrackers.

private void reloadTrackers() {
    if (DEBUG)
        Slog.d(TAG, "reloadTrackers");
    for (int i = 0; i < mTrackers.size(); i++) {
        mTrackers.valueAt(i).setCallback(null);
    }
    mTrackers.clear();
    for (UserHandle user : UserManager.get(mContext).getUserProfiles()) {
        final Context context = user.isSystem() ? mContext : getContextForUser(mContext, user);
        if (context == null) {
            Slog.w(TAG, "Unable to create context for user " + user.getIdentifier());
            continue;
        }
        mTrackers.put(user.getIdentifier(), new CalendarTracker(mContext, context));
    }
    evaluateSubscriptions();
}
Also used : Context(android.content.Context) UserHandle(android.os.UserHandle)

Example 40 with UserHandle

use of android.os.UserHandle in project platform_frameworks_base by android.

the class DevicePolicyManagerService method setApplicationRestrictions.

@Override
public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
    enforceCanManageApplicationRestrictions(who);
    final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
    final long id = mInjector.binderClearCallingIdentity();
    try {
        mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
    } finally {
        mInjector.binderRestoreCallingIdentity(id);
    }
}
Also used : UserHandle(android.os.UserHandle)

Aggregations

UserHandle (android.os.UserHandle)568 Intent (android.content.Intent)231 RemoteException (android.os.RemoteException)163 PendingIntent (android.app.PendingIntent)132 ComponentName (android.content.ComponentName)69 Context (android.content.Context)68 UserInfo (android.content.pm.UserInfo)66 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)62 Bundle (android.os.Bundle)50 IBinder (android.os.IBinder)49 UserManager (android.os.UserManager)44 PackageManager (android.content.pm.PackageManager)40 ApplicationInfo (android.content.pm.ApplicationInfo)30 IOException (java.io.IOException)30 ArrayList (java.util.ArrayList)30 ActivityNotFoundException (android.content.ActivityNotFoundException)28 Notification (android.app.Notification)27 ServiceConnection (android.content.ServiceConnection)27 IPackageManager (android.content.pm.IPackageManager)27 Pair (android.util.Pair)23