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