UserController.java revision 84a4c971c484f05f2a2494d6353f36f4d954a5e0
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
21import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
23import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
25import static android.content.Context.KEYGUARD_SERVICE;
26import static android.os.Process.SYSTEM_UID;
27
28import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
31import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
33import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
34import static com.android.server.am.ActivityManagerService.MY_PID;
35import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
36import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
38import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
39import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
40import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
41import static com.android.server.am.UserState.STATE_BOOTING;
42import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
43import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
44import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
45
46import android.annotation.NonNull;
47import android.annotation.UserIdInt;
48import android.app.ActivityManager;
49import android.app.AppOpsManager;
50import android.app.Dialog;
51import android.app.IStopUserCallback;
52import android.app.IUserSwitchObserver;
53import android.app.KeyguardManager;
54import android.content.Context;
55import android.content.IIntentReceiver;
56import android.content.Intent;
57import android.content.pm.PackageManager;
58import android.content.pm.UserInfo;
59import android.os.BatteryStats;
60import android.os.Binder;
61import android.os.Build;
62import android.os.Bundle;
63import android.os.Debug;
64import android.os.Handler;
65import android.os.IBinder;
66import android.os.IProgressListener;
67import android.os.IRemoteCallback;
68import android.os.IUserManager;
69import android.os.Process;
70import android.os.RemoteCallbackList;
71import android.os.RemoteException;
72import android.os.ServiceManager;
73import android.os.UserHandle;
74import android.os.UserManager;
75import android.os.UserManagerInternal;
76import android.os.storage.IMountService;
77import android.os.storage.StorageManager;
78import android.util.IntArray;
79import android.util.Pair;
80import android.util.Slog;
81import android.util.SparseArray;
82import android.util.SparseIntArray;
83
84import com.android.internal.R;
85import com.android.internal.annotations.GuardedBy;
86import com.android.internal.util.ArrayUtils;
87import com.android.internal.widget.LockPatternUtils;
88import com.android.server.LocalServices;
89import com.android.server.pm.UserManagerService;
90
91import java.io.PrintWriter;
92import java.util.ArrayList;
93import java.util.Arrays;
94import java.util.HashSet;
95import java.util.List;
96import java.util.Objects;
97import java.util.Set;
98
99/**
100 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
101 */
102final class UserController {
103    private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
104    // Maximum number of users we allow to be running at a time.
105    static final int MAX_RUNNING_USERS = 3;
106
107    // Amount of time we wait for observers to handle a user switch before
108    // giving up on them and unfreezing the screen.
109    static final int USER_SWITCH_TIMEOUT = 2 * 1000;
110
111    private final ActivityManagerService mService;
112    private final Handler mHandler;
113
114    // Holds the current foreground user's id
115    private int mCurrentUserId = UserHandle.USER_SYSTEM;
116    // Holds the target user's id during a user switch
117    private int mTargetUserId = UserHandle.USER_NULL;
118
119    /**
120     * Which users have been started, so are allowed to run code.
121     */
122    @GuardedBy("mService")
123    private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
124
125    /**
126     * LRU list of history of current users.  Most recently current is at the end.
127     */
128    private final ArrayList<Integer> mUserLru = new ArrayList<>();
129
130    /**
131     * Constant array of the users that are currently started.
132     */
133    private int[] mStartedUserArray = new int[] { 0 };
134
135    // If there are multiple profiles for the current user, their ids are here
136    // Currently only the primary user can have managed profiles
137    private int[] mCurrentProfileIds = new int[] {};
138
139    /**
140     * Mapping from each known user ID to the profile group ID it is associated with.
141     */
142    private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
143
144    /**
145     * Registered observers of the user switching mechanics.
146     */
147    private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
148            = new RemoteCallbackList<>();
149
150    /**
151     * Currently active user switch.
152     */
153    Object mCurUserSwitchCallback;
154
155    private volatile UserManagerService mUserManager;
156
157    private final LockPatternUtils mLockPatternUtils;
158
159    UserController(ActivityManagerService service) {
160        mService = service;
161        mHandler = mService.mHandler;
162        // User 0 is the first and only user that runs at boot.
163        final UserState uss = new UserState(UserHandle.SYSTEM);
164        mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
165        mUserLru.add(UserHandle.USER_SYSTEM);
166        mLockPatternUtils = new LockPatternUtils(mService.mContext);
167        updateStartedUserArrayLocked();
168    }
169
170    void finishUserSwitch(UserState uss) {
171        synchronized (mService) {
172            finishUserBoot(uss);
173
174            startProfilesLocked();
175            stopRunningUsersLocked(MAX_RUNNING_USERS);
176        }
177    }
178
179    void stopRunningUsersLocked(int maxRunningUsers) {
180        int num = mUserLru.size();
181        int i = 0;
182        while (num > maxRunningUsers && i < mUserLru.size()) {
183            Integer oldUserId = mUserLru.get(i);
184            UserState oldUss = mStartedUsers.get(oldUserId);
185            if (oldUss == null) {
186                // Shouldn't happen, but be sane if it does.
187                mUserLru.remove(i);
188                num--;
189                continue;
190            }
191            if (oldUss.state == UserState.STATE_STOPPING
192                    || oldUss.state == UserState.STATE_SHUTDOWN) {
193                // This user is already stopping, doesn't count.
194                num--;
195                i++;
196                continue;
197            }
198            if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
199                // Owner/System user and current user can't be stopped. We count it as running
200                // when it is not a pure system user.
201                if (UserInfo.isSystemOnly(oldUserId)) {
202                    num--;
203                }
204                i++;
205                continue;
206            }
207            // This is a user to be stopped.
208            if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
209                num--;
210            }
211            num--;
212            i++;
213        }
214    }
215
216    private void finishUserBoot(UserState uss) {
217        finishUserBoot(uss, null);
218    }
219
220    private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
221        final int userId = uss.mHandle.getIdentifier();
222        synchronized (mService) {
223            // Bail if we ended up with a stale user
224            if (mStartedUsers.get(userId) != uss) return;
225
226            // We always walk through all the user lifecycle states to send
227            // consistent developer events. We step into RUNNING_LOCKED here,
228            // but we might immediately step into RUNNING below if the user
229            // storage is already unlocked.
230            if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
231                Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
232                intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
233                intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
234                        | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
235                mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
236                        new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
237                        AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
238            }
239
240            // We need to delay unlocking managed profiles until the parent user
241            // is also unlocked.
242            if (getUserManager().isManagedProfile(userId)) {
243                final UserInfo parent = getUserManager().getProfileParent(userId);
244                if (parent != null
245                        && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
246                    Slog.d(TAG, "User " + userId + " (parent " + parent.id
247                            + "): attempting unlock because parent is unlocked");
248                    maybeUnlockUser(userId);
249                } else {
250                    Slog.d(TAG, "User " + userId + " (parent " + parent.id
251                            + "): delaying unlock because parent is locked");
252                }
253            } else {
254                maybeUnlockUser(userId);
255            }
256        }
257    }
258
259    /**
260     * Step from {@link UserState#STATE_RUNNING_LOCKED} to
261     * {@link UserState#STATE_RUNNING_UNLOCKING}.
262     */
263    private void finishUserUnlocking(final UserState uss) {
264        final int userId = uss.mHandle.getIdentifier();
265        synchronized (mService) {
266            // Bail if we ended up with a stale user
267            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
268
269            // Only keep marching forward if user is actually unlocked
270            if (!isUserKeyUnlocked(userId)) return;
271
272            if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
273                uss.mUnlockProgress.start();
274
275                // Prepare app storage before we go any further
276                uss.mUnlockProgress.setProgress(5,
277                        mService.mContext.getString(R.string.android_start_title));
278                mUserManager.onBeforeUnlockUser(userId);
279                uss.mUnlockProgress.setProgress(20);
280
281                // Dispatch unlocked to system services
282                mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
283
284                // Dispatch unlocked to external apps
285                final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
286                unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
287                unlockedIntent.addFlags(
288                        Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
289                mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
290                        null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
291                        userId);
292
293                if (getUserInfo(userId).isManagedProfile()) {
294                    UserInfo parent = getUserManager().getProfileParent(userId);
295                    if (parent != null) {
296                        final Intent profileUnlockedIntent = new Intent(
297                                Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
298                        profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
299                        profileUnlockedIntent.addFlags(
300                                Intent.FLAG_RECEIVER_REGISTERED_ONLY
301                                | Intent.FLAG_RECEIVER_FOREGROUND);
302                        mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
303                                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
304                                null, false, false, MY_PID, SYSTEM_UID,
305                                parent.id);
306                    }
307                }
308
309                // Send PRE_BOOT broadcasts if fingerprint changed
310                final UserInfo info = getUserInfo(userId);
311                if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
312                    uss.mUnlockProgress.startSegment(80);
313                    new PreBootBroadcaster(mService, userId, uss.mUnlockProgress) {
314                        @Override
315                        public void onFinished() {
316                            finishUserUnlocked(uss);
317                        }
318                    }.sendNext();
319                } else {
320                    finishUserUnlocked(uss);
321                }
322            }
323        }
324    }
325
326    /**
327     * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
328     * {@link UserState#STATE_RUNNING_UNLOCKED}.
329     */
330    private void finishUserUnlocked(UserState uss) {
331        try {
332            finishUserUnlockedInternal(uss);
333        } finally {
334            uss.mUnlockProgress.finish();
335        }
336    }
337
338    private void finishUserUnlockedInternal(UserState uss) {
339        final int userId = uss.mHandle.getIdentifier();
340        synchronized (mService) {
341            // Bail if we ended up with a stale user
342            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
343
344            // Only keep marching forward if user is actually unlocked
345            if (!isUserKeyUnlocked(userId)) return;
346
347            if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
348                // Remember that we logged in
349                mUserManager.onUserLoggedIn(userId);
350
351                final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
352                bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
353                bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
354                        | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
355                mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
356                        new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
357                        AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
358            }
359        }
360    }
361
362    int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
363        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
364                != PackageManager.PERMISSION_GRANTED) {
365            String msg = "Permission Denial: switchUser() from pid="
366                    + Binder.getCallingPid()
367                    + ", uid=" + Binder.getCallingUid()
368                    + " requires " + INTERACT_ACROSS_USERS_FULL;
369            Slog.w(TAG, msg);
370            throw new SecurityException(msg);
371        }
372        if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
373            throw new IllegalArgumentException("Can't stop system user " + userId);
374        }
375        mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
376                userId);
377        synchronized (mService) {
378            return stopUsersLocked(userId, force, callback);
379        }
380    }
381
382    /**
383     * Stops the user along with its related users. The method calls
384     * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
385     */
386    private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
387        if (userId == UserHandle.USER_SYSTEM) {
388            return USER_OP_ERROR_IS_SYSTEM;
389        }
390        if (isCurrentUserLocked(userId)) {
391            return USER_OP_IS_CURRENT;
392        }
393        int[] usersToStop = getUsersToStopLocked(userId);
394        // If one of related users is system or current, no related users should be stopped
395        for (int i = 0; i < usersToStop.length; i++) {
396            int relatedUserId = usersToStop[i];
397            if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
398                if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
399                        + relatedUserId);
400                // We still need to stop the requested user if it's a force stop.
401                if (force) {
402                    Slog.i(TAG,
403                            "Force stop user " + userId + ". Related users will not be stopped");
404                    stopSingleUserLocked(userId, callback);
405                    return USER_OP_SUCCESS;
406                }
407                return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
408            }
409        }
410        if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
411        for (int userIdToStop : usersToStop) {
412            stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
413        }
414        return USER_OP_SUCCESS;
415    }
416
417    private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
418        if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
419        final UserState uss = mStartedUsers.get(userId);
420        if (uss == null) {
421            // User is not started, nothing to do...  but we do need to
422            // callback if requested.
423            if (callback != null) {
424                mHandler.post(new Runnable() {
425                    @Override
426                    public void run() {
427                        try {
428                            callback.userStopped(userId);
429                        } catch (RemoteException e) {
430                        }
431                    }
432                });
433            }
434            return;
435        }
436
437        if (callback != null) {
438            uss.mStopCallbacks.add(callback);
439        }
440
441        if (uss.state != UserState.STATE_STOPPING
442                && uss.state != UserState.STATE_SHUTDOWN) {
443            uss.setState(UserState.STATE_STOPPING);
444            updateStartedUserArrayLocked();
445
446            long ident = Binder.clearCallingIdentity();
447            try {
448                // We are going to broadcast ACTION_USER_STOPPING and then
449                // once that is done send a final ACTION_SHUTDOWN and then
450                // stop the user.
451                final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
452                stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
453                stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
454                stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
455                // This is the result receiver for the initial stopping broadcast.
456                final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
457                    @Override
458                    public void performReceive(Intent intent, int resultCode, String data,
459                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
460                        mHandler.post(new Runnable() {
461                            @Override
462                            public void run() {
463                                finishUserStopping(userId, uss);
464                            }
465                        });
466                    }
467                };
468                // Kick things off.
469                mService.broadcastIntentLocked(null, null, stoppingIntent,
470                        null, stoppingReceiver, 0, null, null,
471                        new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
472                        null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
473            } finally {
474                Binder.restoreCallingIdentity(ident);
475            }
476        }
477    }
478
479    void finishUserStopping(final int userId, final UserState uss) {
480        // On to the next.
481        final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
482        // This is the result receiver for the final shutdown broadcast.
483        final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
484            @Override
485            public void performReceive(Intent intent, int resultCode, String data,
486                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
487                mHandler.post(new Runnable() {
488                    @Override
489                    public void run() {
490                        finishUserStopped(uss);
491                    }
492                });
493            }
494        };
495
496        synchronized (mService) {
497            if (uss.state != UserState.STATE_STOPPING) {
498                // Whoops, we are being started back up.  Abort, abort!
499                return;
500            }
501            uss.setState(UserState.STATE_SHUTDOWN);
502        }
503
504        mService.mBatteryStatsService.noteEvent(
505                BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
506                Integer.toString(userId), userId);
507        mService.mSystemServiceManager.stopUser(userId);
508
509        synchronized (mService) {
510            mService.broadcastIntentLocked(null, null, shutdownIntent,
511                    null, shutdownReceiver, 0, null, null, null,
512                    AppOpsManager.OP_NONE,
513                    null, true, false, MY_PID, SYSTEM_UID, userId);
514        }
515    }
516
517    void finishUserStopped(UserState uss) {
518        final int userId = uss.mHandle.getIdentifier();
519        boolean stopped;
520        ArrayList<IStopUserCallback> callbacks;
521        synchronized (mService) {
522            callbacks = new ArrayList<>(uss.mStopCallbacks);
523            if (mStartedUsers.get(userId) != uss) {
524                stopped = false;
525            } else if (uss.state != UserState.STATE_SHUTDOWN) {
526                stopped = false;
527            } else {
528                stopped = true;
529                // User can no longer run.
530                mStartedUsers.remove(userId);
531                mUserLru.remove(Integer.valueOf(userId));
532                updateStartedUserArrayLocked();
533
534                mService.onUserStoppedLocked(userId);
535                // Clean up all state and processes associated with the user.
536                // Kill all the processes for the user.
537                forceStopUserLocked(userId, "finish user");
538            }
539        }
540
541        for (int i = 0; i < callbacks.size(); i++) {
542            try {
543                if (stopped) callbacks.get(i).userStopped(userId);
544                else callbacks.get(i).userStopAborted(userId);
545            } catch (RemoteException e) {
546            }
547        }
548
549        if (stopped) {
550            mService.mSystemServiceManager.cleanupUser(userId);
551            synchronized (mService) {
552                mService.mStackSupervisor.removeUserLocked(userId);
553            }
554            // Remove the user if it is ephemeral.
555            if (getUserInfo(userId).isEphemeral()) {
556                mUserManager.removeUser(userId);
557            }
558        }
559    }
560
561    /**
562     * Determines the list of users that should be stopped together with the specified
563     * {@code userId}. The returned list includes {@code userId}.
564     */
565    private @NonNull int[] getUsersToStopLocked(int userId) {
566        int startedUsersSize = mStartedUsers.size();
567        IntArray userIds = new IntArray();
568        userIds.add(userId);
569        synchronized (mUserProfileGroupIdsSelfLocked) {
570            int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
571                    UserInfo.NO_PROFILE_GROUP_ID);
572            for (int i = 0; i < startedUsersSize; i++) {
573                UserState uss = mStartedUsers.valueAt(i);
574                int startedUserId = uss.mHandle.getIdentifier();
575                // Skip unrelated users (profileGroupId mismatch)
576                int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
577                        UserInfo.NO_PROFILE_GROUP_ID);
578                boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
579                        && (userGroupId == startedUserGroupId);
580                // userId has already been added
581                boolean sameUserId = startedUserId == userId;
582                if (!sameGroup || sameUserId) {
583                    continue;
584                }
585                userIds.add(startedUserId);
586            }
587        }
588        return userIds.toArray();
589    }
590
591    private void forceStopUserLocked(int userId, String reason) {
592        mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
593                userId, reason);
594        Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
595        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
596                | Intent.FLAG_RECEIVER_FOREGROUND);
597        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
598        mService.broadcastIntentLocked(null, null, intent,
599                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
600                null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
601    }
602
603    /**
604     * Stops the guest or ephemeral user if it has gone to the background.
605     */
606    private void stopGuestOrEphemeralUserIfBackground() {
607        synchronized (mService) {
608            final int num = mUserLru.size();
609            for (int i = 0; i < num; i++) {
610                Integer oldUserId = mUserLru.get(i);
611                UserState oldUss = mStartedUsers.get(oldUserId);
612                if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
613                        || oldUss.state == UserState.STATE_STOPPING
614                        || oldUss.state == UserState.STATE_SHUTDOWN) {
615                    continue;
616                }
617                UserInfo userInfo = getUserInfo(oldUserId);
618                if (userInfo.isEphemeral()) {
619                    LocalServices.getService(UserManagerInternal.class)
620                            .onEphemeralUserStop(oldUserId);
621                }
622                if (userInfo.isGuest() || userInfo.isEphemeral()) {
623                    // This is a user to be stopped.
624                    stopUsersLocked(oldUserId, true, null);
625                    break;
626                }
627            }
628        }
629    }
630
631    void startProfilesLocked() {
632        if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
633        List<UserInfo> profiles = getUserManager().getProfiles(
634                mCurrentUserId, false /* enabledOnly */);
635        List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
636        for (UserInfo user : profiles) {
637            if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
638                    && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
639                profilesToStart.add(user);
640            }
641        }
642        final int profilesToStartSize = profilesToStart.size();
643        int i = 0;
644        for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
645            startUser(profilesToStart.get(i).id, /* foreground= */ false);
646        }
647        if (i < profilesToStartSize) {
648            Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
649        }
650    }
651
652    private UserManagerService getUserManager() {
653        UserManagerService userManager = mUserManager;
654        if (userManager == null) {
655            IBinder b = ServiceManager.getService(Context.USER_SERVICE);
656            userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
657        }
658        return userManager;
659    }
660
661    private IMountService getMountService() {
662        return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
663    }
664
665    private boolean isUserKeyUnlocked(int userId) {
666        final IMountService mountService = getMountService();
667        if (mountService != null) {
668            try {
669                return mountService.isUserKeyUnlocked(userId);
670            } catch (RemoteException e) {
671                throw e.rethrowAsRuntimeException();
672            }
673        } else {
674            Slog.w(TAG, "Mount service not published; guessing locked state based on property");
675            return !StorageManager.isFileEncryptedNativeOrEmulated();
676        }
677    }
678
679    boolean startUser(final int userId, final boolean foreground) {
680        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
681                != PackageManager.PERMISSION_GRANTED) {
682            String msg = "Permission Denial: switchUser() from pid="
683                    + Binder.getCallingPid()
684                    + ", uid=" + Binder.getCallingUid()
685                    + " requires " + INTERACT_ACROSS_USERS_FULL;
686            Slog.w(TAG, msg);
687            throw new SecurityException(msg);
688        }
689
690        if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
691
692        final long ident = Binder.clearCallingIdentity();
693        try {
694            synchronized (mService) {
695                final int oldUserId = mCurrentUserId;
696                if (oldUserId == userId) {
697                    return true;
698                }
699
700                mService.mStackSupervisor.setLockTaskModeLocked(null,
701                        ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
702
703                final UserInfo userInfo = getUserInfo(userId);
704                if (userInfo == null) {
705                    Slog.w(TAG, "No user info for user #" + userId);
706                    return false;
707                }
708                if (foreground && userInfo.isManagedProfile()) {
709                    Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
710                    return false;
711                }
712
713                if (foreground) {
714                    mService.mWindowManager.startFreezingScreen(
715                            R.anim.screen_user_exit, R.anim.screen_user_enter);
716                }
717
718                boolean needStart = false;
719
720                // If the user we are switching to is not currently started, then
721                // we need to start it now.
722                if (mStartedUsers.get(userId) == null) {
723                    mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
724                    updateStartedUserArrayLocked();
725                    needStart = true;
726                }
727
728                final UserState uss = mStartedUsers.get(userId);
729                final Integer userIdInt = userId;
730                mUserLru.remove(userIdInt);
731                mUserLru.add(userIdInt);
732
733                if (foreground) {
734                    mCurrentUserId = userId;
735                    mService.updateUserConfigurationLocked();
736                    mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
737                    updateCurrentProfileIdsLocked();
738                    mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
739                    // Once the internal notion of the active user has switched, we lock the device
740                    // with the option to show the user switcher on the keyguard.
741                    mService.mWindowManager.lockNow(null);
742                } else {
743                    final Integer currentUserIdInt = mCurrentUserId;
744                    updateCurrentProfileIdsLocked();
745                    mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
746                    mUserLru.remove(currentUserIdInt);
747                    mUserLru.add(currentUserIdInt);
748                }
749
750                // Make sure user is in the started state.  If it is currently
751                // stopping, we need to knock that off.
752                if (uss.state == UserState.STATE_STOPPING) {
753                    // If we are stopping, we haven't sent ACTION_SHUTDOWN,
754                    // so we can just fairly silently bring the user back from
755                    // the almost-dead.
756                    uss.setState(uss.lastState);
757                    updateStartedUserArrayLocked();
758                    needStart = true;
759                } else if (uss.state == UserState.STATE_SHUTDOWN) {
760                    // This means ACTION_SHUTDOWN has been sent, so we will
761                    // need to treat this as a new boot of the user.
762                    uss.setState(UserState.STATE_BOOTING);
763                    updateStartedUserArrayLocked();
764                    needStart = true;
765                }
766
767                if (uss.state == UserState.STATE_BOOTING) {
768                    // Give user manager a chance to propagate user restrictions
769                    // to other services and prepare app storage
770                    getUserManager().onBeforeStartUser(userId);
771
772                    // Booting up a new user, need to tell system services about it.
773                    // Note that this is on the same handler as scheduling of broadcasts,
774                    // which is important because it needs to go first.
775                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
776                }
777
778                if (foreground) {
779                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
780                            oldUserId));
781                    mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
782                    mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
783                    mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
784                            oldUserId, userId, uss));
785                    mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
786                            oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
787                }
788
789                if (needStart) {
790                    // Send USER_STARTED broadcast
791                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
792                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
793                            | Intent.FLAG_RECEIVER_FOREGROUND);
794                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
795                    mService.broadcastIntentLocked(null, null, intent,
796                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
797                            null, false, false, MY_PID, SYSTEM_UID, userId);
798                }
799
800                if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
801                    if (userId != UserHandle.USER_SYSTEM) {
802                        Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
803                        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
804                        mService.broadcastIntentLocked(null, null, intent, null,
805                                new IIntentReceiver.Stub() {
806                                    @Override
807                                    public void performReceive(Intent intent, int resultCode,
808                                            String data, Bundle extras, boolean ordered,
809                                            boolean sticky, int sendingUser) {
810                                        mHandler.post(new Runnable() {
811                                            @Override
812                                            public void run() {
813                                                onUserInitialized(uss, foreground,
814                                                        oldUserId, userId);
815                                            }
816                                        });
817                                    }
818                                }, 0, null, null, null, AppOpsManager.OP_NONE,
819                                null, true, false, MY_PID, SYSTEM_UID, userId);
820                        uss.initializing = true;
821                    } else {
822                        getUserManager().makeInitialized(userInfo.id);
823                    }
824                }
825
826                if (foreground) {
827                    if (!uss.initializing) {
828                        moveUserToForegroundLocked(uss, oldUserId, userId);
829                    }
830                } else {
831                    mService.mUserController.finishUserBoot(uss);
832                }
833
834                if (needStart) {
835                    Intent intent = new Intent(Intent.ACTION_USER_STARTING);
836                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
837                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
838                    mService.broadcastIntentLocked(null, null, intent,
839                            null, new IIntentReceiver.Stub() {
840                                @Override
841                                public void performReceive(Intent intent, int resultCode,
842                                        String data, Bundle extras, boolean ordered, boolean sticky,
843                                        int sendingUser) throws RemoteException {
844                                }
845                            }, 0, null, null,
846                            new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
847                            null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
848                }
849            }
850        } finally {
851            Binder.restoreCallingIdentity(ident);
852        }
853
854        return true;
855    }
856
857    /**
858     * Start user, if its not already running, and bring it to foreground.
859     */
860    boolean startUserInForeground(final int userId, Dialog dlg) {
861        boolean result = startUser(userId, /* foreground */ true);
862        dlg.dismiss();
863        return result;
864    }
865
866    boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
867        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
868                != PackageManager.PERMISSION_GRANTED) {
869            String msg = "Permission Denial: unlockUser() from pid="
870                    + Binder.getCallingPid()
871                    + ", uid=" + Binder.getCallingUid()
872                    + " requires " + INTERACT_ACROSS_USERS_FULL;
873            Slog.w(TAG, msg);
874            throw new SecurityException(msg);
875        }
876
877        final long binderToken = Binder.clearCallingIdentity();
878        try {
879            return unlockUserCleared(userId, token, secret, listener);
880        } finally {
881            Binder.restoreCallingIdentity(binderToken);
882        }
883    }
884
885    /**
886     * Attempt to unlock user without a credential token. This typically
887     * succeeds when the device doesn't have credential-encrypted storage, or
888     * when the the credential-encrypted storage isn't tied to a user-provided
889     * PIN or pattern.
890     */
891    boolean maybeUnlockUser(final int userId) {
892        // Try unlocking storage using empty token
893        return unlockUserCleared(userId, null, null, null);
894    }
895
896    private static void notifyFinished(int userId, IProgressListener listener) {
897        if (listener == null) return;
898        try {
899            listener.onFinished(userId, null);
900        } catch (RemoteException ignored) {
901        }
902    }
903
904    boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
905            IProgressListener listener) {
906        final UserState uss;
907        synchronized (mService) {
908            // Bail if user isn't actually running, otherwise register the given
909            // listener to watch for unlock progress
910            uss = mStartedUsers.get(userId);
911            if (uss == null) {
912                notifyFinished(userId, listener);
913                return false;
914            } else {
915                uss.mUnlockProgress.addListener(listener);
916            }
917        }
918
919        if (!isUserKeyUnlocked(userId)) {
920            final UserInfo userInfo = getUserInfo(userId);
921            final IMountService mountService = getMountService();
922            try {
923                mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
924            } catch (RemoteException | RuntimeException e) {
925                Slog.w(TAG, "Failed to unlock: " + e.getMessage());
926                notifyFinished(userId, listener);
927                return false;
928            }
929        }
930
931        synchronized (mService) {
932            finishUserUnlocking(uss);
933
934            // We just unlocked a user, so let's now attempt to unlock any
935            // managed profiles under that user.
936            for (int i = 0; i < mStartedUsers.size(); i++) {
937                final int testUserId = mStartedUsers.keyAt(i);
938                final UserInfo parent = getUserManager().getProfileParent(testUserId);
939                if (parent != null && parent.id == userId && testUserId != userId) {
940                    Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
941                            + "): attempting unlock because parent was just unlocked");
942                    maybeUnlockUser(testUserId);
943                }
944            }
945        }
946
947        return true;
948    }
949
950    void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
951        // The dialog will show and then initiate the user switch by calling startUserInForeground
952        Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
953                fromToUserPair.second, true /* above system */);
954        d.show();
955    }
956
957    void dispatchForegroundProfileChanged(int userId) {
958        final int observerCount = mUserSwitchObservers.beginBroadcast();
959        for (int i = 0; i < observerCount; i++) {
960            try {
961                mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
962            } catch (RemoteException e) {
963                // Ignore
964            }
965        }
966        mUserSwitchObservers.finishBroadcast();
967    }
968
969    /** Called on handler thread */
970    void dispatchUserSwitchComplete(int userId) {
971        final int observerCount = mUserSwitchObservers.beginBroadcast();
972        for (int i = 0; i < observerCount; i++) {
973            try {
974                mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
975            } catch (RemoteException e) {
976            }
977        }
978        mUserSwitchObservers.finishBroadcast();
979    }
980
981    private void stopBackgroundUsersIfEnforced(int oldUserId) {
982        // Never stop system user
983        if (oldUserId == UserHandle.USER_SYSTEM) {
984            return;
985        }
986        // For now, only check for user restriction. Additional checks can be added here
987        boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
988                oldUserId);
989        if (!disallowRunInBg) {
990            return;
991        }
992        synchronized (mService) {
993            if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
994                    + " and related users");
995            stopUsersLocked(oldUserId, false, null);
996        }
997    }
998
999    void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1000        synchronized (mService) {
1001            Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
1002            sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1003        }
1004    }
1005
1006    void dispatchUserSwitch(final UserState uss, final int oldUserId,
1007            final int newUserId) {
1008        final int observerCount = mUserSwitchObservers.beginBroadcast();
1009        if (observerCount > 0) {
1010            final IRemoteCallback callback = new IRemoteCallback.Stub() {
1011                int mCount = 0;
1012                @Override
1013                public void sendResult(Bundle data) throws RemoteException {
1014                    synchronized (mService) {
1015                        if (mCurUserSwitchCallback == this) {
1016                            mCount++;
1017                            if (mCount == observerCount) {
1018                                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1019                            }
1020                        }
1021                    }
1022                }
1023            };
1024            synchronized (mService) {
1025                uss.switching = true;
1026                mCurUserSwitchCallback = callback;
1027            }
1028            for (int i = 0; i < observerCount; i++) {
1029                try {
1030                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
1031                            newUserId, callback);
1032                } catch (RemoteException e) {
1033                }
1034            }
1035        } else {
1036            synchronized (mService) {
1037                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1038            }
1039        }
1040        mUserSwitchObservers.finishBroadcast();
1041    }
1042
1043    void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1044        mCurUserSwitchCallback = null;
1045        mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1046        mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1047                oldUserId, newUserId, uss));
1048    }
1049
1050    void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1051        completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
1052    }
1053
1054    void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
1055        synchronized (mService) {
1056            if (foreground) {
1057                moveUserToForegroundLocked(uss, oldUserId, newUserId);
1058            }
1059        }
1060        completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
1061    }
1062
1063    void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
1064            boolean clearInitializing, boolean clearSwitching) {
1065        boolean unfrozen = false;
1066        synchronized (mService) {
1067            if (clearInitializing) {
1068                uss.initializing = false;
1069                getUserManager().makeInitialized(uss.mHandle.getIdentifier());
1070            }
1071            if (clearSwitching) {
1072                uss.switching = false;
1073            }
1074            if (!uss.switching && !uss.initializing) {
1075                mService.mWindowManager.stopFreezingScreen();
1076                unfrozen = true;
1077            }
1078        }
1079        if (unfrozen) {
1080            mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1081            mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1082                    newUserId, 0));
1083        }
1084        stopGuestOrEphemeralUserIfBackground();
1085        stopBackgroundUsersIfEnforced(oldUserId);
1086    }
1087
1088    void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1089        boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1090        if (homeInFront) {
1091            mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1092        } else {
1093            mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
1094        }
1095        EventLogTags.writeAmSwitchUser(newUserId);
1096        sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1097    }
1098
1099    void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1100        long ident = Binder.clearCallingIdentity();
1101        try {
1102            Intent intent;
1103            if (oldUserId >= 0) {
1104                // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1105                List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1106                int count = profiles.size();
1107                for (int i = 0; i < count; i++) {
1108                    int profileUserId = profiles.get(i).id;
1109                    intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1110                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1111                            | Intent.FLAG_RECEIVER_FOREGROUND);
1112                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1113                    mService.broadcastIntentLocked(null, null, intent,
1114                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1115                            null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1116                }
1117            }
1118            if (newUserId >= 0) {
1119                // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1120                List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1121                int count = profiles.size();
1122                for (int i = 0; i < count; i++) {
1123                    int profileUserId = profiles.get(i).id;
1124                    intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1125                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1126                            | Intent.FLAG_RECEIVER_FOREGROUND);
1127                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1128                    mService.broadcastIntentLocked(null, null, intent,
1129                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1130                            null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1131                }
1132                intent = new Intent(Intent.ACTION_USER_SWITCHED);
1133                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1134                        | Intent.FLAG_RECEIVER_FOREGROUND);
1135                intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1136                mService.broadcastIntentLocked(null, null, intent,
1137                        null, null, 0, null, null,
1138                        new String[] {android.Manifest.permission.MANAGE_USERS},
1139                        AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1140                        UserHandle.USER_ALL);
1141            }
1142        } finally {
1143            Binder.restoreCallingIdentity(ident);
1144        }
1145    }
1146
1147
1148    int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1149            int allowMode, String name, String callerPackage) {
1150        final int callingUserId = UserHandle.getUserId(callingUid);
1151        if (callingUserId == userId) {
1152            return userId;
1153        }
1154
1155        // Note that we may be accessing mCurrentUserId outside of a lock...
1156        // shouldn't be a big deal, if this is being called outside
1157        // of a locked context there is intrinsically a race with
1158        // the value the caller will receive and someone else changing it.
1159        // We assume that USER_CURRENT_OR_SELF will use the current user; later
1160        // we will switch to the calling user if access to the current user fails.
1161        int targetUserId = unsafeConvertIncomingUserLocked(userId);
1162
1163        if (callingUid != 0 && callingUid != SYSTEM_UID) {
1164            final boolean allow;
1165            if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1166                    callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1167                // If the caller has this permission, they always pass go.  And collect $200.
1168                allow = true;
1169            } else if (allowMode == ALLOW_FULL_ONLY) {
1170                // We require full access, sucks to be you.
1171                allow = false;
1172            } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1173                    callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1174                // If the caller does not have either permission, they are always doomed.
1175                allow = false;
1176            } else if (allowMode == ALLOW_NON_FULL) {
1177                // We are blanket allowing non-full access, you lucky caller!
1178                allow = true;
1179            } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1180                // We may or may not allow this depending on whether the two users are
1181                // in the same profile.
1182                allow = isSameProfileGroup(callingUserId, targetUserId);
1183            } else {
1184                throw new IllegalArgumentException("Unknown mode: " + allowMode);
1185            }
1186            if (!allow) {
1187                if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1188                    // In this case, they would like to just execute as their
1189                    // owner user instead of failing.
1190                    targetUserId = callingUserId;
1191                } else {
1192                    StringBuilder builder = new StringBuilder(128);
1193                    builder.append("Permission Denial: ");
1194                    builder.append(name);
1195                    if (callerPackage != null) {
1196                        builder.append(" from ");
1197                        builder.append(callerPackage);
1198                    }
1199                    builder.append(" asks to run as user ");
1200                    builder.append(userId);
1201                    builder.append(" but is calling from user ");
1202                    builder.append(UserHandle.getUserId(callingUid));
1203                    builder.append("; this requires ");
1204                    builder.append(INTERACT_ACROSS_USERS_FULL);
1205                    if (allowMode != ALLOW_FULL_ONLY) {
1206                        builder.append(" or ");
1207                        builder.append(INTERACT_ACROSS_USERS);
1208                    }
1209                    String msg = builder.toString();
1210                    Slog.w(TAG, msg);
1211                    throw new SecurityException(msg);
1212                }
1213            }
1214        }
1215        if (!allowAll && targetUserId < 0) {
1216            throw new IllegalArgumentException(
1217                    "Call does not support special user #" + targetUserId);
1218        }
1219        // Check shell permission
1220        if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1221            if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1222                throw new SecurityException("Shell does not have permission to access user "
1223                        + targetUserId + "\n " + Debug.getCallers(3));
1224            }
1225        }
1226        return targetUserId;
1227    }
1228
1229    int unsafeConvertIncomingUserLocked(int userId) {
1230        return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1231                ? getCurrentUserIdLocked(): userId;
1232    }
1233
1234    void registerUserSwitchObserver(IUserSwitchObserver observer) {
1235        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1236                != PackageManager.PERMISSION_GRANTED) {
1237            final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1238                    + Binder.getCallingPid()
1239                    + ", uid=" + Binder.getCallingUid()
1240                    + " requires " + INTERACT_ACROSS_USERS_FULL;
1241            Slog.w(TAG, msg);
1242            throw new SecurityException(msg);
1243        }
1244
1245        mUserSwitchObservers.register(observer);
1246    }
1247
1248    void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1249        mUserSwitchObservers.unregister(observer);
1250    }
1251
1252    UserState getStartedUserStateLocked(int userId) {
1253        return mStartedUsers.get(userId);
1254    }
1255
1256    boolean hasStartedUserState(int userId) {
1257        return mStartedUsers.get(userId) != null;
1258    }
1259
1260    private void updateStartedUserArrayLocked() {
1261        int num = 0;
1262        for (int i = 0; i < mStartedUsers.size(); i++) {
1263            UserState uss = mStartedUsers.valueAt(i);
1264            // This list does not include stopping users.
1265            if (uss.state != UserState.STATE_STOPPING
1266                    && uss.state != UserState.STATE_SHUTDOWN) {
1267                num++;
1268            }
1269        }
1270        mStartedUserArray = new int[num];
1271        num = 0;
1272        for (int i = 0; i < mStartedUsers.size(); i++) {
1273            UserState uss = mStartedUsers.valueAt(i);
1274            if (uss.state != UserState.STATE_STOPPING
1275                    && uss.state != UserState.STATE_SHUTDOWN) {
1276                mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1277            }
1278        }
1279    }
1280
1281    void sendBootCompletedLocked(IIntentReceiver resultTo) {
1282        for (int i = 0; i < mStartedUsers.size(); i++) {
1283            UserState uss = mStartedUsers.valueAt(i);
1284            finishUserBoot(uss, resultTo);
1285        }
1286    }
1287
1288    void onSystemReady() {
1289        updateCurrentProfileIdsLocked();
1290    }
1291
1292    /**
1293     * Refreshes the list of users related to the current user when either a
1294     * user switch happens or when a new related user is started in the
1295     * background.
1296     */
1297    private void updateCurrentProfileIdsLocked() {
1298        final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
1299                false /* enabledOnly */);
1300        int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1301        for (int i = 0; i < currentProfileIds.length; i++) {
1302            currentProfileIds[i] = profiles.get(i).id;
1303        }
1304        mCurrentProfileIds = currentProfileIds;
1305
1306        synchronized (mUserProfileGroupIdsSelfLocked) {
1307            mUserProfileGroupIdsSelfLocked.clear();
1308            final List<UserInfo> users = getUserManager().getUsers(false);
1309            for (int i = 0; i < users.size(); i++) {
1310                UserInfo user = users.get(i);
1311                if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1312                    mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1313                }
1314            }
1315        }
1316    }
1317
1318    int[] getStartedUserArrayLocked() {
1319        return mStartedUserArray;
1320    }
1321
1322    boolean isUserRunningLocked(int userId, int flags) {
1323        UserState state = getStartedUserStateLocked(userId);
1324        if (state == null) {
1325            return false;
1326        }
1327        if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1328            return true;
1329        }
1330
1331        final boolean unlocked;
1332        switch (state.state) {
1333            case UserState.STATE_STOPPING:
1334            case UserState.STATE_SHUTDOWN:
1335            default:
1336                return false;
1337
1338            case UserState.STATE_BOOTING:
1339            case UserState.STATE_RUNNING_LOCKED:
1340                unlocked = false;
1341                break;
1342
1343            case UserState.STATE_RUNNING_UNLOCKING:
1344            case UserState.STATE_RUNNING_UNLOCKED:
1345                unlocked = true;
1346                break;
1347        }
1348
1349        if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1350            return !unlocked;
1351        }
1352        if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1353            return unlocked;
1354        }
1355
1356        // One way or another, we're running!
1357        return true;
1358    }
1359
1360    UserInfo getCurrentUser() {
1361        if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1362                != PackageManager.PERMISSION_GRANTED) && (
1363                mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1364                        != PackageManager.PERMISSION_GRANTED)) {
1365            String msg = "Permission Denial: getCurrentUser() from pid="
1366                    + Binder.getCallingPid()
1367                    + ", uid=" + Binder.getCallingUid()
1368                    + " requires " + INTERACT_ACROSS_USERS;
1369            Slog.w(TAG, msg);
1370            throw new SecurityException(msg);
1371        }
1372        synchronized (mService) {
1373            return getCurrentUserLocked();
1374        }
1375    }
1376
1377    UserInfo getCurrentUserLocked() {
1378        int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1379        return getUserInfo(userId);
1380    }
1381
1382    int getCurrentOrTargetUserIdLocked() {
1383        return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1384    }
1385
1386    int getCurrentUserIdLocked() {
1387        return mCurrentUserId;
1388    }
1389
1390    private boolean isCurrentUserLocked(int userId) {
1391        return userId == getCurrentOrTargetUserIdLocked();
1392    }
1393
1394    int setTargetUserIdLocked(int targetUserId) {
1395        return mTargetUserId = targetUserId;
1396    }
1397
1398    int[] getUsers() {
1399        UserManagerService ums = getUserManager();
1400        return ums != null ? ums.getUserIds() : new int[] { 0 };
1401    }
1402
1403    UserInfo getUserInfo(int userId) {
1404        return getUserManager().getUserInfo(userId);
1405    }
1406
1407    int[] getUserIds() {
1408        return getUserManager().getUserIds();
1409    }
1410
1411    boolean exists(int userId) {
1412        return getUserManager().exists(userId);
1413    }
1414
1415    boolean hasUserRestriction(String restriction, int userId) {
1416        return getUserManager().hasUserRestriction(restriction, userId);
1417    }
1418
1419    Set<Integer> getProfileIds(int userId) {
1420        Set<Integer> userIds = new HashSet<>();
1421        final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1422                false /* enabledOnly */);
1423        for (UserInfo user : profiles) {
1424            userIds.add(user.id);
1425        }
1426        return userIds;
1427    }
1428
1429    boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1430        synchronized (mUserProfileGroupIdsSelfLocked) {
1431            int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1432                    UserInfo.NO_PROFILE_GROUP_ID);
1433            int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1434                    UserInfo.NO_PROFILE_GROUP_ID);
1435            return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1436                    && callingProfile == targetProfile;
1437        }
1438    }
1439
1440    boolean isCurrentProfileLocked(int userId) {
1441        return ArrayUtils.contains(mCurrentProfileIds, userId);
1442    }
1443
1444    int[] getCurrentProfileIdsLocked() {
1445        return mCurrentProfileIds;
1446    }
1447
1448    /**
1449     * Returns whether the given user requires credential entry at this time. This is used to
1450     * intercept activity launches for work apps when the Work Challenge is present.
1451     */
1452    boolean shouldConfirmCredentials(int userId) {
1453        synchronized (mService) {
1454            if (mStartedUsers.get(userId) == null) {
1455                return false;
1456            }
1457        }
1458        if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1459            return false;
1460        }
1461        final KeyguardManager km = (KeyguardManager) mService.mContext
1462                .getSystemService(KEYGUARD_SERVICE);
1463        return km.isDeviceLocked(userId);
1464    }
1465
1466    boolean isLockScreenDisabled(@UserIdInt int userId) {
1467        return mLockPatternUtils.isLockScreenDisabled(userId);
1468    }
1469
1470    void dump(PrintWriter pw, boolean dumpAll) {
1471        pw.println("  mStartedUsers:");
1472        for (int i = 0; i < mStartedUsers.size(); i++) {
1473            UserState uss = mStartedUsers.valueAt(i);
1474            pw.print("    User #"); pw.print(uss.mHandle.getIdentifier());
1475            pw.print(": "); uss.dump("", pw);
1476        }
1477        pw.print("  mStartedUserArray: [");
1478        for (int i = 0; i < mStartedUserArray.length; i++) {
1479            if (i > 0) pw.print(", ");
1480            pw.print(mStartedUserArray[i]);
1481        }
1482        pw.println("]");
1483        pw.print("  mUserLru: [");
1484        for (int i = 0; i < mUserLru.size(); i++) {
1485            if (i > 0) pw.print(", ");
1486            pw.print(mUserLru.get(i));
1487        }
1488        pw.println("]");
1489        if (dumpAll) {
1490            pw.print("  mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1491        }
1492        synchronized (mUserProfileGroupIdsSelfLocked) {
1493            if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1494                pw.println("  mUserProfileGroupIds:");
1495                for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1496                    pw.print("    User #");
1497                    pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1498                    pw.print(" -> profile #");
1499                    pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1500                }
1501            }
1502        }
1503    }
1504}
1505