Java Code Examples for android.os.UserHandle#getCallingUserId()

The following examples show how to use android.os.UserHandle#getCallingUserId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContentService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void setIsSyncable(Account account, String providerName, int syncable) {
    if (TextUtils.isEmpty(providerName)) {
        throw new IllegalArgumentException("Authority must not be empty");
    }
    mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
            "no permission to write the sync settings");

    syncable = normalizeSyncable(syncable);
    final int callingUid = Binder.getCallingUid();

    int userId = UserHandle.getCallingUserId();
    long identityToken = clearCallingIdentity();
    try {
        SyncManager syncManager = getSyncManager();
        if (syncManager != null) {
            syncManager.getSyncStorageEngine().setIsSyncable(
                    account, userId, providerName, syncable, callingUid);
        }
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
 
Example 2
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public void removePeriodicSync(Account account, String authority, Bundle extras) {
    Bundle.setDefusable(extras, true);
    if (account == null) {
        throw new IllegalArgumentException("Account must not be null");
    }
    if (TextUtils.isEmpty(authority)) {
        throw new IllegalArgumentException("Authority must not be empty");
    }
    mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
            "no permission to write the sync settings");

    final int callingUid = Binder.getCallingUid();

    int userId = UserHandle.getCallingUserId();
    long identityToken = clearCallingIdentity();
    try {
        getSyncManager()
                .removePeriodicSync(
                        new SyncStorageEngine.EndPoint(account, authority, userId),
                        extras, "removePeriodicSync() by uid=" + callingUid);
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
 
Example 3
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
    boolean returnFullInfo = true;
    if (userId != UserHandle.getCallingUserId()) {
        checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
    } else {
        returnFullInfo = hasManageUsersPermission();
    }
    final long ident = Binder.clearCallingIdentity();
    try {
        synchronized (mUsersLock) {
            return getProfilesLU(userId, enabledOnly, returnFullInfo);
        }
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 4
Source File: ContentService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSyncActive(Account account, String authority, ComponentName cname) {
    mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
            "no permission to read the sync stats");
    int userId = UserHandle.getCallingUserId();
    long identityToken = clearCallingIdentity();
    try {
        SyncManager syncManager = getSyncManager();
        if (syncManager == null) {
            return false;
        }
        return syncManager.getSyncStorageEngine().isSyncActive(
                new SyncStorageEngine.EndPoint(account, authority, userId));
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
 
Example 5
Source File: BluetoothManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private boolean checkIfCallerIsForegroundUser() {
    int foregroundUser;
    int callingUser = UserHandle.getCallingUserId();
    int callingUid = Binder.getCallingUid();
    long callingIdentity = Binder.clearCallingIdentity();
    UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
    UserInfo ui = um.getProfileParent(callingUser);
    int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
    int callingAppId = UserHandle.getAppId(callingUid);
    boolean valid = false;
    try {
        foregroundUser = ActivityManager.getCurrentUser();
        valid = (callingUser == foregroundUser) || parentUser == foregroundUser
                || callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
        if (DBG && !valid) {
            Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
                    + callingUser + " parentUser=" + parentUser + " foregroundUser="
                    + foregroundUser);
        }
    } finally {
        Binder.restoreCallingIdentity(callingIdentity);
    }
    return valid;
}
 
Example 6
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor getUserIcon(int targetUserId) {
    String iconPath;
    synchronized (mPackagesLock) {
        UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
        if (targetUserInfo == null || targetUserInfo.partial) {
            Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
            return null;
        }

        final int callingUserId = UserHandle.getCallingUserId();
        final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
        final int targetGroupId = targetUserInfo.profileGroupId;
        final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
                && callingGroupId == targetGroupId);
        if ((callingUserId != targetUserId) && !sameGroup) {
            checkManageUsersPermission("get the icon of a user who is not related");
        }

        if (targetUserInfo.iconPath == null) {
            return null;
        }
        iconPath = targetUserInfo.iconPath;
    }

    try {
        return ParcelFileDescriptor.open(
                new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, "Couldn't find icon file", e);
    }
    return null;
}
 
Example 7
Source File: RecoverableKeyStoreManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a key named {@code alias} in caller's namespace.
 *
 * @return grant alias, which caller can use to access the key.
 */
public @Nullable String getKey(@NonNull String alias) throws RemoteException {
    checkRecoverKeyStorePermission();
    Preconditions.checkNotNull(alias, "alias is null");
    int uid = Binder.getCallingUid();
    int userId = UserHandle.getCallingUserId();
    return getAlias(userId, uid, alias);
}
 
Example 8
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS_FULL
 * permission, if the userHandle is not for the caller.
 *
 * @param userHandle the user handle of the user we want to act on behalf of.
 * @param message the message to log on security exception.
 */
private void enforceCrossUserPermission(int userHandle, String message) {
    final int callingUser = UserHandle.getCallingUserId();
    if (callingUser != userHandle) {
        mContext.enforceCallingOrSelfPermission(
                Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
    }
}
 
Example 9
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
        int userId) {
    if (userId == UserHandle.USER_CURRENT) {
        userId = ActivityManager.getCurrentUser();
    }

    if (userId == UserHandle.USER_ALL) {
        mContext.enforceCallingOrSelfPermission(
                Manifest.permission.INTERACT_ACROSS_USERS_FULL, "No access to " + uri);
    } else if (userId < 0) {
        throw new IllegalArgumentException("Invalid user: " + userId);
    } else if (userId != UserHandle.getCallingUserId()) {
        if (checkUriPermission(uri, pid, uid, modeFlags,
                userId) != PackageManager.PERMISSION_GRANTED) {
            boolean allow = false;
            if (mContext.checkCallingOrSelfPermission(
                    Manifest.permission.INTERACT_ACROSS_USERS_FULL)
                            == PackageManager.PERMISSION_GRANTED) {
                allow = true;
            } else if (allowNonFull && mContext.checkCallingOrSelfPermission(
                    Manifest.permission.INTERACT_ACROSS_USERS)
                            == PackageManager.PERMISSION_GRANTED) {
                allow = true;
            }
            if (!allow) {
                final String permissions = allowNonFull
                        ? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
                                Manifest.permission.INTERACT_ACROSS_USERS)
                        : Manifest.permission.INTERACT_ACROSS_USERS_FULL;
                throw new SecurityException("No access to " + uri + ": neither user " + uid
                        + " nor current process has " + permissions);
            }
        }
    }

    return userId;
}
 
Example 10
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isManagedProfile(int userId) {
    int callingUserId = UserHandle.getCallingUserId();
    if (callingUserId != userId && !hasManageUsersPermission()) {
        if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
            throw new SecurityException(
                    "You need MANAGE_USERS permission to: check if specified user a " +
                    "managed profile outside your profile group");
        }
    }
    synchronized (mUsersLock) {
        UserInfo userInfo = getUserInfoLU(userId);
        return userInfo != null && userInfo.isManagedProfile();
    }
}
 
