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