blob: b2963aa3538326028ae4b31b766cb3b5655a6867 [file] [log] [blame]
Ying Zhengd3cb98e2018-05-11 11:42:48 -07001/*
2 * Copyright (C) 2018 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.car.user;
18
Eric Jeong1545f3b2019-09-16 13:56:52 -070019import static com.android.car.CarLog.TAG_USER;
20
21import android.annotation.NonNull;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070022import android.annotation.Nullable;
Eric Jeong1545f3b2019-09-16 13:56:52 -070023import android.annotation.UserIdInt;
Keun young Parkfb656372019-03-12 18:37:55 -070024import android.app.ActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070025import android.app.ActivityManager.StackInfo;
Keun young Parkfb656372019-03-12 18:37:55 -070026import android.app.IActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070027import android.car.CarOccupantZoneManager;
28import android.car.CarOccupantZoneManager.OccupantTypeEnum;
29import android.car.CarOccupantZoneManager.OccupantZoneInfo;
Eric Jeong1545f3b2019-09-16 13:56:52 -070030import android.car.ICarUserService;
jovanak24470652018-09-11 17:51:57 -070031import android.car.settings.CarSettings;
Felipe Leme5528ff72020-02-10 19:05:14 -080032import android.car.user.CarUserManager;
Antonio Kantekc8114752020-03-05 21:37:39 -080033import android.car.user.CarUserManager.UserLifecycleEvent;
felipeale8c5dce2020-04-15 11:27:06 -070034import android.car.user.CarUserManager.UserLifecycleEventType;
Antonio Kantekc8114752020-03-05 21:37:39 -080035import android.car.user.CarUserManager.UserLifecycleListener;
felipealdfdf8512020-06-01 09:35:45 -070036import android.car.user.UserCreationResult;
felipeal159a2a42020-05-08 10:32:11 -070037import android.car.user.UserIdentificationAssociationResponse;
Mayank Garga55c3092020-05-28 03:19:24 -070038import android.car.user.UserRemovalResult;
felipeale5bf0322020-04-16 15:10:57 -070039import android.car.user.UserSwitchResult;
Eric Jeong3a793b02019-09-30 16:12:53 -070040import android.car.userlib.CarUserManagerHelper;
felipeal19e3d732020-03-18 12:07:32 -070041import android.car.userlib.HalCallback;
42import android.car.userlib.UserHalHelper;
Mayank Garga480dd92020-05-14 03:14:57 -070043import android.content.ComponentName;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070044import android.content.Context;
Mayank Garga480dd92020-05-14 03:14:57 -070045import android.content.pm.PackageManager;
46import android.content.pm.PackageManager.NameNotFoundException;
Eric Jeong1545f3b2019-09-16 13:56:52 -070047import android.content.pm.UserInfo;
felipealdfdf8512020-06-01 09:35:45 -070048import android.content.pm.UserInfo.UserInfoFlag;
Felipe Leme315a53b2020-03-12 10:51:04 -070049import android.content.res.Resources;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070050import android.graphics.Bitmap;
felipealdfdf8512020-06-01 09:35:45 -070051import android.hardware.automotive.vehicle.V2_0.CreateUserRequest;
52import android.hardware.automotive.vehicle.V2_0.CreateUserStatus;
Mayank Garg70732a82020-08-05 20:17:47 -070053import android.hardware.automotive.vehicle.V2_0.InitialUserInfoRequestType;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080054import android.hardware.automotive.vehicle.V2_0.InitialUserInfoResponseAction;
Mayank Garga55c3092020-05-28 03:19:24 -070055import android.hardware.automotive.vehicle.V2_0.RemoveUserRequest;
Mayank Gargeb37d092020-06-02 14:37:57 -070056import android.hardware.automotive.vehicle.V2_0.SwitchUserRequest;
Mayank Garg59f22192020-03-27 00:51:45 -070057import android.hardware.automotive.vehicle.V2_0.SwitchUserStatus;
felipeal5e3ede42020-04-23 18:04:07 -070058import android.hardware.automotive.vehicle.V2_0.UserIdentificationGetRequest;
59import android.hardware.automotive.vehicle.V2_0.UserIdentificationResponse;
felipeal159a2a42020-05-08 10:32:11 -070060import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetAssociation;
61import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetRequest;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080062import android.hardware.automotive.vehicle.V2_0.UsersInfo;
Ying Zheng1ab32b62018-06-26 12:47:26 -070063import android.location.LocationManager;
Eric Jeong1545f3b2019-09-16 13:56:52 -070064import android.os.Binder;
Felipe Leme5528ff72020-02-10 19:05:14 -080065import android.os.Bundle;
Antonio Kantek7236a5b2020-04-06 19:53:55 -070066import android.os.Handler;
67import android.os.HandlerThread;
Keun young Parkfb656372019-03-12 18:37:55 -070068import android.os.RemoteException;
Mayank Garg31e73042020-01-23 00:10:38 -080069import android.os.Trace;
Ying Zhengcf20f442018-06-22 16:54:51 -070070import android.os.UserHandle;
Ying Zheng8f90edb2018-06-13 12:42:31 -070071import android.os.UserManager;
jovanak24470652018-09-11 17:51:57 -070072import android.provider.Settings;
Felipe Lemee3cab982020-03-12 11:39:29 -070073import android.sysprop.CarProperties;
felipeal159a2a42020-05-08 10:32:11 -070074import android.text.TextUtils;
felipeal312416a2020-04-14 12:28:24 -070075import android.util.EventLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070076import android.util.Log;
Felipe Leme5528ff72020-02-10 19:05:14 -080077import android.util.SparseArray;
Mayank Garg31e73042020-01-23 00:10:38 -080078import android.util.TimingsTraceLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070079
80import com.android.car.CarServiceBase;
Keun young Parkb241d022020-04-20 20:31:34 -070081import com.android.car.CarServiceUtils;
Eric Jeongc91f9452019-08-30 15:04:21 -070082import com.android.car.R;
Felipe Leme58412202020-01-09 13:45:33 -080083import com.android.car.hal.UserHalService;
Mayank Garg94f3eb92020-08-12 12:38:58 -070084import com.android.car.internal.CommonConstants;
85import com.android.car.internal.EventLogTags;
86import com.android.car.internal.UserHelperLite;
Mayank Garg4bdfbf72020-08-06 13:27:43 -070087import com.android.car.power.CarPowerManagementService;
Mayank Garg665c20b2020-08-07 16:19:28 -070088import com.android.car.user.InitialUserSetter.InitialUserInfo;
Keun-young Parkd462a912019-02-11 08:53:42 -080089import com.android.internal.annotations.GuardedBy;
Keun young Parkf3523cd2019-04-08 10:09:17 -070090import com.android.internal.annotations.VisibleForTesting;
felipeale5bf0322020-04-16 15:10:57 -070091import com.android.internal.infra.AndroidFuture;
Felipe Leme5528ff72020-02-10 19:05:14 -080092import com.android.internal.os.IResultReceiver;
felipeal5e3ede42020-04-23 18:04:07 -070093import com.android.internal.util.ArrayUtils;
felipeal2a84d512020-04-06 18:52:15 -070094import com.android.internal.util.FunctionalUtils;
Mayank Garge19c2922020-03-30 18:05:53 -070095import com.android.internal.util.Preconditions;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070096import com.android.internal.util.UserIcons;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070097
98import java.io.PrintWriter;
Keun-young Parkd462a912019-02-11 08:53:42 -080099import java.util.ArrayList;
felipeal2d0483c2019-11-02 14:07:22 -0700100import java.util.Arrays;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700101import java.util.Iterator;
102import java.util.List;
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000103import java.util.Objects;
Pavel Maltsev17e81832019-04-04 14:38:41 -0700104import java.util.concurrent.CopyOnWriteArrayList;
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700105import java.util.concurrent.CountDownLatch;
106import java.util.concurrent.TimeUnit;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700107
108/**
109 * User service for cars. Manages users at boot time. Including:
110 *
111 * <ol>
Eric Jeong1545f3b2019-09-16 13:56:52 -0700112 * <li> Creates a user used as driver.
113 * <li> Creates a user used as passenger.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700114 * <li> Creates a secondary admin user on first run.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700115 * <li> Switch drivers.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700116 * <ol/>
117 */
Eric Jeong1545f3b2019-09-16 13:56:52 -0700118public final class CarUserService extends ICarUserService.Stub implements CarServiceBase {
Felipe Leme5528ff72020-02-10 19:05:14 -0800119
felipealf7368962020-04-16 12:55:19 -0700120 private static final String TAG = TAG_USER;
121
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800122 /** {@code int} extra used to represent a user id in a {@link IResultReceiver} response. */
Mayank Garg94f3eb92020-08-12 12:38:58 -0700123 public static final String BUNDLE_USER_ID = CommonConstants.BUNDLE_USER_ID;
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800124 /** {@code int} extra used to represent user flags in a {@link IResultReceiver} response. */
Mayank Garg94f3eb92020-08-12 12:38:58 -0700125 public static final String BUNDLE_USER_FLAGS = CommonConstants.BUNDLE_USER_FLAGS;
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800126 /** {@code String} extra used to represent a user name in a {@link IResultReceiver} response. */
Mayank Garg94f3eb92020-08-12 12:38:58 -0700127 public static final String BUNDLE_USER_NAME = CommonConstants.BUNDLE_USER_NAME;
felipeala68ecef2020-05-19 12:46:08 -0700128 /**
129 * {@code int} extra used to represent the user locales in a {@link IResultReceiver} response.
130 */
131 public static final String BUNDLE_USER_LOCALES =
Mayank Garg94f3eb92020-08-12 12:38:58 -0700132 CommonConstants.BUNDLE_USER_LOCALES;
felipeala68ecef2020-05-19 12:46:08 -0700133 /**
134 * {@code int} extra used to represent the info action in a {@link IResultReceiver} response.
135 */
felipeal1a9410d2020-05-06 13:30:05 -0700136 public static final String BUNDLE_INITIAL_INFO_ACTION =
Mayank Garg94f3eb92020-08-12 12:38:58 -0700137 CommonConstants.BUNDLE_INITIAL_INFO_ACTION;
Felipe Leme5528ff72020-02-10 19:05:14 -0800138
Mayank Garg9ed099e2020-06-04 16:05:20 -0700139 public static final String VEHICLE_HAL_NOT_SUPPORTED = "Vehicle Hal not supported.";
140
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700141 private final Context mContext;
Eric Jeong3a793b02019-09-30 16:12:53 -0700142 private final CarUserManagerHelper mCarUserManagerHelper;
Keun young Parkfb656372019-03-12 18:37:55 -0700143 private final IActivityManager mAm;
Anthony Hugh9932a252019-06-12 16:19:56 -0700144 private final UserManager mUserManager;
145 private final int mMaxRunningUsers;
Mayank Garg70732a82020-08-05 20:17:47 -0700146 private final InitialUserSetter mInitialUserSetter;
Eric Jeongc91f9452019-08-30 15:04:21 -0700147 private final boolean mEnablePassengerSupport;
Mayank Garg9732d602020-08-09 21:02:40 -0700148 private final UserPreCreator mUserPreCreator;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700149
Eric Jeongc91f9452019-08-30 15:04:21 -0700150 private final Object mLockUser = new Object();
151 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800152 private boolean mUser0Unlocked;
Eric Jeongc91f9452019-08-30 15:04:21 -0700153 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800154 private final ArrayList<Runnable> mUser0UnlockTasks = new ArrayList<>();
Eric Jeongc91f9452019-08-30 15:04:21 -0700155 // Only one passenger is supported.
156 @GuardedBy("mLockUser")
157 private @UserIdInt int mLastPassengerId;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700158 /**
159 * Background users that will be restarted in garage mode. This list can include the
Mayank Garg31e73042020-01-23 00:10:38 -0800160 * current foreground user but the current foreground user should not be restarted.
Keun young Parkf3523cd2019-04-08 10:09:17 -0700161 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700162 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700163 private final ArrayList<Integer> mBackgroundUsersToRestart = new ArrayList<>();
164 /**
165 * Keep the list of background users started here. This is wholly for debugging purpose.
166 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700167 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700168 private final ArrayList<Integer> mBackgroundUsersRestartedHere = new ArrayList<>();
169
Felipe Leme58412202020-01-09 13:45:33 -0800170 private final UserHalService mHal;
171
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700172 // HandlerThread and Handler used when notifying app listeners (mAppLifecycleListeners).
Keun young Parkb241d022020-04-20 20:31:34 -0700173 private final HandlerThread mHandlerThread = CarServiceUtils.getHandlerThread(
174 getClass().getSimpleName());
175 private final Handler mHandler = new Handler(mHandlerThread.getLooper());
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700176
Felipe Leme5528ff72020-02-10 19:05:14 -0800177 /**
Antonio Kantekc8114752020-03-05 21:37:39 -0800178 * List of listeners to be notified on new user activities events.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700179 * This collection should be accessed and manipulated by mHandlerThread only.
Antonio Kantekc8114752020-03-05 21:37:39 -0800180 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700181 private final List<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>();
Antonio Kantekc8114752020-03-05 21:37:39 -0800182
183 /**
Felipe Leme5528ff72020-02-10 19:05:14 -0800184 * List of lifecycle listeners by uid.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700185 * This collection should be accessed and manipulated by mHandlerThread only.
Felipe Leme5528ff72020-02-10 19:05:14 -0800186 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700187 private final SparseArray<IResultReceiver> mAppLifecycleListeners = new SparseArray<>();
Felipe Leme5528ff72020-02-10 19:05:14 -0800188
Mayank Garg7a114c82020-04-08 21:25:06 -0700189 /**
190 * User Id for the user switch in process, if any.
191 */
192 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700193 private int mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg7a114c82020-04-08 21:25:06 -0700194 /**
195 * Request Id for the user switch in process, if any.
196 */
197 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700198 private int mRequestIdForUserSwitchInProcess;
Felipe Lemee3cab982020-03-12 11:39:29 -0700199 private final int mHalTimeoutMs = CarProperties.user_hal_timeout().orElse(5_000);
200
Eric Jeongc91f9452019-08-30 15:04:21 -0700201 private final CopyOnWriteArrayList<PassengerCallback> mPassengerCallbacks =
202 new CopyOnWriteArrayList<>();
203
Mayank Garg7e1450b2020-08-07 18:15:15 -0700204 // TODO(b/163566866): Use mSwitchGuestUserBeforeSleep for new create guest request
205 private final boolean mSwitchGuestUserBeforeSleep;
206
felipeal61ce3732020-04-03 11:01:00 -0700207 @Nullable
208 @GuardedBy("mLockUser")
209 private UserInfo mInitialUser;
210
Mayank Garg587f1942020-05-06 01:41:34 -0700211 private IResultReceiver mUserSwitchUiReceiver;
212
Eric Jeongc91f9452019-08-30 15:04:21 -0700213 /** Interface for callbaks related to passenger activities. */
214 public interface PassengerCallback {
215 /** Called when passenger is started at a certain zone. */
216 void onPassengerStarted(@UserIdInt int passengerId, int zoneId);
217 /** Called when passenger is stopped. */
218 void onPassengerStopped(@UserIdInt int passengerId);
219 }
220
221 /** Interface for delegating zone-related implementation to CarOccupantZoneService. */
222 public interface ZoneUserBindingHelper {
223 /** Gets occupant zones corresponding to the occupant type. */
224 @NonNull
225 List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType);
226 /** Assigns the user to the occupant zone. */
227 boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId);
228 /** Makes the occupant zone unoccupied. */
229 boolean unassignUserFromOccupantZone(@UserIdInt int userId);
230 /** Returns whether there is a passenger display. */
231 boolean isPassengerDisplayAvailable();
232 }
233
234 private final Object mLockHelper = new Object();
235 @GuardedBy("mLockHelper")
236 private ZoneUserBindingHelper mZoneUserBindingHelper;
237
Felipe Leme58412202020-01-09 13:45:33 -0800238 public CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garg71661ea2020-04-29 01:25:03 -0700239 @NonNull CarUserManagerHelper carUserManagerHelper, @NonNull UserManager userManager,
240 @NonNull IActivityManager am, int maxRunningUsers) {
241 this(context, hal, carUserManagerHelper, userManager, am, maxRunningUsers,
Mayank Garg1bb1c382020-09-03 17:11:11 -0700242 /* initialUserSetter= */ null, /* userPreCreator= */ null);
Mayank Garg71661ea2020-04-29 01:25:03 -0700243 }
244
245 @VisibleForTesting
246 CarUserService(@NonNull Context context, @NonNull UserHalService hal,
247 @NonNull CarUserManagerHelper carUserManagerHelper, @NonNull UserManager userManager,
Mayank Gargccad8062020-08-30 15:05:10 -0700248 @NonNull IActivityManager am, int maxRunningUsers,
Mayank Garg1bb1c382020-09-03 17:11:11 -0700249 @Nullable InitialUserSetter initialUserSetter,
250 @Nullable UserPreCreator userPreCreator) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700251 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
252 Log.d(TAG_USER, "constructed");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700253 }
254 mContext = context;
Felipe Leme58412202020-01-09 13:45:33 -0800255 mHal = hal;
Eric Jeong3a793b02019-09-30 16:12:53 -0700256 mCarUserManagerHelper = carUserManagerHelper;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700257 mAm = am;
258 mMaxRunningUsers = maxRunningUsers;
Anthony Hugh9932a252019-06-12 16:19:56 -0700259 mUserManager = userManager;
Eric Jeongc91f9452019-08-30 15:04:21 -0700260 mLastPassengerId = UserHandle.USER_NULL;
Mayank Garg1bb1c382020-09-03 17:11:11 -0700261 mInitialUserSetter =
262 initialUserSetter == null ? new InitialUserSetter(context, (u) -> setInitialUser(u))
263 : initialUserSetter;
264 mUserPreCreator =
265 userPreCreator == null ? new UserPreCreator(mUserManager) : userPreCreator;
Mayank Garg7e1450b2020-08-07 18:15:15 -0700266 Resources resources = context.getResources();
267 mEnablePassengerSupport = resources.getBoolean(R.bool.enablePassengerSupport);
268 mSwitchGuestUserBeforeSleep = resources.getBoolean(
269 R.bool.config_switchGuestUserBeforeGoingSleep);
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700270 }
271
272 @Override
273 public void init() {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700274 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
275 Log.d(TAG_USER, "init");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700276 }
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700277 }
278
279 @Override
280 public void release() {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700281 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
282 Log.d(TAG_USER, "release");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700283 }
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700284 }
285
286 @Override
Eric Jeong1545f3b2019-09-16 13:56:52 -0700287 public void dump(@NonNull PrintWriter writer) {
felipeal2d0483c2019-11-02 14:07:22 -0700288 checkAtLeastOnePermission("dump()", android.Manifest.permission.DUMP);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700289 writer.println("*CarUserService*");
Felipe Leme5528ff72020-02-10 19:05:14 -0800290 String indent = " ";
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700291 handleDumpListeners(writer, indent);
Mayank Garg587f1942020-05-06 01:41:34 -0700292 writer.printf("User switch UI receiver %s\n", mUserSwitchUiReceiver);
Eric Jeongc91f9452019-08-30 15:04:21 -0700293 synchronized (mLockUser) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700294 writer.println("User0Unlocked: " + mUser0Unlocked);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700295 writer.println("BackgroundUsersToRestart: " + mBackgroundUsersToRestart);
296 writer.println("BackgroundUsersRestarted: " + mBackgroundUsersRestartedHere);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700297 }
298 writer.println("MaxRunningUsers: " + mMaxRunningUsers);
299 List<UserInfo> allDrivers = getAllDrivers();
300 int driversSize = allDrivers.size();
301 writer.println("NumberOfDrivers: " + driversSize);
302 for (int i = 0; i < driversSize; i++) {
303 int driverId = allDrivers.get(i).id;
304 writer.print(indent + "#" + i + ": id=" + driverId);
305 List<UserInfo> passengers = getPassengers(driverId);
306 int passengersSize = passengers.size();
307 writer.print(" NumberPassengers: " + passengersSize);
308 if (passengersSize > 0) {
309 writer.print(" [");
310 for (int j = 0; j < passengersSize; j++) {
311 writer.print(passengers.get(j).id);
312 if (j < passengersSize - 1) {
313 writer.print(" ");
felipeal2d0483c2019-11-02 14:07:22 -0700314 }
felipeal2d0483c2019-11-02 14:07:22 -0700315 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700316 writer.print("]");
felipeal2d0483c2019-11-02 14:07:22 -0700317 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700318 writer.println();
319 }
320 writer.printf("EnablePassengerSupport: %s\n", mEnablePassengerSupport);
321 writer.printf("User HAL timeout: %dms\n", mHalTimeoutMs);
322 writer.printf("Initial user: %s\n", mInitialUser);
felipealbf327652020-06-03 11:33:29 -0700323
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700324 writer.println("Relevant overlayable properties");
325 Resources res = mContext.getResources();
326 writer.printf("%sowner_name=%s\n", indent,
327 res.getString(com.android.internal.R.string.owner_name));
328 writer.printf("%sdefault_guest_name=%s\n", indent,
329 res.getString(R.string.default_guest_name));
felipealf7368962020-04-16 12:55:19 -0700330 writer.printf("User switch in process=%d\n", mUserIdForUserSwitchInProcess);
Mayank Garg7a114c82020-04-08 21:25:06 -0700331 writer.printf("Request Id for the user switch in process=%d\n ",
332 mRequestIdForUserSwitchInProcess);
Mayank Garga480dd92020-05-14 03:14:57 -0700333 writer.printf("System UI package name=%s\n", getSystemUiPackageName());
felipeale8c5dce2020-04-15 11:27:06 -0700334
felipealbf327652020-06-03 11:33:29 -0700335 writer.println("Relevant Global settings");
336 dumpGlobalProperty(writer, indent, CarSettings.Global.LAST_ACTIVE_USER_ID);
337 dumpGlobalProperty(writer, indent, CarSettings.Global.LAST_ACTIVE_PERSISTENT_USER_ID);
338
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700339 mInitialUserSetter.dump(writer);
felipeale8c5dce2020-04-15 11:27:06 -0700340 }
341
felipealbf327652020-06-03 11:33:29 -0700342 private void dumpGlobalProperty(PrintWriter writer, String indent, String property) {
343 String value = Settings.Global.getString(mContext.getContentResolver(), property);
344 writer.printf("%s%s=%s\n", indent, property, value);
345 }
346
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700347 private void handleDumpListeners(@NonNull PrintWriter writer, String indent) {
348 CountDownLatch latch = new CountDownLatch(1);
349 mHandler.post(() -> {
felipealde1e16d2020-06-03 13:20:48 -0700350 handleDumpServiceLifecycleListeners(writer);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700351 handleDumpAppLifecycleListeners(writer, indent);
352 latch.countDown();
353 });
354 int timeout = 5;
355 try {
356 if (!latch.await(timeout, TimeUnit.SECONDS)) {
357 writer.printf("Handler thread didn't respond in %ds when dumping listeners\n",
358 timeout);
359 }
360 } catch (InterruptedException e) {
361 Thread.currentThread().interrupt();
362 writer.println("Interrupted waiting for handler thread to dump app and user listeners");
363 }
364 }
365
felipealde1e16d2020-06-03 13:20:48 -0700366 private void handleDumpServiceLifecycleListeners(@NonNull PrintWriter writer) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700367 if (mUserLifecycleListeners.isEmpty()) {
felipealde1e16d2020-06-03 13:20:48 -0700368 writer.println("No lifecycle listeners for internal services");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700369 return;
370 }
felipealde1e16d2020-06-03 13:20:48 -0700371 int size = mUserLifecycleListeners.size();
372 writer.printf("%d lifecycle listener%s for services\n", size, size == 1 ? "" : "s");
373 String indent = " ";
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700374 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipealde1e16d2020-06-03 13:20:48 -0700375 writer.printf("%s%s\n", indent, FunctionalUtils.getLambdaName(listener));
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700376 }
377 }
378
379 private void handleDumpAppLifecycleListeners(@NonNull PrintWriter writer, String indent) {
felipealde1e16d2020-06-03 13:20:48 -0700380 int size = mAppLifecycleListeners.size();
381 if (size == 0) {
382 writer.println("No lifecycle listeners for apps");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700383 return;
384 }
felipealde1e16d2020-06-03 13:20:48 -0700385 writer.printf("%d lifecycle listener%s for apps \n", size, size == 1 ? "" : "s");
386 for (int i = 0; i < size; i++) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700387 int uid = mAppLifecycleListeners.keyAt(i);
388 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
felipealde1e16d2020-06-03 13:20:48 -0700389 writer.printf("%suid: %d\n", indent, uid);
Keun-young Parkd462a912019-02-11 08:53:42 -0800390 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700391 }
392
393 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700394 * @see ExperimentalCarUserManager.createDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700395 */
396 @Override
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700397 public AndroidFuture<UserCreationResult> createDriver(@NonNull String name, boolean admin) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700398 checkManageUsersPermission("createDriver");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000399 Objects.requireNonNull(name, "name cannot be null");
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700400
401 AndroidFuture<UserCreationResult> future = new AndroidFuture<UserCreationResult>() {
402 @Override
403 protected void onCompleted(UserCreationResult result, Throwable err) {
404 if (result == null) {
405 Log.w(TAG, "createDriver(" + name + "," + admin + ") failed: " + err);
406 } else {
407 if (result.getStatus() == UserCreationResult.STATUS_SUCCESSFUL) {
408 assignDefaultIcon(result.getUser());
409 }
410 }
411 super.onCompleted(result, err);
412 };
413 };
414 int flags = 0;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700415 if (admin) {
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700416 if (!(mUserManager.isAdminUser() || mUserManager.isSystemUser())) {
417 Log.e(TAG_USER, "Only admin users and system user can create other admins.");
418 sendUserCreationResultFailure(future, UserCreationResult.STATUS_INVALID_REQUEST);
419 return future;
420 }
421 flags = UserInfo.FLAG_ADMIN;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700422 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700423 createUser(name, UserInfo.getDefaultUserType(flags), flags, mHalTimeoutMs, future);
424 return future;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700425 }
426
427 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700428 * @see ExperimentalCarUserManager.createPassenger
Eric Jeong1545f3b2019-09-16 13:56:52 -0700429 */
430 @Override
431 @Nullable
432 public UserInfo createPassenger(@NonNull String name, @UserIdInt int driverId) {
433 checkManageUsersPermission("createPassenger");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000434 Objects.requireNonNull(name, "name cannot be null");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700435 UserInfo driver = mUserManager.getUserInfo(driverId);
436 if (driver == null) {
437 Log.w(TAG_USER, "the driver is invalid");
438 return null;
439 }
440 if (driver.isGuest()) {
441 Log.w(TAG_USER, "a guest driver cannot create a passenger");
442 return null;
443 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700444 // createPassenger doesn't use user HAL because user HAL doesn't support profile user yet.
Bookatz42fb1a62019-10-30 11:45:01 -0700445 UserInfo user = mUserManager.createProfileForUser(name,
446 UserManager.USER_TYPE_PROFILE_MANAGED, /* flags */ 0, driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700447 if (user == null) {
448 // Couldn't create user, most likely because there are too many.
449 Log.w(TAG_USER, "can't create a profile for user" + driverId);
450 return null;
451 }
452 // Passenger user should be a non-admin user.
Eric Jeong3a793b02019-09-30 16:12:53 -0700453 mCarUserManagerHelper.setDefaultNonAdminRestrictions(user, /* enable= */ true);
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700454 assignDefaultIcon(user);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700455 return user;
456 }
457
458 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700459 * @see ExperimentalCarUserManager.switchDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700460 */
461 @Override
Eric Jeong25666cf2020-05-14 15:16:27 -0700462 public void switchDriver(@UserIdInt int driverId, AndroidFuture<UserSwitchResult> receiver) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700463 checkManageUsersPermission("switchDriver");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700464 if (UserHelperLite.isHeadlessSystemUser(driverId)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700465 // System user doesn't associate with real person, can not be switched to.
466 Log.w(TAG_USER, "switching to system user in headless system user mode is not allowed");
felipealdfdf8512020-06-01 09:35:45 -0700467 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700468 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700469 }
470 int userSwitchable = mUserManager.getUserSwitchability();
471 if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) {
472 Log.w(TAG_USER, "current process is not allowed to switch user");
felipealdfdf8512020-06-01 09:35:45 -0700473 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700474 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700475 }
Eric Jeong25666cf2020-05-14 15:16:27 -0700476 switchUser(driverId, mHalTimeoutMs, receiver);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700477 }
478
479 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800480 * Returns all drivers who can occupy the driving zone. Guest users are included in the list.
481 *
482 * @return the list of {@link UserInfo} who can be a driver on the device.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700483 */
484 @Override
485 @NonNull
486 public List<UserInfo> getAllDrivers() {
felipeal2d0483c2019-11-02 14:07:22 -0700487 checkManageUsersOrDumpPermission("getAllDrivers");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700488 return getUsers((user) -> !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700489 && !user.isManagedProfile() && !user.isEphemeral());
Eric Jeong1545f3b2019-09-16 13:56:52 -0700490 }
491
492 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800493 * Returns all passengers under the given driver.
494 *
495 * @param driverId User id of a driver.
496 * @return the list of {@link UserInfo} who is a passenger under the given driver.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700497 */
498 @Override
499 @NonNull
500 public List<UserInfo> getPassengers(@UserIdInt int driverId) {
felipeal2d0483c2019-11-02 14:07:22 -0700501 checkManageUsersOrDumpPermission("getPassengers");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700502 return getUsers((user) -> {
Mayank Garg94f3eb92020-08-12 12:38:58 -0700503 return !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Eric Jeong40f8fa32020-05-12 12:23:33 -0700504 && user.isManagedProfile() && user.profileGroupId == driverId;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700505 });
506 }
507
508 /**
509 * @see CarUserManager.startPassenger
510 */
511 @Override
512 public boolean startPassenger(@UserIdInt int passengerId, int zoneId) {
513 checkManageUsersPermission("startPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700514 synchronized (mLockUser) {
515 try {
516 if (!mAm.startUserInBackgroundWithListener(passengerId, null)) {
517 Log.w(TAG_USER, "could not start passenger");
518 return false;
519 }
520 } catch (RemoteException e) {
521 // ignore
522 Log.w(TAG_USER, "error while starting passenger", e);
523 return false;
524 }
525 if (!assignUserToOccupantZone(passengerId, zoneId)) {
526 Log.w(TAG_USER, "could not assign passenger to zone");
527 return false;
528 }
529 mLastPassengerId = passengerId;
530 }
531 for (PassengerCallback callback : mPassengerCallbacks) {
532 callback.onPassengerStarted(passengerId, zoneId);
533 }
534 return true;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700535 }
536
537 /**
538 * @see CarUserManager.stopPassenger
539 */
540 @Override
541 public boolean stopPassenger(@UserIdInt int passengerId) {
542 checkManageUsersPermission("stopPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700543 return stopPassengerInternal(passengerId, true);
544 }
545
546 private boolean stopPassengerInternal(@UserIdInt int passengerId, boolean checkCurrentDriver) {
547 synchronized (mLockUser) {
548 UserInfo passenger = mUserManager.getUserInfo(passengerId);
549 if (passenger == null) {
550 Log.w(TAG_USER, "passenger " + passengerId + " doesn't exist");
551 return false;
552 }
553 if (mLastPassengerId != passengerId) {
554 Log.w(TAG_USER, "passenger " + passengerId + " hasn't been started");
555 return true;
556 }
557 if (checkCurrentDriver) {
558 int currentUser = ActivityManager.getCurrentUser();
559 if (passenger.profileGroupId != currentUser) {
560 Log.w(TAG_USER, "passenger " + passengerId
561 + " is not a profile of the current user");
562 return false;
563 }
564 }
565 // Passenger is a profile, so cannot be stopped through activity manager.
566 // Instead, activities started by the passenger are stopped and the passenger is
567 // unassigned from the zone.
568 stopAllTasks(passengerId);
569 if (!unassignUserFromOccupantZone(passengerId)) {
570 Log.w(TAG_USER, "could not unassign user from occupant zone");
571 return false;
572 }
573 mLastPassengerId = UserHandle.USER_NULL;
574 }
575 for (PassengerCallback callback : mPassengerCallbacks) {
576 callback.onPassengerStopped(passengerId);
577 }
578 return true;
579 }
580
581 private void stopAllTasks(@UserIdInt int userId) {
582 try {
583 for (StackInfo info : mAm.getAllStackInfos()) {
584 for (int i = 0; i < info.taskIds.length; i++) {
585 if (info.taskUserIds[i] == userId) {
586 int taskId = info.taskIds[i];
587 if (!mAm.removeTask(taskId)) {
588 Log.w(TAG_USER, "could not remove task " + taskId);
589 }
590 }
591 }
592 }
593 } catch (RemoteException e) {
594 Log.e(TAG_USER, "could not get stack info", e);
595 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700596 }
597
Felipe Leme5528ff72020-02-10 19:05:14 -0800598 @Override
599 public void setLifecycleListenerForUid(IResultReceiver listener) {
600 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700601 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800602 checkInteractAcrossUsersPermission("setLifecycleListenerForUid" + uid);
603
604 try {
605 listener.asBinder().linkToDeath(() -> onListenerDeath(uid), 0);
606 } catch (RemoteException e) {
607 Log.wtf(TAG_USER, "Cannot listen to death of " + uid);
608 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700609 mHandler.post(() -> mAppLifecycleListeners.append(uid, listener));
Felipe Leme5528ff72020-02-10 19:05:14 -0800610 }
611
612 private void onListenerDeath(int uid) {
613 Log.i(TAG_USER, "Removing listeners for uid " + uid + " on binder death");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700614 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800615 }
616
617 @Override
618 public void resetLifecycleListenerForUid() {
619 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700620 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_RESET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800621 checkInteractAcrossUsersPermission("resetLifecycleListenerForUid-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700622 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800623 }
624
Felipe Lemee3cab982020-03-12 11:39:29 -0700625 /**
felipeal61ce3732020-04-03 11:01:00 -0700626 * Gets the initial foreground user after the device boots or resumes from suspension.
627 *
628 * <p>When the OEM supports the User HAL, the initial user won't be available until the HAL
629 * returns the initial value to {@code CarService} - if HAL takes too long or times out, this
630 * method returns {@code null}.
631 *
632 * <p>If the HAL eventually times out, {@code CarService} will fallback to its default behavior
633 * (like switching to the last active user), and this method will return the result of such
634 * operation.
635 *
636 * <p>Notice that if {@code CarService} crashes, subsequent calls to this method will return
637 * {@code null}.
638 *
639 * @hide
640 */
641 @Nullable
642 public UserInfo getInitialUser() {
643 checkInteractAcrossUsersPermission("getInitialUser");
644 synchronized (mLockUser) {
645 return mInitialUser;
646 }
647 }
648
felipeal61ce3732020-04-03 11:01:00 -0700649 /**
650 * Sets the initial foreground user after the device boots or resumes from suspension.
651 */
652 public void setInitialUser(@Nullable UserInfo user) {
felipeal312416a2020-04-14 12:28:24 -0700653 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_INITIAL_USER,
654 user == null ? UserHandle.USER_NULL : user.id);
felipeal61ce3732020-04-03 11:01:00 -0700655 synchronized (mLockUser) {
656 mInitialUser = user;
657 }
658 if (user == null) {
659 // This mean InitialUserSetter failed and could not fallback, so the initial user was
660 // not switched (and most likely is SYSTEM_USER).
661 // TODO(b/153104378): should we set it to ActivityManager.getCurrentUser() instead?
662 Log.wtf(TAG_USER, "Initial user set to null");
663 }
664 }
665
Mayank Garg7e1450b2020-08-07 18:15:15 -0700666 private void initResumeReplaceGuest() {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700667 int currentUserId = ActivityManager.getCurrentUser();
668 UserInfo currentUser = mUserManager.getUserInfo(currentUserId);
669
670 if (!mInitialUserSetter.canReplaceGuestUser(currentUser)) return; // Not a guest
671
672 InitialUserInfo info =
673 new InitialUserSetter.Builder(InitialUserSetter.TYPE_REPLACE_GUEST).build();
674
675 mInitialUserSetter.set(info);
676 }
677
678 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700679 * Calls to switch user at the power suspend.
Mayank Garg7e1450b2020-08-07 18:15:15 -0700680 *
681 * <p><b>Note:</b> Should be used only by {@link CarPowerManagementService}
682 *
Mayank Garg7e1450b2020-08-07 18:15:15 -0700683 */
Mayank Garg0baf88a2020-08-30 21:57:36 -0700684 public void onSuspend() {
Mayank Garg7e1450b2020-08-07 18:15:15 -0700685 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
Mayank Garg0baf88a2020-08-30 21:57:36 -0700686 Log.d(TAG_USER, "onSuspend called.");
Mayank Garg7e1450b2020-08-07 18:15:15 -0700687 }
688
Mayank Garg0baf88a2020-08-30 21:57:36 -0700689 if (mSwitchGuestUserBeforeSleep) {
690 initResumeReplaceGuest();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700691 }
Mayank Garg1bb1c382020-09-03 17:11:11 -0700692
693 preCreateUsers();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700694 }
695
696 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700697 * Calls to switch user at the power resume.
698 *
699 * <p>
700 * <b>Note:</b> Should be used only by {@link CarPowerManagementService}
701 *
702 */
703 public void onResume() {
704 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
705 Log.d(TAG_USER, "onResume called.");
706 }
707
708 initBootUser(InitialUserInfoRequestType.RESUME);
709 }
710
711 /**
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700712 * Calls to start user at the android startup.
Mayank Garg70732a82020-08-05 20:17:47 -0700713 */
714 public void initBootUser() {
715 int requestType = getInitialUserInfoRequestType();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700716 initBootUser(requestType);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700717 }
718
Mayank Garg7e1450b2020-08-07 18:15:15 -0700719 private void initBootUser(int requestType) {
720 boolean replaceGuest =
721 requestType == InitialUserInfoRequestType.RESUME && !mSwitchGuestUserBeforeSleep;
Mayank Garg70732a82020-08-05 20:17:47 -0700722 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ, requestType,
723 mHalTimeoutMs);
724 checkManageUsersPermission("startInitialUser");
725
726 if (!isUserHalSupported()) {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700727 fallbackToDefaultInitialUserBehavior(/* userLocales= */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700728 return;
729 }
730
731 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
732 mHal.getInitialUserInfo(requestType, mHalTimeoutMs, usersInfo, (status, resp) -> {
733 if (resp != null) {
734 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP,
735 status, resp.action, resp.userToSwitchOrCreate.userId,
736 resp.userToSwitchOrCreate.flags, resp.userNameToCreate, resp.userLocales);
737
738 String userLocales = resp.userLocales;
739 InitialUserInfo info;
740 switch (resp.action) {
741 case InitialUserInfoResponseAction.SWITCH:
742 int userId = resp.userToSwitchOrCreate.userId;
743 if (userId <= 0) {
744 Log.w(TAG, "invalid (or missing) user id sent by HAL: " + userId);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700745 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700746 break;
747 }
748 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_SWITCH)
749 .setUserLocales(userLocales)
750 .setSwitchUserId(userId)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700751 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700752 .build();
753 mInitialUserSetter.set(info);
754 break;
755
756 case InitialUserInfoResponseAction.CREATE:
757 int halFlags = resp.userToSwitchOrCreate.flags;
758 String userName = resp.userNameToCreate;
759 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_CREATE)
760 .setUserLocales(userLocales)
761 .setNewUserName(userName)
762 .setNewUserFlags(halFlags)
763 .build();
764 mInitialUserSetter.set(info);
765 break;
766
767 case InitialUserInfoResponseAction.DEFAULT:
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700768 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700769 break;
770 default:
771 Log.w(TAG_USER, "invalid response action on " + resp);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700772 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700773 break;
774
775 }
776 } else {
777 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP, status);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700778 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700779 }
780 });
781 }
782
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700783 private void fallbackToDefaultInitialUserBehavior(String userLocales, boolean replaceGuest) {
Mayank Garg70732a82020-08-05 20:17:47 -0700784 InitialUserInfo info = new InitialUserSetter.Builder(
785 InitialUserSetter.TYPE_DEFAULT_BEHAVIOR)
786 .setUserLocales(userLocales)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700787 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700788 .build();
789 mInitialUserSetter.set(info);
790 }
791
792 @VisibleForTesting
793 int getInitialUserInfoRequestType() {
794 if (!mCarUserManagerHelper.hasInitialUser()) {
795 return InitialUserInfoRequestType.FIRST_BOOT;
796 }
797 if (mContext.getPackageManager().isDeviceUpgrading()) {
798 return InitialUserInfoRequestType.FIRST_BOOT_AFTER_OTA;
799 }
800 return InitialUserInfoRequestType.COLD_BOOT;
801 }
802
803 /**
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700804 * Calls the {@link UserHalService} and {@link IActivityManager} for user switch.
805 *
806 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700807 * When everything works well, the workflow is:
808 * <ol>
809 * <li> {@link UserHalService} is called for HAL user switch with ANDROID_SWITCH request
810 * type, current user id, target user id, and a callback.
811 * <li> HAL called back with SUCCESS.
812 * <li> {@link IActivityManager} is called for Android user switch.
813 * <li> Receiver would receive {@code STATUS_SUCCESSFUL}.
814 * <li> Once user is unlocked, {@link UserHalService} is again called with ANDROID_POST_SWITCH
815 * request type, current user id, and target user id. In this case, the current and target
816 * user IDs would be same.
817 * <ol/>
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700818 *
819 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700820 * Corner cases:
821 * <ul>
822 * <li> If target user is already the current user, no user switch is performed and receiver
Mayank Gargef1b9332020-06-11 17:36:56 -0700823 * would receive {@code STATUS_OK_USER_ALREADY_IN_FOREGROUND} right away.
Mayank Gargb08f6772020-05-01 18:06:48 -0700824 * <li> If HAL user switch call fails, no Android user switch. Receiver would receive
825 * {@code STATUS_HAL_INTERNAL_FAILURE}.
826 * <li> If HAL user switch call is successful, but android user switch call fails,
827 * {@link UserHalService} is again called with request type POST_SWITCH, current user id, and
828 * target user id, but in this case the current and target user IDs would be different.
829 * <li> If another user switch request for the same target user is received while previous
830 * request is in process, receiver would receive
831 * {@code STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO} for the new request right away.
832 * <li> If a user switch request is received while another user switch request for different
833 * target user is in process, the previous request would be abandoned and new request will be
834 * processed. No POST_SWITCH would be sent for the previous request.
835 * <ul/>
Mayank Garg59f22192020-03-27 00:51:45 -0700836 *
Mayank Garge19c2922020-03-30 18:05:53 -0700837 * @param targetUserId - target user Id
Mayank Garg59f22192020-03-27 00:51:45 -0700838 * @param timeoutMs - timeout for HAL to wait
839 * @param receiver - receiver for the results
840 */
Mayank Garge19c2922020-03-30 18:05:53 -0700841 @Override
842 public void switchUser(@UserIdInt int targetUserId, int timeoutMs,
felipeale5bf0322020-04-16 15:10:57 -0700843 @NonNull AndroidFuture<UserSwitchResult> receiver) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700844 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_REQ, targetUserId, timeoutMs);
Mayank Garg59f22192020-03-27 00:51:45 -0700845 checkManageUsersPermission("switchUser");
Mayank Garge19c2922020-03-30 18:05:53 -0700846 Objects.requireNonNull(receiver);
847 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
felipealf7368962020-04-16 12:55:19 -0700848 Preconditions.checkArgument(targetUser != null, "Target user doesn't exist");
Mayank Garg7a114c82020-04-08 21:25:06 -0700849
felipealf7368962020-04-16 12:55:19 -0700850 int currentUser = ActivityManager.getCurrentUser();
851 if (currentUser == targetUserId) {
Mayank Garg0e239142020-04-14 19:16:31 -0700852 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
853 Log.d(TAG_USER, "Current user is same as requested target user: " + targetUserId);
854 }
Mayank Gargef1b9332020-06-11 17:36:56 -0700855 int resultStatus = UserSwitchResult.STATUS_OK_USER_ALREADY_IN_FOREGROUND;
felipealdfdf8512020-06-01 09:35:45 -0700856 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg0e239142020-04-14 19:16:31 -0700857 return;
858 }
859
Mayank Garg9ed099e2020-06-04 16:05:20 -0700860 // If User Hal is not supported, just android user switch.
861 if (!isUserHalSupported()) {
862 try {
863 if (mAm.switchUser(targetUserId)) {
864 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_SUCCESSFUL);
865 return;
866 }
867 } catch (RemoteException e) {
868 // ignore
869 Log.w(TAG_USER,
870 "error while switching user " + targetUser.toFullString(), e);
871 }
872 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_ANDROID_FAILURE);
873 return;
874 }
875
Mayank Garg7a114c82020-04-08 21:25:06 -0700876 synchronized (mLockUser) {
felipealf7368962020-04-16 12:55:19 -0700877 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
878 Log.d(TAG_USER, "switchUser(" + targetUserId + "): currentuser=" + currentUser
879 + ", mUserIdForUserSwitchInProcess=" + mUserIdForUserSwitchInProcess);
880 }
881
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700882 // If there is another request for the same target user, return another request in
883 // process, else {@link mUserIdForUserSwitchInProcess} is updated and {@link
884 // mRequestIdForUserSwitchInProcess} is reset. It is possible that there may be another
885 // user switch request in process for different target user, but that request is now
886 // ignored.
felipealf7368962020-04-16 12:55:19 -0700887 if (mUserIdForUserSwitchInProcess == targetUserId) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700888 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
889 Log.d(TAG_USER,
890 "Another user switch request in process for the requested target user: "
891 + targetUserId);
892 }
893
894 int resultStatus = UserSwitchResult.STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO;
felipealdfdf8512020-06-01 09:35:45 -0700895 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg7a114c82020-04-08 21:25:06 -0700896 return;
897 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700898 else {
899 mUserIdForUserSwitchInProcess = targetUserId;
900 mRequestIdForUserSwitchInProcess = 0;
901 }
Mayank Garg7a114c82020-04-08 21:25:06 -0700902 }
903
felipealdfdf8512020-06-01 09:35:45 -0700904 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -0700905 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
906
907 mHal.switchUser(request, timeoutMs, (status, resp) -> {
felipealf7368962020-04-16 12:55:19 -0700908 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
909 Log.d(TAG, "switch response: status="
910 + UserHalHelper.halCallbackStatusToString(status) + ", resp=" + resp);
911 }
912
felipeale5bf0322020-04-16 15:10:57 -0700913 int resultStatus = UserSwitchResult.STATUS_HAL_INTERNAL_FAILURE;
felipealf7368962020-04-16 12:55:19 -0700914
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700915 synchronized (mLockUser) {
916 if (status != HalCallback.STATUS_OK) {
917 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, status);
918 Log.w(TAG, "invalid callback status ("
919 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
920 + resp);
felipealdfdf8512020-06-01 09:35:45 -0700921 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700922 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
923 return;
924 }
felipealf7368962020-04-16 12:55:19 -0700925
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700926 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, status, resp.status,
927 resp.errorMessage);
928
929 if (mUserIdForUserSwitchInProcess != targetUserId) {
930 // Another user switch request received while HAL responded. No need to process
931 // this request further
932 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
933 Log.d(TAG_USER, "Another user switch received while HAL responsed. Request "
934 + "abondoned for : " + targetUserId + ". Current user in process: "
935 + mUserIdForUserSwitchInProcess);
felipealf7368962020-04-16 12:55:19 -0700936 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700937 resultStatus =
938 UserSwitchResult.STATUS_TARGET_USER_ABANDONED_DUE_TO_A_NEW_REQUEST;
felipealdfdf8512020-06-01 09:35:45 -0700939 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700940 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
941 return;
942 }
943
944 switch (resp.status) {
945 case SwitchUserStatus.SUCCESS:
946 boolean switched;
947 try {
948 switched = mAm.switchUser(targetUserId);
949 if (switched) {
Mayank Garg587f1942020-05-06 01:41:34 -0700950 sendUserSwitchUiCallback(targetUserId);
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700951 resultStatus = UserSwitchResult.STATUS_SUCCESSFUL;
952 mRequestIdForUserSwitchInProcess = resp.requestId;
953 } else {
954 resultStatus = UserSwitchResult.STATUS_ANDROID_FAILURE;
955 postSwitchHalResponse(resp.requestId, targetUserId);
956 }
957 } catch (RemoteException e) {
958 // ignore
959 Log.w(TAG_USER,
960 "error while switching user " + targetUser.toFullString(), e);
961 }
962 break;
963 case SwitchUserStatus.FAILURE:
964 // HAL failed to switch user
965 resultStatus = UserSwitchResult.STATUS_HAL_FAILURE;
966 break;
felipealdfdf8512020-06-01 09:35:45 -0700967 default:
968 // Shouldn't happen because UserHalService validates the status
969 Log.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700970 }
971
972 if (mRequestIdForUserSwitchInProcess == 0) {
973 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
974 }
Mayank Garg59f22192020-03-27 00:51:45 -0700975 }
felipealdfdf8512020-06-01 09:35:45 -0700976 sendUserSwitchResult(receiver, resultStatus, resp.errorMessage);
Mayank Garg59f22192020-03-27 00:51:45 -0700977 });
978 }
979
Mayank Garga55c3092020-05-28 03:19:24 -0700980 @Override
981 public UserRemovalResult removeUser(@UserIdInt int userId) {
982 checkManageUsersPermission("removeUser");
983 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_REQ, userId);
984 // If the requested user is the current user, return error.
985 if (ActivityManager.getCurrentUser() == userId) {
986 return logAndGetResults(userId,
987 UserRemovalResult.STATUS_TARGET_USER_IS_CURRENT_USER);
988 }
989
990 // If requested user is the only admin user, return error.
991 UserInfo userInfo = mUserManager.getUserInfo(userId);
992 if (userInfo == null) {
993 return logAndGetResults(userId, UserRemovalResult.STATUS_USER_DOES_NOT_EXIST);
994 }
995
996 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
997 new android.hardware.automotive.vehicle.V2_0.UserInfo();
998 halUser.userId = userInfo.id;
999 halUser.flags = UserHalHelper.convertFlags(userInfo);
1000 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1001
1002 // Do not delete last admin user.
1003 if (UserHalHelper.isAdmin(halUser.flags)) {
1004 int size = usersInfo.existingUsers.size();
1005 int totalAdminUsers = 0;
1006 for (int i = 0; i < size; i++) {
1007 if (UserHalHelper.isAdmin(usersInfo.existingUsers.get(i).flags)) {
1008 totalAdminUsers++;
1009 }
1010 }
1011 if (totalAdminUsers == 1) {
1012 return logAndGetResults(userId,
1013 UserRemovalResult.STATUS_TARGET_USER_IS_LAST_ADMIN_USER);
1014 }
1015 }
1016
1017 // First remove user from android and then remove from HAL because HAL remove user is one
1018 // way call.
1019 if (!mUserManager.removeUser(userId)) {
1020 return logAndGetResults(userId, UserRemovalResult.STATUS_ANDROID_FAILURE);
1021 }
1022
Mayank Garg9ed099e2020-06-04 16:05:20 -07001023 if (isUserHalSupported()) {
1024 RemoveUserRequest request = new RemoveUserRequest();
1025 request.removedUserInfo = halUser;
Mayank Garg4adef862020-06-16 18:12:28 -07001026 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Garg9ed099e2020-06-04 16:05:20 -07001027 mHal.removeUser(request);
1028 }
1029
Mayank Garga55c3092020-05-28 03:19:24 -07001030 return logAndGetResults(userId, UserRemovalResult.STATUS_SUCCESSFUL);
1031 }
1032
1033 private UserRemovalResult logAndGetResults(@UserIdInt int userId,
1034 @UserRemovalResult.Status int result) {
1035 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_RESP, userId, result);
1036 return new UserRemovalResult(result);
1037 }
1038
Mayank Garg587f1942020-05-06 01:41:34 -07001039 private void sendUserSwitchUiCallback(@UserIdInt int targetUserId) {
1040 if (mUserSwitchUiReceiver == null) {
1041 Log.w(TAG_USER, "No User switch UI receiver.");
1042 return;
1043 }
1044
felipealdfdf8512020-06-01 09:35:45 -07001045 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_UI_REQ, targetUserId);
Mayank Garg587f1942020-05-06 01:41:34 -07001046 try {
Mayank Garg587f1942020-05-06 01:41:34 -07001047 mUserSwitchUiReceiver.send(targetUserId, null);
1048 } catch (RemoteException e) {
1049 Log.e(TAG_USER, "Error calling user switch UI receiver.", e);
1050 }
1051 }
1052
felipeal5e3ede42020-04-23 18:04:07 -07001053 @Override
felipealdfdf8512020-06-01 09:35:45 -07001054 public void createUser(@Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
1055 int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver) {
1056 Objects.requireNonNull(userType, "user type cannot be null");
1057 Objects.requireNonNull(receiver, "receiver cannot be null");
1058 checkManageOrCreateUsersPermission("createUser");
Mayank Garg94f3eb92020-08-12 12:38:58 -07001059 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_REQ,
1060 UserHelperLite.safeName(name), userType, flags, timeoutMs);
felipealdfdf8512020-06-01 09:35:45 -07001061
1062 UserInfo newUser;
1063 try {
1064 newUser = mUserManager.createUser(name, userType, flags);
1065 if (newUser == null) {
1066 Log.w(TAG, "um.createUser() returned null for user of type " + userType
1067 + " and flags " + UserInfo.flagsToString(flags));
1068 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1069 return;
1070 }
1071 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1072 Log.d(TAG, "Created user: " + newUser.toFullString());
1073 }
1074 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_CREATED, newUser.id,
Mayank Garg94f3eb92020-08-12 12:38:58 -07001075 UserHelperLite.safeName(newUser.name), newUser.userType, newUser.flags);
felipealdfdf8512020-06-01 09:35:45 -07001076 } catch (RuntimeException e) {
1077 Log.e(TAG_USER, "Error creating user of type " + userType + " and flags"
1078 + UserInfo.flagsToString(flags), e);
1079 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1080 return;
1081 }
1082
Mayank Garg9ed099e2020-06-04 16:05:20 -07001083 if (!isUserHalSupported()) {
1084 sendUserCreationResult(receiver, UserCreationResult.STATUS_SUCCESSFUL, newUser, null);
1085 return;
1086 }
1087
felipealdfdf8512020-06-01 09:35:45 -07001088 CreateUserRequest request = new CreateUserRequest();
1089 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1090 if (!TextUtils.isEmpty(name)) {
1091 request.newUserName = name;
1092 }
1093 request.newUserInfo.userId = newUser.id;
1094 request.newUserInfo.flags = UserHalHelper.convertFlags(newUser);
1095 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1096 Log.d(TAG, "Create user request: " + request);
1097 }
1098
1099 try {
1100 mHal.createUser(request, timeoutMs, (status, resp) -> {
1101 int resultStatus = UserCreationResult.STATUS_HAL_INTERNAL_FAILURE;
1102 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1103 Log.d(TAG, "createUserResponse: status="
1104 + UserHalHelper.halCallbackStatusToString(status) + ", resp=" + resp);
1105 }
1106 UserInfo user = null; // user returned in the result
1107 if (status != HalCallback.STATUS_OK) {
1108 Log.w(TAG, "invalid callback status ("
1109 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1110 + resp);
1111 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1112 resultStatus, resp.errorMessage);
1113 removeUser(newUser, "HAL call failed with "
1114 + UserHalHelper.halCallbackStatusToString(status));
1115 sendUserCreationResult(receiver, resultStatus, user, /* errorMsg= */ null);
1116 return;
1117 }
1118
1119 switch (resp.status) {
1120 case CreateUserStatus.SUCCESS:
1121 resultStatus = UserCreationResult.STATUS_SUCCESSFUL;
1122 user = newUser;
1123 break;
1124 case CreateUserStatus.FAILURE:
1125 // HAL failed to switch user
1126 resultStatus = UserCreationResult.STATUS_HAL_FAILURE;
1127 break;
1128 default:
1129 // Shouldn't happen because UserHalService validates the status
1130 Log.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
1131 }
1132 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1133 resultStatus, resp.errorMessage);
1134 if (user == null) {
1135 removeUser(newUser, "HAL returned "
1136 + UserCreationResult.statusToString(resultStatus));
1137 }
1138 sendUserCreationResult(receiver, resultStatus, user, resp.errorMessage);
1139 });
1140 } catch (Exception e) {
1141 Log.w(TAG, "mHal.createUser(" + request + ") failed", e);
1142 removeUser(newUser, "mHal.createUser() failed");
1143 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_HAL_INTERNAL_FAILURE);
1144 }
1145 }
1146
1147 private void removeUser(@NonNull UserInfo user, @NonNull String reason) {
1148 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_REMOVED, user.id, reason);
1149 try {
1150 if (!mUserManager.removeUser(user.id)) {
1151 Log.w(TAG, "Failed to remove user " + user.toFullString());
1152 }
1153 } catch (Exception e) {
1154 Log.e(TAG, "Failed to remove user " + user.toFullString(), e);
1155 }
1156 }
1157
1158 @Override
felipeal159a2a42020-05-08 10:32:11 -07001159 public UserIdentificationAssociationResponse getUserIdentificationAssociation(int[] types) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001160 if (!isUserHalUserAssociationSupported()) {
1161 return UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED);
1162 }
1163
felipeal5e3ede42020-04-23 18:04:07 -07001164 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
1165 checkManageUsersPermission("getUserIdentificationAssociation");
1166
1167 int uid = getCallingUid();
1168 int userId = UserHandle.getUserId(uid);
1169 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_REQ, uid, userId);
1170
1171 UserIdentificationGetRequest request = new UserIdentificationGetRequest();
1172 request.userInfo.userId = userId;
1173 request.userInfo.flags = getHalUserInfoFlags(userId);
1174
1175 request.numberAssociationTypes = types.length;
1176 for (int i = 0; i < types.length; i++) {
1177 request.associationTypes.add(types[i]);
1178 }
1179
1180 UserIdentificationResponse halResponse = mHal.getUserAssociation(request);
1181 if (halResponse == null) {
1182 Log.w(TAG, "getUserIdentificationAssociation(): HAL returned null for "
1183 + Arrays.toString(types));
felipeal159a2a42020-05-08 10:32:11 -07001184 return UserIdentificationAssociationResponse.forFailure();
felipeal5e3ede42020-04-23 18:04:07 -07001185 }
1186
1187 int[] values = new int[halResponse.associations.size()];
1188 for (int i = 0; i < values.length; i++) {
1189 values[i] = halResponse.associations.get(i).value;
1190 }
1191 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_RESP, values.length);
1192
felipeal159a2a42020-05-08 10:32:11 -07001193 return UserIdentificationAssociationResponse.forSuccess(values, halResponse.errorMessage);
1194 }
1195
1196 @Override
1197 public void setUserIdentificationAssociation(int timeoutMs, int[] types, int[] values,
1198 AndroidFuture<UserIdentificationAssociationResponse> result) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001199 if (!isUserHalUserAssociationSupported()) {
1200 result.complete(
1201 UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED));
1202 return;
1203 }
1204
felipeal159a2a42020-05-08 10:32:11 -07001205 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
1206 Preconditions.checkArgument(!ArrayUtils.isEmpty(values), "must have at least one value");
1207 if (types.length != values.length) {
1208 throw new IllegalArgumentException("types (" + Arrays.toString(types) + ") and values ("
1209 + Arrays.toString(values) + ") should have the same length");
1210 }
1211 checkManageUsersPermission("setUserIdentificationAssociation");
1212
1213 int uid = getCallingUid();
1214 int userId = UserHandle.getUserId(uid);
1215 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_REQ, uid, userId, types.length);
1216
1217 UserIdentificationSetRequest request = new UserIdentificationSetRequest();
1218 request.userInfo.userId = userId;
1219 request.userInfo.flags = getHalUserInfoFlags(userId);
1220
1221 request.numberAssociations = types.length;
1222 for (int i = 0; i < types.length; i++) {
1223 UserIdentificationSetAssociation association = new UserIdentificationSetAssociation();
1224 association.type = types[i];
1225 association.value = values[i];
1226 request.associations.add(association);
1227 }
1228
1229 mHal.setUserAssociation(timeoutMs, request, (status, resp) -> {
1230 if (status != HalCallback.STATUS_OK) {
1231 Log.w(TAG, "setUserIdentificationAssociation(): invalid callback status ("
1232 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1233 + resp);
1234 if (resp == null || TextUtils.isEmpty(resp.errorMessage)) {
1235 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0);
1236 result.complete(UserIdentificationAssociationResponse.forFailure());
1237 return;
1238 }
1239 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0,
1240 resp.errorMessage);
1241 result.complete(
1242 UserIdentificationAssociationResponse.forFailure(resp.errorMessage));
1243 return;
1244 }
1245 int respSize = resp.associations.size();
1246 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, respSize,
1247 resp.errorMessage);
1248
1249 int[] responseTypes = new int[respSize];
1250 for (int i = 0; i < respSize; i++) {
1251 responseTypes[i] = resp.associations.get(i).value;
1252 }
1253 UserIdentificationAssociationResponse response = UserIdentificationAssociationResponse
1254 .forSuccess(responseTypes, resp.errorMessage);
1255 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1256 Log.d(TAG, "setUserIdentificationAssociation(): resp= " + resp
1257 + ", converted=" + response);
1258 }
1259 result.complete(response);
1260 });
felipeal5e3ede42020-04-23 18:04:07 -07001261 }
1262
1263 /**
1264 * Gets the User HAL flags for the given user.
1265 *
1266 * @throws IllegalArgumentException if the user does not exist.
1267 */
1268 private int getHalUserInfoFlags(@UserIdInt int userId) {
1269 UserInfo user = mUserManager.getUserInfo(userId);
1270 Preconditions.checkArgument(user != null, "no user for id %d", userId);
1271 return UserHalHelper.convertFlags(user);
1272 }
1273
Mayank Garg0e239142020-04-14 19:16:31 -07001274 private void sendResult(@NonNull IResultReceiver receiver, int resultCode,
1275 @Nullable Bundle resultData) {
1276 try {
1277 receiver.send(resultCode, resultData);
1278 } catch (RemoteException e) {
1279 // ignore
1280 Log.w(TAG_USER, "error while sending results", e);
1281 }
1282 }
1283
felipealdfdf8512020-06-01 09:35:45 -07001284 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
felipeale5bf0322020-04-16 15:10:57 -07001285 @UserSwitchResult.Status int status) {
felipealdfdf8512020-06-01 09:35:45 -07001286 sendUserSwitchResult(receiver, status, /* errorMessage= */ null);
felipeale5bf0322020-04-16 15:10:57 -07001287 }
1288
felipealdfdf8512020-06-01 09:35:45 -07001289 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
felipeale5bf0322020-04-16 15:10:57 -07001290 @UserSwitchResult.Status int status, @Nullable String errorMessage) {
1291 receiver.complete(new UserSwitchResult(status, errorMessage));
1292 }
1293
felipealdfdf8512020-06-01 09:35:45 -07001294 private void sendUserCreationResultFailure(@NonNull AndroidFuture<UserCreationResult> receiver,
1295 @UserCreationResult.Status int status) {
1296 sendUserCreationResult(receiver, status, /* user= */ null, /* errorMessage= */ null);
1297 }
1298
1299 private void sendUserCreationResult(@NonNull AndroidFuture<UserCreationResult> receiver,
1300 @UserCreationResult.Status int status, @NonNull UserInfo user,
1301 @Nullable String errorMessage) {
1302 if (TextUtils.isEmpty(errorMessage)) {
1303 errorMessage = null;
1304 }
1305 receiver.complete(new UserCreationResult(status, user, errorMessage));
1306 }
1307
Mayank Garg6307fe42020-04-15 23:09:03 -07001308 /**
1309 * Calls activity manager for user switch.
1310 *
1311 * <p><b>NOTE</b> This method is meant to be called just by UserHalService.
1312 *
1313 * @param requestId for the user switch request
1314 * @param targetUserId of the target user
1315 *
1316 * @hide
1317 */
1318 public void switchAndroidUserFromHal(int requestId, @UserIdInt int targetUserId) {
1319 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_FROM_HAL_REQ, requestId,
1320 targetUserId);
1321 Log.i(TAG_USER, "User hal requested a user switch. Target user id " + targetUserId);
1322
1323 try {
1324 boolean result = mAm.switchUser(targetUserId);
1325 if (result) {
1326 updateUserSwitchInProcess(requestId, targetUserId);
1327 } else {
1328 postSwitchHalResponse(requestId, targetUserId);
1329 }
1330 } catch (RemoteException e) {
1331 // ignore
1332 Log.w(TAG_USER, "error while switching user " + targetUserId, e);
1333 }
1334 }
1335
1336 private void updateUserSwitchInProcess(int requestId, @UserIdInt int targetUserId) {
1337 synchronized (mLockUser) {
1338 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
1339 // Some other user switch is in process.
1340 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1341 Log.d(TAG_USER, "User switch for user: " + mUserIdForUserSwitchInProcess
1342 + " is in process. Abandoning it as a new user switch is requested"
1343 + " for the target user: " + targetUserId);
1344 }
1345 }
1346 mUserIdForUserSwitchInProcess = targetUserId;
1347 mRequestIdForUserSwitchInProcess = requestId;
1348 }
1349 }
Mayank Garg9ed099e2020-06-04 16:05:20 -07001350
Mayank Garg7a114c82020-04-08 21:25:06 -07001351 private void postSwitchHalResponse(int requestId, @UserIdInt int targetUserId) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001352 if (!isUserHalSupported()) return;
1353
felipealdfdf8512020-06-01 09:35:45 -07001354 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -07001355 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_POST_SWITCH_USER_REQ, requestId,
1356 targetUserId, usersInfo.currentUser.userId);
1357 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
1358 request.requestId = requestId;
1359 mHal.postSwitchResponse(request);
1360 }
1361
1362 private SwitchUserRequest createUserSwitchRequest(@UserIdInt int targetUserId,
1363 @NonNull UsersInfo usersInfo) {
1364 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
Mayank Garg7a114c82020-04-08 21:25:06 -07001365 android.hardware.automotive.vehicle.V2_0.UserInfo halTargetUser =
1366 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1367 halTargetUser.userId = targetUser.id;
1368 halTargetUser.flags = UserHalHelper.convertFlags(targetUser);
Mayank Gargeb37d092020-06-02 14:37:57 -07001369 SwitchUserRequest request = new SwitchUserRequest();
1370 request.targetUser = halTargetUser;
1371 request.usersInfo = usersInfo;
1372 return request;
Mayank Garg7a114c82020-04-08 21:25:06 -07001373 }
1374
Mayank Garg59f22192020-03-27 00:51:45 -07001375 /**
Felipe Lemee3cab982020-03-12 11:39:29 -07001376 * Checks if the User HAL is supported.
1377 */
1378 public boolean isUserHalSupported() {
1379 return mHal.isSupported();
1380 }
1381
Mayank Garg587f1942020-05-06 01:41:34 -07001382 /**
Mayank Garg9ed099e2020-06-04 16:05:20 -07001383 * Checks if the User HAL user association is supported.
1384 */
1385 @Override
1386 public boolean isUserHalUserAssociationSupported() {
1387 return mHal.isUserAssociationSupported();
1388 }
1389
1390 /**
Mayank Garg587f1942020-05-06 01:41:34 -07001391 * Sets a callback which is invoked before user switch.
1392 *
1393 * <p>
1394 * This method should only be called by the Car System UI. The purpose of this call is to notify
1395 * Car System UI to show the user switch UI before the user switch.
1396 */
1397 @Override
1398 public void setUserSwitchUiCallback(@NonNull IResultReceiver receiver) {
Yan Zhu67a383e2020-05-11 20:46:24 -07001399 checkManageUsersPermission("setUserSwitchUiCallback");
Mayank Garga480dd92020-05-14 03:14:57 -07001400
1401 // Confirm that caller is system UI.
1402 String systemUiPackageName = getSystemUiPackageName();
1403 if (systemUiPackageName == null) {
1404 throw new IllegalStateException("System UI package not found.");
1405 }
1406
1407 try {
1408 int systemUiUid = mContext
1409 .createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0).getPackageManager()
1410 .getPackageUid(systemUiPackageName, PackageManager.MATCH_SYSTEM_ONLY);
1411 int callerUid = Binder.getCallingUid();
1412 if (systemUiUid != callerUid) {
1413 throw new SecurityException("Invalid caller. Only" + systemUiPackageName
1414 + " is allowed to make this call");
1415 }
1416 } catch (NameNotFoundException e) {
1417 throw new IllegalStateException("Package " + systemUiPackageName + " not found.");
1418 }
1419
Mayank Garg587f1942020-05-06 01:41:34 -07001420 mUserSwitchUiReceiver = receiver;
1421 }
1422
Mayank Garga480dd92020-05-14 03:14:57 -07001423 // TODO(157082995): This information can be taken from
1424 // PackageManageInternalImpl.getSystemUiServiceComponent
1425 @Nullable
1426 private String getSystemUiPackageName() {
1427 try {
1428 ComponentName componentName = ComponentName.unflattenFromString(mContext.getResources()
1429 .getString(com.android.internal.R.string.config_systemUIServiceComponent));
1430 return componentName.getPackageName();
1431 } catch (RuntimeException e) {
1432 Log.w(TAG_USER, "error while getting system UI package name.", e);
1433 return null;
1434 }
1435 }
1436
Keun young Park13a7a822019-04-04 15:53:08 -07001437 private void updateDefaultUserRestriction() {
1438 // We want to set restrictions on system and guest users only once. These are persisted
1439 // onto disk, so it's sufficient to do it once + we minimize the number of disk writes.
1440 if (Settings.Global.getInt(mContext.getContentResolver(),
Eric Jeong1545f3b2019-09-16 13:56:52 -07001441 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, /* default= */ 0) != 0) {
1442 return;
Keun young Park13a7a822019-04-04 15:53:08 -07001443 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001444 // Only apply the system user restrictions if the system user is headless.
1445 if (UserManager.isHeadlessSystemUserMode()) {
1446 setSystemUserRestrictions();
1447 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001448 Settings.Global.putInt(mContext.getContentResolver(),
1449 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, 1);
Keun young Park13a7a822019-04-04 15:53:08 -07001450 }
1451
Eric Jeong1545f3b2019-09-16 13:56:52 -07001452 private boolean isPersistentUser(@UserIdInt int userId) {
Anthony Hugh9932a252019-06-12 16:19:56 -07001453 return !mUserManager.getUserInfo(userId).isEphemeral();
1454 }
1455
Antonio Kantekc8114752020-03-05 21:37:39 -08001456 /**
Antonio Kantekc8114752020-03-05 21:37:39 -08001457 * Adds a new {@link UserLifecycleListener} to listen to user activity events.
1458 */
1459 public void addUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1460 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001461 mHandler.post(() -> mUserLifecycleListeners.add(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001462 }
1463
1464 /**
1465 * Removes previously added {@link UserLifecycleListener}.
1466 */
1467 public void removeUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1468 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001469 mHandler.post(() -> mUserLifecycleListeners.remove(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001470 }
1471
Eric Jeongc91f9452019-08-30 15:04:21 -07001472 /** Adds callback to listen to passenger activity events. */
1473 public void addPassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001474 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001475 mPassengerCallbacks.add(callback);
1476 }
1477
1478 /** Removes previously added callback to listen passenger events. */
1479 public void removePassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001480 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001481 mPassengerCallbacks.remove(callback);
1482 }
1483
1484 /** Sets the implementation of ZoneUserBindingHelper. */
1485 public void setZoneUserBindingHelper(@NonNull ZoneUserBindingHelper helper) {
1486 synchronized (mLockHelper) {
1487 mZoneUserBindingHelper = helper;
1488 }
1489 }
1490
felipeal98900c82020-04-09 09:05:02 -07001491 private void onUserUnlocked(@UserIdInt int userId) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001492 ArrayList<Runnable> tasks = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001493 synchronized (mLockUser) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001494 sendPostSwitchToHalLocked(userId);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001495 if (userId == UserHandle.USER_SYSTEM) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001496 if (!mUser0Unlocked) { // user 0, unlocked, do this only once
1497 updateDefaultUserRestriction();
1498 tasks = new ArrayList<>(mUser0UnlockTasks);
1499 mUser0UnlockTasks.clear();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001500 mUser0Unlocked = true;
Keun young Parkf3523cd2019-04-08 10:09:17 -07001501 }
1502 } else { // none user0
Eric Jeong1545f3b2019-09-16 13:56:52 -07001503 Integer user = userId;
1504 if (isPersistentUser(userId)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001505 // current foreground user should stay in top priority.
Anthony Hughfbb67762019-10-15 12:54:54 -07001506 if (userId == ActivityManager.getCurrentUser()) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001507 mBackgroundUsersToRestart.remove(user);
1508 mBackgroundUsersToRestart.add(0, user);
1509 }
1510 // -1 for user 0
1511 if (mBackgroundUsersToRestart.size() > (mMaxRunningUsers - 1)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001512 int userToDrop = mBackgroundUsersToRestart.get(
Keun young Parkf3523cd2019-04-08 10:09:17 -07001513 mBackgroundUsersToRestart.size() - 1);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001514 Log.i(TAG_USER, "New user unlocked:" + userId
Keun young Parkf3523cd2019-04-08 10:09:17 -07001515 + ", dropping least recently user from restart list:" + userToDrop);
1516 // Drop the least recently used user.
1517 mBackgroundUsersToRestart.remove(mBackgroundUsersToRestart.size() - 1);
1518 }
1519 }
Keun-young Parkd462a912019-02-11 08:53:42 -08001520 }
1521 }
1522 if (tasks != null && tasks.size() > 0) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001523 Log.d(TAG_USER, "User0 unlocked, run queued tasks:" + tasks.size());
Keun-young Parkd462a912019-02-11 08:53:42 -08001524 for (Runnable r : tasks) {
1525 r.run();
1526 }
1527 }
1528 }
1529
1530 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001531 * Starts all background users that were active in system.
1532 *
Keun young Parkfb656372019-03-12 18:37:55 -07001533 * @return list of background users started successfully.
1534 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001535 @NonNull
Keun young Parkfb656372019-03-12 18:37:55 -07001536 public ArrayList<Integer> startAllBackgroundUsers() {
1537 ArrayList<Integer> users;
Eric Jeongc91f9452019-08-30 15:04:21 -07001538 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001539 users = new ArrayList<>(mBackgroundUsersToRestart);
1540 mBackgroundUsersRestartedHere.clear();
1541 mBackgroundUsersRestartedHere.addAll(mBackgroundUsersToRestart);
Keun young Parkfb656372019-03-12 18:37:55 -07001542 }
1543 ArrayList<Integer> startedUsers = new ArrayList<>();
1544 for (Integer user : users) {
Anthony Hughfbb67762019-10-15 12:54:54 -07001545 if (user == ActivityManager.getCurrentUser()) {
Keun young Parkfb656372019-03-12 18:37:55 -07001546 continue;
1547 }
1548 try {
1549 if (mAm.startUserInBackground(user)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001550 if (mUserManager.isUserUnlockingOrUnlocked(user)) {
1551 // already unlocked / unlocking. No need to unlock.
Keun young Parkfb656372019-03-12 18:37:55 -07001552 startedUsers.add(user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001553 } else if (mAm.unlockUser(user, null, null, null)) {
1554 startedUsers.add(user);
1555 } else { // started but cannot unlock
Eric Jeong1545f3b2019-09-16 13:56:52 -07001556 Log.w(TAG_USER, "Background user started but cannot be unlocked:" + user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001557 if (mUserManager.isUserRunning(user)) {
1558 // add to started list so that it can be stopped later.
1559 startedUsers.add(user);
1560 }
Keun young Parkfb656372019-03-12 18:37:55 -07001561 }
1562 }
1563 } catch (RemoteException e) {
1564 // ignore
Eric Jeong1545f3b2019-09-16 13:56:52 -07001565 Log.w(TAG_USER, "error while starting user in background", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001566 }
1567 }
Keun young Parkf3523cd2019-04-08 10:09:17 -07001568 // Keep only users that were re-started in mBackgroundUsersRestartedHere
Eric Jeongc91f9452019-08-30 15:04:21 -07001569 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001570 ArrayList<Integer> usersToRemove = new ArrayList<>();
1571 for (Integer user : mBackgroundUsersToRestart) {
1572 if (!startedUsers.contains(user)) {
1573 usersToRemove.add(user);
1574 }
1575 }
1576 mBackgroundUsersRestartedHere.removeAll(usersToRemove);
1577 }
Keun young Parkfb656372019-03-12 18:37:55 -07001578 return startedUsers;
1579 }
1580
1581 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001582 * Stops all background users that were active in system.
1583 *
1584 * @return whether stopping succeeds.
Keun young Parkfb656372019-03-12 18:37:55 -07001585 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001586 public boolean stopBackgroundUser(@UserIdInt int userId) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001587 if (userId == UserHandle.USER_SYSTEM) {
1588 return false;
1589 }
Anthony Hughfbb67762019-10-15 12:54:54 -07001590 if (userId == ActivityManager.getCurrentUser()) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001591 Log.i(TAG_USER, "stopBackgroundUser, already a FG user:" + userId);
Keun young Parkfb656372019-03-12 18:37:55 -07001592 return false;
1593 }
1594 try {
Keun young Parked9e6282019-09-19 17:38:26 -07001595 int r = mAm.stopUserWithDelayedLocking(userId, true, null);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001596 if (r == ActivityManager.USER_OP_SUCCESS) {
Eric Jeongc91f9452019-08-30 15:04:21 -07001597 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001598 Integer user = userId;
1599 mBackgroundUsersRestartedHere.remove(user);
1600 }
1601 } else if (r == ActivityManager.USER_OP_IS_CURRENT) {
1602 return false;
1603 } else {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001604 Log.i(TAG_USER, "stopBackgroundUser failed, user:" + userId + " err:" + r);
Keun young Parkfb656372019-03-12 18:37:55 -07001605 return false;
1606 }
1607 } catch (RemoteException e) {
1608 // ignore
Eric Jeong1545f3b2019-09-16 13:56:52 -07001609 Log.w(TAG_USER, "error while stopping user", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001610 }
1611 return true;
1612 }
1613
1614 /**
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001615 * Notifies all registered {@link UserLifecycleListener} with the event passed as argument.
Pavel Maltsev17e81832019-04-04 14:38:41 -07001616 */
Mayank Gargccad8062020-08-30 15:05:10 -07001617 public void onUserLifecycleEvent(@UserLifecycleEventType int eventType,
felipeale8c5dce2020-04-15 11:27:06 -07001618 @UserIdInt int fromUserId, @UserIdInt int toUserId) {
1619 int userId = toUserId;
felipeal98900c82020-04-09 09:05:02 -07001620
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001621 // Handle special cases first...
felipeal98900c82020-04-09 09:05:02 -07001622 if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_SWITCHING) {
Mayank Garge5de0f92020-04-23 21:38:38 -07001623 onUserSwitching(fromUserId, toUserId);
felipeal98900c82020-04-09 09:05:02 -07001624 } else if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
1625 onUserUnlocked(userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001626 }
1627
felipeale8c5dce2020-04-15 11:27:06 -07001628 // ...then notify listeners.
Yan Zhue7921522020-04-16 15:59:25 -07001629 UserLifecycleEvent event = new UserLifecycleEvent(eventType, fromUserId, userId);
felipeale8c5dce2020-04-15 11:27:06 -07001630
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001631 mHandler.post(() -> {
1632 handleNotifyServiceUserLifecycleListeners(event);
1633 handleNotifyAppUserLifecycleListeners(event);
1634 });
felipeale8c5dce2020-04-15 11:27:06 -07001635 }
1636
Mayank Garg7a114c82020-04-08 21:25:06 -07001637 private void sendPostSwitchToHalLocked(@UserIdInt int userId) {
felipealf7368962020-04-16 12:55:19 -07001638 if (mUserIdForUserSwitchInProcess == UserHandle.USER_NULL
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001639 || mUserIdForUserSwitchInProcess != userId
1640 || mRequestIdForUserSwitchInProcess == 0) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001641 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1642 Log.d(TAG_USER, "No user switch request Id. No android post switch sent.");
1643 }
1644 return;
1645 }
felipealf7368962020-04-16 12:55:19 -07001646 postSwitchHalResponse(mRequestIdForUserSwitchInProcess, mUserIdForUserSwitchInProcess);
1647 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001648 mRequestIdForUserSwitchInProcess = 0;
Mayank Garg7a114c82020-04-08 21:25:06 -07001649 }
1650
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001651 private void handleNotifyAppUserLifecycleListeners(UserLifecycleEvent event) {
1652 int listenersSize = mAppLifecycleListeners.size();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001653 if (listenersSize == 0) {
felipeal2a84d512020-04-06 18:52:15 -07001654 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1655 Log.d(TAG_USER, "No app listener to be notified of " + event);
1656 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001657 return;
1658 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001659 // Must use a different TimingsTraceLog because it's another thread
1660 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1661 Log.d(TAG_USER, "Notifying " + listenersSize + " app listeners of " + event);
1662 }
felipeal2a84d512020-04-06 18:52:15 -07001663 int userId = event.getUserId();
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001664 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
felipealde1e16d2020-06-03 13:20:48 -07001665 int eventType = event.getEventType();
1666 t.traceBegin("notify-app-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001667 for (int i = 0; i < listenersSize; i++) {
1668 int uid = mAppLifecycleListeners.keyAt(i);
felipealde1e16d2020-06-03 13:20:48 -07001669
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001670 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
1671 Bundle data = new Bundle();
felipealde1e16d2020-06-03 13:20:48 -07001672 data.putInt(CarUserManager.BUNDLE_PARAM_ACTION, eventType);
Yan Zhue7921522020-04-16 15:59:25 -07001673
felipealde1e16d2020-06-03 13:20:48 -07001674 int fromUserId = event.getPreviousUserId();
1675 if (fromUserId != UserHandle.USER_NULL) {
1676 data.putInt(CarUserManager.BUNDLE_PARAM_PREVIOUS_USER_ID, fromUserId);
Yan Zhue7921522020-04-16 15:59:25 -07001677 }
1678
felipeal2a84d512020-04-06 18:52:15 -07001679 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001680 Log.d(TAG_USER, "Notifying listener for uid " + uid);
felipeal2a84d512020-04-06 18:52:15 -07001681 }
felipealde1e16d2020-06-03 13:20:48 -07001682 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_APP_LIFECYCLE_LISTENER,
1683 uid, eventType, fromUserId, userId);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001684 try {
felipealde1e16d2020-06-03 13:20:48 -07001685 t.traceBegin("notify-app-listener-uid-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001686 listener.send(userId, data);
1687 } catch (RemoteException e) {
1688 Log.e(TAG_USER, "Error calling lifecycle listener", e);
1689 } finally {
1690 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001691 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001692 }
1693 t.traceEnd(); // notify-app-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001694 }
1695
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001696 private void handleNotifyServiceUserLifecycleListeners(UserLifecycleEvent event) {
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001697 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
1698 if (mUserLifecycleListeners.isEmpty()) {
felipeal2a84d512020-04-06 18:52:15 -07001699 Log.w(TAG_USER, "Not notifying internal UserLifecycleListeners");
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001700 return;
felipeal2a84d512020-04-06 18:52:15 -07001701 } else if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1702 Log.d(TAG_USER, "Notifying " + mUserLifecycleListeners.size() + " service listeners of "
1703 + event);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001704 }
felipeal2a84d512020-04-06 18:52:15 -07001705
felipealde1e16d2020-06-03 13:20:48 -07001706 int userId = event.getUserId();
1707 int eventType = event.getEventType();
1708 t.traceBegin("notify-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001709 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipeal2a84d512020-04-06 18:52:15 -07001710 String listenerName = FunctionalUtils.getLambdaName(listener);
felipealde1e16d2020-06-03 13:20:48 -07001711 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_INTERNAL_LIFECYCLE_LISTENER,
1712 listenerName, eventType, event.getPreviousUserId(), userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001713 try {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001714 t.traceBegin("notify-listener-" + listenerName);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001715 listener.onEvent(event);
1716 } catch (RuntimeException e) {
1717 Log.e(TAG_USER,
felipeal2a84d512020-04-06 18:52:15 -07001718 "Exception raised when invoking onEvent for " + listenerName, e);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001719 } finally {
1720 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001721 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001722 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001723 t.traceEnd(); // notify-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001724 }
1725
Mayank Garge5de0f92020-04-23 21:38:38 -07001726 private void onUserSwitching(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
Eric Jeong40f8fa32020-05-12 12:23:33 -07001727 Log.i(TAG_USER, "onUserSwitching() callback for user " + toUserId);
Felipe Leme5528ff72020-02-10 19:05:14 -08001728 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
Mayank Garge5de0f92020-04-23 21:38:38 -07001729 t.traceBegin("onUserSwitching-" + toUserId);
Felipe Leme5528ff72020-02-10 19:05:14 -08001730
Mayank Garge5de0f92020-04-23 21:38:38 -07001731 // Switch HAL users if user switch is not requested by CarUserService
1732 notifyHalLegacySwitch(fromUserId, toUserId);
1733
felipealbf327652020-06-03 11:33:29 -07001734 mCarUserManagerHelper.setLastActiveUser(toUserId);
1735
Eric Jeongc91f9452019-08-30 15:04:21 -07001736 if (mLastPassengerId != UserHandle.USER_NULL) {
1737 stopPassengerInternal(mLastPassengerId, false);
1738 }
1739 if (mEnablePassengerSupport && isPassengerDisplayAvailable()) {
1740 setupPassengerUser();
Mayank Garge5de0f92020-04-23 21:38:38 -07001741 startFirstPassenger(toUserId);
Eric Jeongc91f9452019-08-30 15:04:21 -07001742 }
felipeal98900c82020-04-09 09:05:02 -07001743 t.traceEnd();
Pavel Maltsev17e81832019-04-04 14:38:41 -07001744 }
1745
Mayank Garge5de0f92020-04-23 21:38:38 -07001746 private void notifyHalLegacySwitch(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
1747 synchronized (mLockUser) {
felipeal7d12ee22020-06-05 09:30:19 -07001748 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
1749 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1750 Log.d(TAG, "notifyHalLegacySwitch(" + fromUserId + ", " + toUserId
1751 + "): not needed, normal switch for " + mUserIdForUserSwitchInProcess);
1752 }
1753 return;
1754 }
Mayank Garge5de0f92020-04-23 21:38:38 -07001755 }
1756
Mayank Garg9ed099e2020-06-04 16:05:20 -07001757 if (!isUserHalSupported()) return;
1758
Mayank Garge5de0f92020-04-23 21:38:38 -07001759 // switch HAL user
felipeal7d12ee22020-06-05 09:30:19 -07001760 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager, fromUserId);
Mayank Gargeb37d092020-06-02 14:37:57 -07001761 SwitchUserRequest request = createUserSwitchRequest(toUserId, usersInfo);
1762 mHal.legacyUserSwitch(request);
Mayank Garge5de0f92020-04-23 21:38:38 -07001763 }
1764
Pavel Maltsev17e81832019-04-04 14:38:41 -07001765 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001766 * Runs the given runnable when user 0 is unlocked. If user 0 is already unlocked, it is
Keun-young Parkd462a912019-02-11 08:53:42 -08001767 * run inside this call.
Eric Jeong1545f3b2019-09-16 13:56:52 -07001768 *
Keun-young Parkd462a912019-02-11 08:53:42 -08001769 * @param r Runnable to run.
1770 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001771 public void runOnUser0Unlock(@NonNull Runnable r) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001772 Objects.requireNonNull(r, "runnable cannot be null");
Keun-young Parkd462a912019-02-11 08:53:42 -08001773 boolean runNow = false;
Eric Jeongc91f9452019-08-30 15:04:21 -07001774 synchronized (mLockUser) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001775 if (mUser0Unlocked) {
1776 runNow = true;
1777 } else {
1778 mUser0UnlockTasks.add(r);
1779 }
1780 }
1781 if (runNow) {
1782 r.run();
1783 }
1784 }
1785
Keun young Parkf3523cd2019-04-08 10:09:17 -07001786 @VisibleForTesting
Eric Jeong1545f3b2019-09-16 13:56:52 -07001787 @NonNull
1788 ArrayList<Integer> getBackgroundUsersToRestart() {
1789 ArrayList<Integer> backgroundUsersToRestart = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001790 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001791 backgroundUsersToRestart = new ArrayList<>(mBackgroundUsersToRestart);
1792 }
1793 return backgroundUsersToRestart;
1794 }
1795
Ying Zheng1ab32b62018-06-26 12:47:26 -07001796 private void setSystemUserRestrictions() {
Ying Zheng1ab32b62018-06-26 12:47:26 -07001797 // Disable Location service for system user.
1798 LocationManager locationManager =
1799 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Anthony Hugh04ee04f2019-12-17 16:11:33 -08001800 locationManager.setLocationEnabledForUser(
1801 /* enabled= */ false, UserHandle.of(UserHandle.USER_SYSTEM));
Ying Zheng1ab32b62018-06-26 12:47:26 -07001802 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001803
1804 /**
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001805 * Assigns a default icon to a user according to the user's id.
1806 *
1807 * @param userInfo User whose avatar is set to default icon.
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001808 */
Eric Jeongb2dc6ff2020-06-05 17:00:26 -07001809 private void assignDefaultIcon(UserInfo userInfo) {
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001810 int idForIcon = userInfo.isGuest() ? UserHandle.USER_NULL : userInfo.id;
1811 Bitmap bitmap = UserIcons.convertToBitmap(
1812 UserIcons.getDefaultUserIcon(mContext.getResources(), idForIcon, false));
1813 mUserManager.setUserIcon(userInfo.id, bitmap);
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001814 }
1815
Eric Jeong1545f3b2019-09-16 13:56:52 -07001816 private interface UserFilter {
1817 boolean isEligibleUser(UserInfo user);
1818 }
1819
1820 /** Returns all users who are matched by the given filter. */
1821 private List<UserInfo> getUsers(UserFilter filter) {
Colin Cross0df71ea2020-08-27 04:12:26 +00001822 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeong1545f3b2019-09-16 13:56:52 -07001823
1824 for (Iterator<UserInfo> iterator = users.iterator(); iterator.hasNext(); ) {
1825 UserInfo user = iterator.next();
1826 if (!filter.isEligibleUser(user)) {
1827 iterator.remove();
1828 }
1829 }
1830 return users;
1831 }
1832
1833 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001834 * Enforces that apps which have the
1835 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
1836 * can make certain calls to the CarUserManager.
1837 *
1838 * @param message used as message if SecurityException is thrown.
1839 * @throws SecurityException if the caller is not system or root.
1840 */
1841 private static void checkManageUsersPermission(String message) {
felipeal2d0483c2019-11-02 14:07:22 -07001842 checkAtLeastOnePermission(message, android.Manifest.permission.MANAGE_USERS);
1843 }
1844
felipealdfdf8512020-06-01 09:35:45 -07001845 private static void checkManageOrCreateUsersPermission(String message) {
1846 checkAtLeastOnePermission(message,
1847 android.Manifest.permission.MANAGE_USERS,
1848 android.Manifest.permission.CREATE_USERS);
1849 }
1850
felipeal2d0483c2019-11-02 14:07:22 -07001851 private static void checkManageUsersOrDumpPermission(String message) {
1852 checkAtLeastOnePermission(message,
1853 android.Manifest.permission.MANAGE_USERS,
1854 android.Manifest.permission.DUMP);
1855 }
1856
Felipe Leme5528ff72020-02-10 19:05:14 -08001857 private void checkInteractAcrossUsersPermission(String message) {
1858 checkAtLeastOnePermission(message, android.Manifest.permission.INTERACT_ACROSS_USERS,
1859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
1860 }
1861
felipeal2d0483c2019-11-02 14:07:22 -07001862 private static void checkAtLeastOnePermission(String message, String...permissions) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001863 int callingUid = Binder.getCallingUid();
felipeal2d0483c2019-11-02 14:07:22 -07001864 if (!hasAtLeastOnePermissionGranted(callingUid, permissions)) {
1865 throw new SecurityException("You need one of " + Arrays.toString(permissions)
Felipe Leme5528ff72020-02-10 19:05:14 -08001866 + " to: " + message);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001867 }
1868 }
1869
felipeal2d0483c2019-11-02 14:07:22 -07001870 private static boolean hasAtLeastOnePermissionGranted(int uid, String... permissions) {
1871 for (String permission : permissions) {
1872 if (ActivityManager.checkComponentPermission(permission, uid, /* owningUid = */-1,
1873 /* exported = */ true)
1874 == android.content.pm.PackageManager.PERMISSION_GRANTED) {
1875 return true;
1876 }
1877 }
1878 return false;
Eric Jeong1545f3b2019-09-16 13:56:52 -07001879 }
Eric Jeongc91f9452019-08-30 15:04:21 -07001880
1881 private int getNumberOfManagedProfiles(@UserIdInt int userId) {
Colin Cross0df71ea2020-08-27 04:12:26 +00001882 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeongc91f9452019-08-30 15:04:21 -07001883 // Count all users that are managed profiles of the given user.
1884 int managedProfilesCount = 0;
1885 for (UserInfo user : users) {
1886 if (user.isManagedProfile() && user.profileGroupId == userId) {
1887 managedProfilesCount++;
1888 }
1889 }
1890 return managedProfilesCount;
1891 }
1892
1893 /**
1894 * Starts the first passenger of the given driver and assigns the passenger to the front
1895 * passenger zone.
1896 *
1897 * @param driverId User id of the driver.
1898 * @return whether it succeeds.
1899 */
1900 private boolean startFirstPassenger(@UserIdInt int driverId) {
1901 int zoneId = getAvailablePassengerZone();
1902 if (zoneId == OccupantZoneInfo.INVALID_ZONE_ID) {
1903 Log.w(TAG_USER, "passenger occupant zone is not found");
1904 return false;
1905 }
1906 List<UserInfo> passengers = getPassengers(driverId);
1907 if (passengers.size() < 1) {
1908 Log.w(TAG_USER, "passenger is not found");
1909 return false;
1910 }
1911 // Only one passenger is supported. If there are two or more passengers, the first passenger
1912 // is chosen.
1913 int passengerId = passengers.get(0).id;
1914 if (!startPassenger(passengerId, zoneId)) {
1915 Log.w(TAG_USER, "cannot start passenger " + passengerId);
1916 return false;
1917 }
1918 return true;
1919 }
1920
1921 private int getAvailablePassengerZone() {
1922 int[] occupantTypes = new int[] {CarOccupantZoneManager.OCCUPANT_TYPE_FRONT_PASSENGER,
1923 CarOccupantZoneManager.OCCUPANT_TYPE_REAR_PASSENGER};
1924 for (int occupantType : occupantTypes) {
1925 int zoneId = getZoneId(occupantType);
1926 if (zoneId != OccupantZoneInfo.INVALID_ZONE_ID) {
1927 return zoneId;
1928 }
1929 }
1930 return OccupantZoneInfo.INVALID_ZONE_ID;
1931 }
1932
1933 /**
1934 * Creates a new passenger user when there is no passenger user.
1935 */
1936 private void setupPassengerUser() {
1937 int currentUser = ActivityManager.getCurrentUser();
1938 int profileCount = getNumberOfManagedProfiles(currentUser);
1939 if (profileCount > 0) {
1940 Log.w(TAG_USER, "max profile of user" + currentUser
1941 + " is exceeded: current profile count is " + profileCount);
1942 return;
1943 }
1944 // TODO(b/140311342): Use resource string for the default passenger name.
1945 UserInfo passenger = createPassenger("Passenger", currentUser);
1946 if (passenger == null) {
1947 // Couldn't create user, most likely because there are too many.
1948 Log.w(TAG_USER, "cannot create a passenger user");
1949 return;
1950 }
1951 }
1952
1953 @NonNull
1954 private List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType) {
1955 ZoneUserBindingHelper helper = null;
1956 synchronized (mLockHelper) {
1957 if (mZoneUserBindingHelper == null) {
1958 Log.w(TAG_USER, "implementation is not delegated");
1959 return new ArrayList<OccupantZoneInfo>();
1960 }
1961 helper = mZoneUserBindingHelper;
1962 }
1963 return helper.getOccupantZones(occupantType);
1964 }
1965
1966 private boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId) {
1967 ZoneUserBindingHelper helper = null;
1968 synchronized (mLockHelper) {
1969 if (mZoneUserBindingHelper == null) {
1970 Log.w(TAG_USER, "implementation is not delegated");
1971 return false;
1972 }
1973 helper = mZoneUserBindingHelper;
1974 }
1975 return helper.assignUserToOccupantZone(userId, zoneId);
1976 }
1977
1978 private boolean unassignUserFromOccupantZone(@UserIdInt int userId) {
1979 ZoneUserBindingHelper helper = null;
1980 synchronized (mLockHelper) {
1981 if (mZoneUserBindingHelper == null) {
1982 Log.w(TAG_USER, "implementation is not delegated");
1983 return false;
1984 }
1985 helper = mZoneUserBindingHelper;
1986 }
1987 return helper.unassignUserFromOccupantZone(userId);
1988 }
1989
1990 private boolean isPassengerDisplayAvailable() {
1991 ZoneUserBindingHelper helper = null;
1992 synchronized (mLockHelper) {
1993 if (mZoneUserBindingHelper == null) {
1994 Log.w(TAG_USER, "implementation is not delegated");
1995 return false;
1996 }
1997 helper = mZoneUserBindingHelper;
1998 }
1999 return helper.isPassengerDisplayAvailable();
2000 }
2001
2002 /**
2003 * Gets the zone id of the given occupant type. If there are two or more zones, the first found
2004 * zone is returned.
2005 *
2006 * @param occupantType The type of an occupant.
2007 * @return The zone id of the given occupant type. {@link OccupantZoneInfo.INVALID_ZONE_ID},
2008 * if not found.
2009 */
2010 private int getZoneId(@OccupantTypeEnum int occupantType) {
2011 List<OccupantZoneInfo> zoneInfos = getOccupantZones(occupantType);
2012 return (zoneInfos.size() > 0) ? zoneInfos.get(0).zoneId : OccupantZoneInfo.INVALID_ZONE_ID;
2013 }
Mayank Garg9732d602020-08-09 21:02:40 -07002014
2015 /**
2016 * Manages the required number of pre-created users.
2017 */
2018 public void preCreateUsers() {
2019 mUserPreCreator.managePreCreatedUsers();
2020 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002021}