Example 11
Source File: DreamManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override // Binder call
public ComponentName getDefaultDreamComponent() {
    checkPermission(android.Manifest.permission.READ_DREAM_STATE);

    final int userId = UserHandle.getCallingUserId();
    final long ident = Binder.clearCallingIdentity();
    try {
        return getDefaultDreamComponentForUser(userId);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 12
Source File: SettingsProvider.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
    if (requestingUserId == UserHandle.getCallingUserId()) {
        return requestingUserId;
    }
    return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
            Binder.getCallingUid(), requestingUserId, false, true,
            "get/set setting for user", null);
}
 
Example 13
Source File: ContentService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void cancelRequest(SyncRequest request) {
    SyncManager syncManager = getSyncManager();
    if (syncManager == null) return;
    int userId = UserHandle.getCallingUserId();
    final int callingUid = Binder.getCallingUid();

    if (request.isPeriodic()) {
        mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
                "no permission to write the sync settings");
    }

    Bundle extras = new Bundle(request.getBundle());
    validateExtras(callingUid, extras);

    long identityToken = clearCallingIdentity();
    try {
        SyncStorageEngine.EndPoint info;

        Account account = request.getAccount();
        String provider = request.getProvider();
        info = new SyncStorageEngine.EndPoint(account, provider, userId);
        if (request.isPeriodic()) {
            // Remove periodic sync.
            getSyncManager().removePeriodicSync(info, extras,
                    "cancelRequest() by uid=" + callingUid);
        }
        // Cancel active syncs and clear pending syncs from the queue.
        syncManager.cancelScheduledSyncOperation(info, extras);
        syncManager.cancelActiveSync(info, extras, "API");
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
 
Example 14
Source File: OemLockService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void enforceUserIsAdmin() {
    final int userId = UserHandle.getCallingUserId();
    final long token = Binder.clearCallingIdentity();
    try {
        if (!UserManager.get(mContext).isUserAdmin(userId)) {
            throw new SecurityException("Must be an admin user");
        }
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 15
Source File: ContentService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** Old API. Schedule periodic sync with default flexMillis time. */
@Override
public void addPeriodicSync(Account account, String authority, Bundle extras,
                            long pollFrequency) {
    Bundle.setDefusable(extras, true);
    if (account == null) {
        throw new IllegalArgumentException("Account must not be null");
    }
    if (TextUtils.isEmpty(authority)) {
        throw new IllegalArgumentException("Authority must not be empty.");
    }
    mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
            "no permission to write the sync settings");

    validateExtras(Binder.getCallingUid(), extras);

    int userId = UserHandle.getCallingUserId();

    pollFrequency = clampPeriod(pollFrequency);
    long defaultFlex = SyncStorageEngine.calculateDefaultFlexTime(pollFrequency);

    long identityToken = clearCallingIdentity();
    try {
        SyncStorageEngine.EndPoint info =
                new SyncStorageEngine.EndPoint(account, authority, userId);
        getSyncManager().updateOrAddPeriodicSync(info, pollFrequency,
                defaultFlex, extras);
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
 
Example 16
Source File: ClipboardService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private final void addActiveOwnerLocked(int uid, String pkg) {
    final IPackageManager pm = AppGlobals.getPackageManager();
    final int targetUserHandle = UserHandle.getCallingUserId();
    final long oldIdentity = Binder.clearCallingIdentity();
    try {
        PackageInfo pi = pm.getPackageInfo(pkg, 0, targetUserHandle);
        if (pi == null) {
            throw new IllegalArgumentException("Unknown package " + pkg);
        }
        if (!UserHandle.isSameApp(pi.applicationInfo.uid, uid)) {
            throw new SecurityException("Calling uid " + uid
                    + " does not own package " + pkg);
        }
    } catch (RemoteException e) {
        // Can't happen; the package manager is in the same process
    } finally {
        Binder.restoreCallingIdentity(oldIdentity);
    }
    PerUserClipboard clipboard = getClipboard();
    if (clipboard.primaryClip != null && !clipboard.activePermissionOwners.contains(pkg)) {
        final int N = clipboard.primaryClip.getItemCount();
        for (int i=0; i<N; i++) {
            grantItemLocked(clipboard.primaryClip.getItemAt(i), clipboard.primaryClipUid, pkg,
                    UserHandle.getUserId(uid));
        }
        clipboard.activePermissionOwners.add(pkg);
    }
}
 
Example 17
Source File: DreamManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override // Binder call
public void setDreamComponents(ComponentName[] componentNames) {
    checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);

    final int userId = UserHandle.getCallingUserId();
    final long ident = Binder.clearCallingIdentity();
    try {
        setDreamComponentsForUser(userId, componentNames);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 18
Source File: DreamManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override // Binder call
public ComponentName[] getDreamComponents() {
    checkPermission(android.Manifest.permission.READ_DREAM_STATE);

    final int userId = UserHandle.getCallingUserId();
    final long ident = Binder.clearCallingIdentity();
    try {
        return getDreamComponentsForUser(userId);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 19
Source File: CrossProfileAppsServiceImpl.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public int getCallingUserId() {
    return UserHandle.getCallingUserId();
}
 
Example 20
Source File: SettingsProvider.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
private static int getRequestingUserId(Bundle args) {
    final int callingUserId = UserHandle.getCallingUserId();
    return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
            : callingUserId;
}