blob: 36f97f703de7f8c3aa242f676f27eeb8c3bcc5f1 [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
Felipe Leme17799202020-09-03 12:55:53 -070019import static android.Manifest.permission.CREATE_USERS;
20import static android.Manifest.permission.MANAGE_USERS;
Felipe Leme5d5ab142020-10-27 13:49:10 -070021import static android.car.drivingstate.CarUxRestrictions.UX_RESTRICTIONS_NO_SETUP;
Felipe Leme17799202020-09-03 12:55:53 -070022
Felipe Leme55236722020-10-16 16:54:32 -070023import static com.android.car.PermissionHelper.checkHasAtLeastOnePermissionGranted;
24import static com.android.car.PermissionHelper.checkHasDumpPermissionGranted;
Eric Jeong1545f3b2019-09-16 13:56:52 -070025
26import android.annotation.NonNull;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070027import android.annotation.Nullable;
Eric Jeong1545f3b2019-09-16 13:56:52 -070028import android.annotation.UserIdInt;
Keun young Parkfb656372019-03-12 18:37:55 -070029import android.app.ActivityManager;
Louis Chang3bf2f202020-08-18 13:04:28 +080030import android.app.ActivityTaskManager.RootTaskInfo;
Keun young Parkfb656372019-03-12 18:37:55 -070031import android.app.IActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070032import android.car.CarOccupantZoneManager;
33import android.car.CarOccupantZoneManager.OccupantTypeEnum;
34import android.car.CarOccupantZoneManager.OccupantZoneInfo;
Eric Jeong1545f3b2019-09-16 13:56:52 -070035import android.car.ICarUserService;
Felipe Leme5d5ab142020-10-27 13:49:10 -070036import android.car.drivingstate.CarUxRestrictions;
Felipe Leme56ef9ad2020-11-05 18:39:03 -080037import android.car.drivingstate.ICarUxRestrictionsChangeListener;
jovanak24470652018-09-11 17:51:57 -070038import android.car.settings.CarSettings;
Felipe Leme5528ff72020-02-10 19:05:14 -080039import android.car.user.CarUserManager;
Mayank Garg3f566582020-10-02 22:10:16 -070040import android.car.user.CarUserManager.UserIdentificationAssociationSetValue;
41import android.car.user.CarUserManager.UserIdentificationAssociationType;
Antonio Kantekc8114752020-03-05 21:37:39 -080042import android.car.user.CarUserManager.UserLifecycleEvent;
43import android.car.user.CarUserManager.UserLifecycleListener;
felipealdfdf8512020-06-01 09:35:45 -070044import android.car.user.UserCreationResult;
felipeal159a2a42020-05-08 10:32:11 -070045import android.car.user.UserIdentificationAssociationResponse;
Mayank Garga55c3092020-05-28 03:19:24 -070046import android.car.user.UserRemovalResult;
felipeale5bf0322020-04-16 15:10:57 -070047import android.car.user.UserSwitchResult;
felipeal19e3d732020-03-18 12:07:32 -070048import android.car.userlib.HalCallback;
49import android.car.userlib.UserHalHelper;
Mayank Garge90a4082020-09-30 12:57:34 -070050import android.car.userlib.UserHelper;
Mayank Garga480dd92020-05-14 03:14:57 -070051import android.content.ComponentName;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070052import android.content.Context;
Mayank Garga480dd92020-05-14 03:14:57 -070053import android.content.pm.PackageManager;
54import android.content.pm.PackageManager.NameNotFoundException;
Eric Jeong1545f3b2019-09-16 13:56:52 -070055import android.content.pm.UserInfo;
felipealdfdf8512020-06-01 09:35:45 -070056import android.content.pm.UserInfo.UserInfoFlag;
Felipe Leme315a53b2020-03-12 10:51:04 -070057import android.content.res.Resources;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070058import android.graphics.Bitmap;
felipealdfdf8512020-06-01 09:35:45 -070059import android.hardware.automotive.vehicle.V2_0.CreateUserRequest;
60import android.hardware.automotive.vehicle.V2_0.CreateUserStatus;
Mayank Garg70732a82020-08-05 20:17:47 -070061import android.hardware.automotive.vehicle.V2_0.InitialUserInfoRequestType;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080062import android.hardware.automotive.vehicle.V2_0.InitialUserInfoResponseAction;
Mayank Garga55c3092020-05-28 03:19:24 -070063import android.hardware.automotive.vehicle.V2_0.RemoveUserRequest;
Mayank Gargeb37d092020-06-02 14:37:57 -070064import android.hardware.automotive.vehicle.V2_0.SwitchUserRequest;
Mayank Garg59f22192020-03-27 00:51:45 -070065import android.hardware.automotive.vehicle.V2_0.SwitchUserStatus;
felipeal5e3ede42020-04-23 18:04:07 -070066import android.hardware.automotive.vehicle.V2_0.UserIdentificationGetRequest;
67import android.hardware.automotive.vehicle.V2_0.UserIdentificationResponse;
felipeal159a2a42020-05-08 10:32:11 -070068import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetAssociation;
69import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetRequest;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080070import android.hardware.automotive.vehicle.V2_0.UsersInfo;
Ying Zheng1ab32b62018-06-26 12:47:26 -070071import android.location.LocationManager;
Eric Jeong1545f3b2019-09-16 13:56:52 -070072import android.os.Binder;
Felipe Leme5528ff72020-02-10 19:05:14 -080073import android.os.Bundle;
Antonio Kantek7236a5b2020-04-06 19:53:55 -070074import android.os.Handler;
75import android.os.HandlerThread;
Felipe Leme17799202020-09-03 12:55:53 -070076import android.os.Process;
Keun young Parkfb656372019-03-12 18:37:55 -070077import android.os.RemoteException;
Mayank Garg31e73042020-01-23 00:10:38 -080078import android.os.Trace;
Ying Zhengcf20f442018-06-22 16:54:51 -070079import android.os.UserHandle;
Ying Zheng8f90edb2018-06-13 12:42:31 -070080import android.os.UserManager;
jovanak24470652018-09-11 17:51:57 -070081import android.provider.Settings;
Felipe Lemee3cab982020-03-12 11:39:29 -070082import android.sysprop.CarProperties;
felipeal159a2a42020-05-08 10:32:11 -070083import android.text.TextUtils;
felipeal312416a2020-04-14 12:28:24 -070084import android.util.EventLog;
Felipe Leme176a5fd2021-01-20 15:48:33 -080085import android.util.IndentingPrintWriter;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070086import android.util.Log;
Eric Jeongf75d4132020-12-21 13:48:23 -080087import android.util.Slog;
Felipe Leme5528ff72020-02-10 19:05:14 -080088import android.util.SparseArray;
Felipe Leme6b34fc32020-10-26 15:49:17 -070089import android.util.SparseBooleanArray;
Mayank Garg31e73042020-01-23 00:10:38 -080090import android.util.TimingsTraceLog;
Felipe Leme56ef9ad2020-11-05 18:39:03 -080091import android.view.Display;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070092
Mayank Garg72c71d22021-02-03 23:54:45 -080093import com.android.car.CarLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070094import com.android.car.CarServiceBase;
Keun young Parkb241d022020-04-20 20:31:34 -070095import com.android.car.CarServiceUtils;
Felipe Leme5d5ab142020-10-27 13:49:10 -070096import com.android.car.CarUxRestrictionsManagerService;
Eric Jeongc91f9452019-08-30 15:04:21 -070097import com.android.car.R;
Felipe Leme58412202020-01-09 13:45:33 -080098import com.android.car.hal.UserHalService;
Felipe Leme56ef9ad2020-11-05 18:39:03 -080099import com.android.car.internal.ICarServiceHelper;
Mayank Gargf59f95b2020-10-01 14:55:11 -0700100import com.android.car.internal.common.CommonConstants.UserLifecycleEventType;
Mayank Garg801ea6a2020-09-29 15:43:49 -0700101import com.android.car.internal.common.EventLogTags;
102import com.android.car.internal.common.UserHelperLite;
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700103import com.android.car.power.CarPowerManagementService;
Mayank Garg665c20b2020-08-07 16:19:28 -0700104import com.android.car.user.InitialUserSetter.InitialUserInfo;
Keun-young Parkd462a912019-02-11 08:53:42 -0800105import com.android.internal.annotations.GuardedBy;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700106import com.android.internal.annotations.VisibleForTesting;
felipeale5bf0322020-04-16 15:10:57 -0700107import com.android.internal.infra.AndroidFuture;
Felipe Leme5528ff72020-02-10 19:05:14 -0800108import com.android.internal.os.IResultReceiver;
felipeal5e3ede42020-04-23 18:04:07 -0700109import com.android.internal.util.ArrayUtils;
felipeal2a84d512020-04-06 18:52:15 -0700110import com.android.internal.util.FunctionalUtils;
Mayank Garge19c2922020-03-30 18:05:53 -0700111import com.android.internal.util.Preconditions;
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700112import com.android.internal.util.UserIcons;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700113
114import java.io.PrintWriter;
Keun-young Parkd462a912019-02-11 08:53:42 -0800115import java.util.ArrayList;
felipeal2d0483c2019-11-02 14:07:22 -0700116import java.util.Arrays;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700117import java.util.Iterator;
118import java.util.List;
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000119import java.util.Objects;
Pavel Maltsev17e81832019-04-04 14:38:41 -0700120import java.util.concurrent.CopyOnWriteArrayList;
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700121import java.util.concurrent.CountDownLatch;
122import java.util.concurrent.TimeUnit;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700123
124/**
125 * User service for cars. Manages users at boot time. Including:
126 *
127 * <ol>
Eric Jeong1545f3b2019-09-16 13:56:52 -0700128 * <li> Creates a user used as driver.
129 * <li> Creates a user used as passenger.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700130 * <li> Creates a secondary admin user on first run.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700131 * <li> Switch drivers.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700132 * <ol/>
133 */
Eric Jeong1545f3b2019-09-16 13:56:52 -0700134public final class CarUserService extends ICarUserService.Stub implements CarServiceBase {
Felipe Leme5528ff72020-02-10 19:05:14 -0800135
Mayank Garg72c71d22021-02-03 23:54:45 -0800136 private static final String TAG = CarLog.tagFor(CarUserService.class);
felipealf7368962020-04-16 12:55:19 -0700137
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800138 /** {@code int} extra used to represent a user id in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700139 public static final String BUNDLE_USER_ID = "user.id";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800140 /** {@code int} extra used to represent user flags in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700141 public static final String BUNDLE_USER_FLAGS = "user.flags";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800142 /** {@code String} extra used to represent a user name in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700143 public static final String BUNDLE_USER_NAME = "user.name";
felipeala68ecef2020-05-19 12:46:08 -0700144 /**
145 * {@code int} extra used to represent the user locales in a {@link IResultReceiver} response.
146 */
Mayank Garg8f932822020-09-17 16:09:12 -0700147 public static final String BUNDLE_USER_LOCALES = "user.locales";
felipeala68ecef2020-05-19 12:46:08 -0700148 /**
149 * {@code int} extra used to represent the info action in a {@link IResultReceiver} response.
150 */
Mayank Garg8f932822020-09-17 16:09:12 -0700151 public static final String BUNDLE_INITIAL_INFO_ACTION = "initial_info.action";
Felipe Leme5528ff72020-02-10 19:05:14 -0800152
Mayank Garg9ed099e2020-06-04 16:05:20 -0700153 public static final String VEHICLE_HAL_NOT_SUPPORTED = "Vehicle Hal not supported.";
154
Mayank Garg02576972021-02-18 16:46:07 -0800155 public static final String HANDLER_THREAD_NAME = "UserService";
156
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700157 private final Context mContext;
Keun young Parkfb656372019-03-12 18:37:55 -0700158 private final IActivityManager mAm;
Anthony Hugh9932a252019-06-12 16:19:56 -0700159 private final UserManager mUserManager;
160 private final int mMaxRunningUsers;
Mayank Garg70732a82020-08-05 20:17:47 -0700161 private final InitialUserSetter mInitialUserSetter;
Eric Jeongc91f9452019-08-30 15:04:21 -0700162 private final boolean mEnablePassengerSupport;
Mayank Garg9732d602020-08-09 21:02:40 -0700163 private final UserPreCreator mUserPreCreator;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700164
Eric Jeongc91f9452019-08-30 15:04:21 -0700165 private final Object mLockUser = new Object();
166 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800167 private boolean mUser0Unlocked;
Eric Jeongc91f9452019-08-30 15:04:21 -0700168 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800169 private final ArrayList<Runnable> mUser0UnlockTasks = new ArrayList<>();
Eric Jeongc91f9452019-08-30 15:04:21 -0700170 // Only one passenger is supported.
171 @GuardedBy("mLockUser")
172 private @UserIdInt int mLastPassengerId;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700173 /**
174 * Background users that will be restarted in garage mode. This list can include the
Mayank Garg31e73042020-01-23 00:10:38 -0800175 * current foreground user but the current foreground user should not be restarted.
Keun young Parkf3523cd2019-04-08 10:09:17 -0700176 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700177 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700178 private final ArrayList<Integer> mBackgroundUsersToRestart = new ArrayList<>();
179 /**
180 * Keep the list of background users started here. This is wholly for debugging purpose.
181 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700182 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700183 private final ArrayList<Integer> mBackgroundUsersRestartedHere = new ArrayList<>();
184
Felipe Leme58412202020-01-09 13:45:33 -0800185 private final UserHalService mHal;
186
Keun young Parkb241d022020-04-20 20:31:34 -0700187 private final HandlerThread mHandlerThread = CarServiceUtils.getHandlerThread(
Mayank Garg02576972021-02-18 16:46:07 -0800188 HANDLER_THREAD_NAME);
189 private final Handler mHandler;
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700190
Felipe Leme5528ff72020-02-10 19:05:14 -0800191 /**
Antonio Kantekc8114752020-03-05 21:37:39 -0800192 * List of listeners to be notified on new user activities events.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700193 * This collection should be accessed and manipulated by mHandlerThread only.
Antonio Kantekc8114752020-03-05 21:37:39 -0800194 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700195 private final List<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>();
Antonio Kantekc8114752020-03-05 21:37:39 -0800196
197 /**
Felipe Leme5528ff72020-02-10 19:05:14 -0800198 * List of lifecycle listeners by uid.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700199 * This collection should be accessed and manipulated by mHandlerThread only.
Felipe Leme5528ff72020-02-10 19:05:14 -0800200 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700201 private final SparseArray<IResultReceiver> mAppLifecycleListeners = new SparseArray<>();
Felipe Leme5528ff72020-02-10 19:05:14 -0800202
Mayank Garg7a114c82020-04-08 21:25:06 -0700203 /**
204 * User Id for the user switch in process, if any.
205 */
206 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700207 private int mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg7a114c82020-04-08 21:25:06 -0700208 /**
209 * Request Id for the user switch in process, if any.
210 */
211 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700212 private int mRequestIdForUserSwitchInProcess;
Felipe Lemee3cab982020-03-12 11:39:29 -0700213 private final int mHalTimeoutMs = CarProperties.user_hal_timeout().orElse(5_000);
214
Eric Jeongc91f9452019-08-30 15:04:21 -0700215 private final CopyOnWriteArrayList<PassengerCallback> mPassengerCallbacks =
216 new CopyOnWriteArrayList<>();
217
Mayank Garg7e1450b2020-08-07 18:15:15 -0700218 // TODO(b/163566866): Use mSwitchGuestUserBeforeSleep for new create guest request
219 private final boolean mSwitchGuestUserBeforeSleep;
220
Mayank Garg02576972021-02-18 16:46:07 -0800221 private final int mUserPreCreationDelayMs;
222
felipeal61ce3732020-04-03 11:01:00 -0700223 @Nullable
224 @GuardedBy("mLockUser")
225 private UserInfo mInitialUser;
226
Mayank Garg587f1942020-05-06 01:41:34 -0700227 private IResultReceiver mUserSwitchUiReceiver;
228
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800229 private final CarUxRestrictionsManagerService mCarUxRestrictionService;
230
231 /**
232 * Whether some operations - like user switch - are restricted by driving safety constraints.
233 */
234 @GuardedBy("mLockUser")
235 private boolean mUxRestricted;
236
237 /**
238 * Callback to notify {@code CarServiceHelper} about driving safety changes (through
239 * {@link ICarServiceHelper#setSafetyMode(boolean).
240 *
241 * <p>NOTE: in theory, that logic should belong to {@code CarDevicePolicyService}, but it's
242 * simpler to do it here (and that service already depends on this one).
243 */
244 @GuardedBy("mLockUser")
245 private ICarServiceHelper mICarServiceHelper;
246
247 private final ICarUxRestrictionsChangeListener mCarUxRestrictionsChangeListener =
248 new ICarUxRestrictionsChangeListener.Stub() {
249 @Override
250 public void onUxRestrictionsChanged(CarUxRestrictions restrictions) {
251 setUxRestrictions(restrictions);
252 }
253 };
Felipe Leme5d5ab142020-10-27 13:49:10 -0700254
Eric Jeongc91f9452019-08-30 15:04:21 -0700255 /** Interface for callbaks related to passenger activities. */
256 public interface PassengerCallback {
257 /** Called when passenger is started at a certain zone. */
258 void onPassengerStarted(@UserIdInt int passengerId, int zoneId);
259 /** Called when passenger is stopped. */
260 void onPassengerStopped(@UserIdInt int passengerId);
261 }
262
263 /** Interface for delegating zone-related implementation to CarOccupantZoneService. */
264 public interface ZoneUserBindingHelper {
265 /** Gets occupant zones corresponding to the occupant type. */
266 @NonNull
267 List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType);
268 /** Assigns the user to the occupant zone. */
269 boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId);
270 /** Makes the occupant zone unoccupied. */
271 boolean unassignUserFromOccupantZone(@UserIdInt int userId);
272 /** Returns whether there is a passenger display. */
273 boolean isPassengerDisplayAvailable();
274 }
275
276 private final Object mLockHelper = new Object();
277 @GuardedBy("mLockHelper")
278 private ZoneUserBindingHelper mZoneUserBindingHelper;
279
Felipe Leme6b34fc32020-10-26 15:49:17 -0700280 /** Map used to avoid calling UserHAL when a user was removed because HAL creation failed. */
281 @GuardedBy("mLockUser")
282 private final SparseBooleanArray mFailedToCreateUserIds = new SparseBooleanArray(1);
283
Felipe Leme58412202020-01-09 13:45:33 -0800284 public CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garge90a4082020-09-30 12:57:34 -0700285 @NonNull UserManager userManager,
Felipe Leme5d5ab142020-10-27 13:49:10 -0700286 @NonNull IActivityManager am, int maxRunningUsers,
287 @NonNull CarUxRestrictionsManagerService uxRestrictionService) {
Mayank Garge90a4082020-09-30 12:57:34 -0700288 this(context, hal, userManager, am, maxRunningUsers,
Mayank Garg02576972021-02-18 16:46:07 -0800289 /* initialUserSetter= */ null, /* userPreCreator= */ null, uxRestrictionService,
290 null);
Mayank Garg71661ea2020-04-29 01:25:03 -0700291 }
292
293 @VisibleForTesting
294 CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garge90a4082020-09-30 12:57:34 -0700295 @NonNull UserManager userManager,
Mayank Gargccad8062020-08-30 15:05:10 -0700296 @NonNull IActivityManager am, int maxRunningUsers,
Mayank Garg1bb1c382020-09-03 17:11:11 -0700297 @Nullable InitialUserSetter initialUserSetter,
Felipe Leme5d5ab142020-10-27 13:49:10 -0700298 @Nullable UserPreCreator userPreCreator,
Mayank Garg02576972021-02-18 16:46:07 -0800299 @NonNull CarUxRestrictionsManagerService uxRestrictionService,
300 @Nullable Handler handler) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800301 if (Log.isLoggable(TAG, Log.DEBUG)) {
Felipe Leme8725a2f2020-12-09 16:04:51 -0800302 Slog.d(TAG, "constructed for user " + context.getUserId());
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700303 }
304 mContext = context;
Felipe Leme58412202020-01-09 13:45:33 -0800305 mHal = hal;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700306 mAm = am;
307 mMaxRunningUsers = maxRunningUsers;
Anthony Hugh9932a252019-06-12 16:19:56 -0700308 mUserManager = userManager;
Eric Jeongc91f9452019-08-30 15:04:21 -0700309 mLastPassengerId = UserHandle.USER_NULL;
Mayank Garg02576972021-02-18 16:46:07 -0800310 mHandler = handler == null ? new Handler(mHandlerThread.getLooper()) : handler;
Mayank Garg1bb1c382020-09-03 17:11:11 -0700311 mInitialUserSetter =
Felipe Lemecceb2992020-11-18 18:22:44 -0800312 initialUserSetter == null ? new InitialUserSetter(context, this,
313 (u) -> setInitialUser(u)) : initialUserSetter;
Mayank Garg1bb1c382020-09-03 17:11:11 -0700314 mUserPreCreator =
315 userPreCreator == null ? new UserPreCreator(mUserManager) : userPreCreator;
Mayank Garg7e1450b2020-08-07 18:15:15 -0700316 Resources resources = context.getResources();
317 mEnablePassengerSupport = resources.getBoolean(R.bool.enablePassengerSupport);
318 mSwitchGuestUserBeforeSleep = resources.getBoolean(
319 R.bool.config_switchGuestUserBeforeGoingSleep);
Mayank Garg02576972021-02-18 16:46:07 -0800320 mUserPreCreationDelayMs = resources.getInteger(
321 R.integer.config_WaitDurationForUserPreCreation);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800322 mCarUxRestrictionService = uxRestrictionService;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700323 }
324
325 @Override
326 public void init() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800327 if (Log.isLoggable(TAG, Log.DEBUG)) {
328 Slog.d(TAG, "init()");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700329 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800330 mCarUxRestrictionService.registerUxRestrictionsChangeListener(
331 mCarUxRestrictionsChangeListener, Display.DEFAULT_DISPLAY);
332
333 setUxRestrictions(mCarUxRestrictionService.getCurrentUxRestrictions());
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700334 }
335
336 @Override
337 public void release() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800338 if (Log.isLoggable(TAG, Log.DEBUG)) {
339 Slog.d(TAG, "release()");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700340 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800341 mCarUxRestrictionService
342 .unregisterUxRestrictionsChangeListener(mCarUxRestrictionsChangeListener);
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700343 }
344
345 @Override
Felipe Leme176a5fd2021-01-20 15:48:33 -0800346 public void dump(@NonNull IndentingPrintWriter writer) {
Felipe Leme55236722020-10-16 16:54:32 -0700347 checkHasDumpPermissionGranted("dump()");
348
Eric Jeong1545f3b2019-09-16 13:56:52 -0700349 writer.println("*CarUserService*");
Felipe Leme5528ff72020-02-10 19:05:14 -0800350 String indent = " ";
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700351 handleDumpListeners(writer, indent);
Mayank Garg587f1942020-05-06 01:41:34 -0700352 writer.printf("User switch UI receiver %s\n", mUserSwitchUiReceiver);
Eric Jeongc91f9452019-08-30 15:04:21 -0700353 synchronized (mLockUser) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700354 writer.println("User0Unlocked: " + mUser0Unlocked);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700355 writer.println("BackgroundUsersToRestart: " + mBackgroundUsersToRestart);
356 writer.println("BackgroundUsersRestarted: " + mBackgroundUsersRestartedHere);
Felipe Leme6b34fc32020-10-26 15:49:17 -0700357 if (mFailedToCreateUserIds.size() > 0) {
358 writer.println("FailedToCreateUserIds: " + mFailedToCreateUserIds);
359 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800360 writer.printf("Is UX restricted: %b\n", mUxRestricted);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700361 }
Mayank Garg02576972021-02-18 16:46:07 -0800362
363 writer.println("SwitchGuestUserBeforeSleep: " + mSwitchGuestUserBeforeSleep);
364 writer.println("UserPreCreationDelayMs: " + mUserPreCreationDelayMs);
365
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700366 writer.println("MaxRunningUsers: " + mMaxRunningUsers);
367 List<UserInfo> allDrivers = getAllDrivers();
368 int driversSize = allDrivers.size();
369 writer.println("NumberOfDrivers: " + driversSize);
370 for (int i = 0; i < driversSize; i++) {
371 int driverId = allDrivers.get(i).id;
372 writer.print(indent + "#" + i + ": id=" + driverId);
373 List<UserInfo> passengers = getPassengers(driverId);
374 int passengersSize = passengers.size();
375 writer.print(" NumberPassengers: " + passengersSize);
376 if (passengersSize > 0) {
377 writer.print(" [");
378 for (int j = 0; j < passengersSize; j++) {
379 writer.print(passengers.get(j).id);
380 if (j < passengersSize - 1) {
381 writer.print(" ");
felipeal2d0483c2019-11-02 14:07:22 -0700382 }
felipeal2d0483c2019-11-02 14:07:22 -0700383 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700384 writer.print("]");
felipeal2d0483c2019-11-02 14:07:22 -0700385 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700386 writer.println();
387 }
388 writer.printf("EnablePassengerSupport: %s\n", mEnablePassengerSupport);
389 writer.printf("User HAL timeout: %dms\n", mHalTimeoutMs);
390 writer.printf("Initial user: %s\n", mInitialUser);
felipealbf327652020-06-03 11:33:29 -0700391
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700392 writer.println("Relevant overlayable properties");
393 Resources res = mContext.getResources();
394 writer.printf("%sowner_name=%s\n", indent,
395 res.getString(com.android.internal.R.string.owner_name));
396 writer.printf("%sdefault_guest_name=%s\n", indent,
397 res.getString(R.string.default_guest_name));
felipealf7368962020-04-16 12:55:19 -0700398 writer.printf("User switch in process=%d\n", mUserIdForUserSwitchInProcess);
Mayank Garg7a114c82020-04-08 21:25:06 -0700399 writer.printf("Request Id for the user switch in process=%d\n ",
400 mRequestIdForUserSwitchInProcess);
Mayank Garga480dd92020-05-14 03:14:57 -0700401 writer.printf("System UI package name=%s\n", getSystemUiPackageName());
felipeale8c5dce2020-04-15 11:27:06 -0700402
felipealbf327652020-06-03 11:33:29 -0700403 writer.println("Relevant Global settings");
404 dumpGlobalProperty(writer, indent, CarSettings.Global.LAST_ACTIVE_USER_ID);
405 dumpGlobalProperty(writer, indent, CarSettings.Global.LAST_ACTIVE_PERSISTENT_USER_ID);
406
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700407 mInitialUserSetter.dump(writer);
felipeale8c5dce2020-04-15 11:27:06 -0700408 }
409
felipealbf327652020-06-03 11:33:29 -0700410 private void dumpGlobalProperty(PrintWriter writer, String indent, String property) {
411 String value = Settings.Global.getString(mContext.getContentResolver(), property);
412 writer.printf("%s%s=%s\n", indent, property, value);
413 }
414
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700415 private void handleDumpListeners(@NonNull PrintWriter writer, String indent) {
416 CountDownLatch latch = new CountDownLatch(1);
417 mHandler.post(() -> {
felipealde1e16d2020-06-03 13:20:48 -0700418 handleDumpServiceLifecycleListeners(writer);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700419 handleDumpAppLifecycleListeners(writer, indent);
420 latch.countDown();
421 });
422 int timeout = 5;
423 try {
424 if (!latch.await(timeout, TimeUnit.SECONDS)) {
425 writer.printf("Handler thread didn't respond in %ds when dumping listeners\n",
426 timeout);
427 }
428 } catch (InterruptedException e) {
429 Thread.currentThread().interrupt();
430 writer.println("Interrupted waiting for handler thread to dump app and user listeners");
431 }
432 }
433
felipealde1e16d2020-06-03 13:20:48 -0700434 private void handleDumpServiceLifecycleListeners(@NonNull PrintWriter writer) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700435 if (mUserLifecycleListeners.isEmpty()) {
felipealde1e16d2020-06-03 13:20:48 -0700436 writer.println("No lifecycle listeners for internal services");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700437 return;
438 }
felipealde1e16d2020-06-03 13:20:48 -0700439 int size = mUserLifecycleListeners.size();
440 writer.printf("%d lifecycle listener%s for services\n", size, size == 1 ? "" : "s");
441 String indent = " ";
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700442 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipealde1e16d2020-06-03 13:20:48 -0700443 writer.printf("%s%s\n", indent, FunctionalUtils.getLambdaName(listener));
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700444 }
445 }
446
447 private void handleDumpAppLifecycleListeners(@NonNull PrintWriter writer, String indent) {
felipealde1e16d2020-06-03 13:20:48 -0700448 int size = mAppLifecycleListeners.size();
449 if (size == 0) {
450 writer.println("No lifecycle listeners for apps");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700451 return;
452 }
felipealde1e16d2020-06-03 13:20:48 -0700453 writer.printf("%d lifecycle listener%s for apps \n", size, size == 1 ? "" : "s");
454 for (int i = 0; i < size; i++) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700455 int uid = mAppLifecycleListeners.keyAt(i);
456 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
Felipe Lemeea4b5322020-10-26 15:33:36 -0700457 writer.printf("%suid: %d listener: %s\n", indent, uid,
458 FunctionalUtils.getLambdaName(listener));
Keun-young Parkd462a912019-02-11 08:53:42 -0800459 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700460 }
461
462 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700463 * @see ExperimentalCarUserManager.createDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700464 */
465 @Override
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700466 public AndroidFuture<UserCreationResult> createDriver(@NonNull String name, boolean admin) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700467 checkManageUsersPermission("createDriver");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000468 Objects.requireNonNull(name, "name cannot be null");
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700469
470 AndroidFuture<UserCreationResult> future = new AndroidFuture<UserCreationResult>() {
471 @Override
472 protected void onCompleted(UserCreationResult result, Throwable err) {
473 if (result == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800474 Slog.w(TAG, "createDriver(" + name + "," + admin + ") failed: " + err);
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700475 } else {
476 if (result.getStatus() == UserCreationResult.STATUS_SUCCESSFUL) {
477 assignDefaultIcon(result.getUser());
478 }
479 }
480 super.onCompleted(result, err);
481 };
482 };
483 int flags = 0;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700484 if (admin) {
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700485 if (!(mUserManager.isAdminUser() || mUserManager.isSystemUser())) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800486 Slog.e(TAG, "Only admin users and system user can create other admins.");
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700487 sendUserCreationResultFailure(future, UserCreationResult.STATUS_INVALID_REQUEST);
488 return future;
489 }
490 flags = UserInfo.FLAG_ADMIN;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700491 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700492 createUser(name, UserInfo.getDefaultUserType(flags), flags, mHalTimeoutMs, future);
493 return future;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700494 }
495
496 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700497 * @see ExperimentalCarUserManager.createPassenger
Eric Jeong1545f3b2019-09-16 13:56:52 -0700498 */
499 @Override
500 @Nullable
501 public UserInfo createPassenger(@NonNull String name, @UserIdInt int driverId) {
502 checkManageUsersPermission("createPassenger");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000503 Objects.requireNonNull(name, "name cannot be null");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700504 UserInfo driver = mUserManager.getUserInfo(driverId);
505 if (driver == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800506 Slog.w(TAG, "the driver is invalid");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700507 return null;
508 }
509 if (driver.isGuest()) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800510 Slog.w(TAG, "a guest driver cannot create a passenger");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700511 return null;
512 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700513 // createPassenger doesn't use user HAL because user HAL doesn't support profile user yet.
Bookatz42fb1a62019-10-30 11:45:01 -0700514 UserInfo user = mUserManager.createProfileForUser(name,
515 UserManager.USER_TYPE_PROFILE_MANAGED, /* flags */ 0, driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700516 if (user == null) {
517 // Couldn't create user, most likely because there are too many.
Eric Jeongf75d4132020-12-21 13:48:23 -0800518 Slog.w(TAG, "can't create a profile for user" + driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700519 return null;
520 }
521 // Passenger user should be a non-admin user.
Mayank Garge90a4082020-09-30 12:57:34 -0700522 UserHelper.setDefaultNonAdminRestrictions(mContext, user, /* enable= */ true);
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700523 assignDefaultIcon(user);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700524 return user;
525 }
526
527 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700528 * @see ExperimentalCarUserManager.switchDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700529 */
530 @Override
Eric Jeong25666cf2020-05-14 15:16:27 -0700531 public void switchDriver(@UserIdInt int driverId, AndroidFuture<UserSwitchResult> receiver) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700532 checkManageUsersPermission("switchDriver");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700533 if (UserHelperLite.isHeadlessSystemUser(driverId)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700534 // System user doesn't associate with real person, can not be switched to.
Eric Jeongf75d4132020-12-21 13:48:23 -0800535 Slog.w(TAG, "switching to system user in headless system user mode is not allowed");
felipealdfdf8512020-06-01 09:35:45 -0700536 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700537 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700538 }
539 int userSwitchable = mUserManager.getUserSwitchability();
540 if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800541 Slog.w(TAG, "current process is not allowed to switch user");
felipealdfdf8512020-06-01 09:35:45 -0700542 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700543 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700544 }
Eric Jeong25666cf2020-05-14 15:16:27 -0700545 switchUser(driverId, mHalTimeoutMs, receiver);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700546 }
547
548 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800549 * Returns all drivers who can occupy the driving zone. Guest users are included in the list.
550 *
551 * @return the list of {@link UserInfo} who can be a driver on the device.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700552 */
553 @Override
554 @NonNull
555 public List<UserInfo> getAllDrivers() {
felipeal2d0483c2019-11-02 14:07:22 -0700556 checkManageUsersOrDumpPermission("getAllDrivers");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700557 return getUsers((user) -> !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700558 && !user.isManagedProfile() && !user.isEphemeral());
Eric Jeong1545f3b2019-09-16 13:56:52 -0700559 }
560
561 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800562 * Returns all passengers under the given driver.
563 *
564 * @param driverId User id of a driver.
565 * @return the list of {@link UserInfo} who is a passenger under the given driver.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700566 */
567 @Override
568 @NonNull
569 public List<UserInfo> getPassengers(@UserIdInt int driverId) {
felipeal2d0483c2019-11-02 14:07:22 -0700570 checkManageUsersOrDumpPermission("getPassengers");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700571 return getUsers((user) -> {
Mayank Garg94f3eb92020-08-12 12:38:58 -0700572 return !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Eric Jeong40f8fa32020-05-12 12:23:33 -0700573 && user.isManagedProfile() && user.profileGroupId == driverId;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700574 });
575 }
576
577 /**
578 * @see CarUserManager.startPassenger
579 */
580 @Override
581 public boolean startPassenger(@UserIdInt int passengerId, int zoneId) {
582 checkManageUsersPermission("startPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700583 synchronized (mLockUser) {
584 try {
585 if (!mAm.startUserInBackgroundWithListener(passengerId, null)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800586 Slog.w(TAG, "could not start passenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700587 return false;
588 }
589 } catch (RemoteException e) {
590 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -0800591 Slog.w(TAG, "error while starting passenger", e);
Eric Jeongc91f9452019-08-30 15:04:21 -0700592 return false;
593 }
594 if (!assignUserToOccupantZone(passengerId, zoneId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800595 Slog.w(TAG, "could not assign passenger to zone");
Eric Jeongc91f9452019-08-30 15:04:21 -0700596 return false;
597 }
598 mLastPassengerId = passengerId;
599 }
600 for (PassengerCallback callback : mPassengerCallbacks) {
601 callback.onPassengerStarted(passengerId, zoneId);
602 }
603 return true;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700604 }
605
606 /**
607 * @see CarUserManager.stopPassenger
608 */
609 @Override
610 public boolean stopPassenger(@UserIdInt int passengerId) {
611 checkManageUsersPermission("stopPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700612 return stopPassengerInternal(passengerId, true);
613 }
614
615 private boolean stopPassengerInternal(@UserIdInt int passengerId, boolean checkCurrentDriver) {
616 synchronized (mLockUser) {
617 UserInfo passenger = mUserManager.getUserInfo(passengerId);
618 if (passenger == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800619 Slog.w(TAG, "passenger " + passengerId + " doesn't exist");
Eric Jeongc91f9452019-08-30 15:04:21 -0700620 return false;
621 }
622 if (mLastPassengerId != passengerId) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800623 Slog.w(TAG, "passenger " + passengerId + " hasn't been started");
Eric Jeongc91f9452019-08-30 15:04:21 -0700624 return true;
625 }
626 if (checkCurrentDriver) {
627 int currentUser = ActivityManager.getCurrentUser();
628 if (passenger.profileGroupId != currentUser) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800629 Slog.w(TAG, "passenger " + passengerId
Eric Jeongc91f9452019-08-30 15:04:21 -0700630 + " is not a profile of the current user");
631 return false;
632 }
633 }
634 // Passenger is a profile, so cannot be stopped through activity manager.
635 // Instead, activities started by the passenger are stopped and the passenger is
636 // unassigned from the zone.
637 stopAllTasks(passengerId);
638 if (!unassignUserFromOccupantZone(passengerId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800639 Slog.w(TAG, "could not unassign user from occupant zone");
Eric Jeongc91f9452019-08-30 15:04:21 -0700640 return false;
641 }
642 mLastPassengerId = UserHandle.USER_NULL;
643 }
644 for (PassengerCallback callback : mPassengerCallbacks) {
645 callback.onPassengerStopped(passengerId);
646 }
647 return true;
648 }
649
650 private void stopAllTasks(@UserIdInt int userId) {
651 try {
Louis Chang3bf2f202020-08-18 13:04:28 +0800652 for (RootTaskInfo info : mAm.getAllRootTaskInfos()) {
653 for (int i = 0; i < info.childTaskIds.length; i++) {
654 if (info.childTaskUserIds[i] == userId) {
655 int taskId = info.childTaskIds[i];
Eric Jeongc91f9452019-08-30 15:04:21 -0700656 if (!mAm.removeTask(taskId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800657 Slog.w(TAG, "could not remove task " + taskId);
Eric Jeongc91f9452019-08-30 15:04:21 -0700658 }
659 }
660 }
661 }
662 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800663 Slog.e(TAG, "could not get stack info", e);
Eric Jeongc91f9452019-08-30 15:04:21 -0700664 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700665 }
666
Felipe Leme5528ff72020-02-10 19:05:14 -0800667 @Override
668 public void setLifecycleListenerForUid(IResultReceiver listener) {
669 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700670 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800671 checkInteractAcrossUsersPermission("setLifecycleListenerForUid" + uid);
672
673 try {
674 listener.asBinder().linkToDeath(() -> onListenerDeath(uid), 0);
675 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800676 Slog.wtf(TAG, "Cannot listen to death of " + uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800677 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700678 mHandler.post(() -> mAppLifecycleListeners.append(uid, listener));
Felipe Leme5528ff72020-02-10 19:05:14 -0800679 }
680
681 private void onListenerDeath(int uid) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800682 Slog.i(TAG, "Removing listeners for uid " + uid + " on binder death");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700683 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800684 }
685
686 @Override
687 public void resetLifecycleListenerForUid() {
688 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700689 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_RESET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800690 checkInteractAcrossUsersPermission("resetLifecycleListenerForUid-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700691 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800692 }
693
Felipe Lemee3cab982020-03-12 11:39:29 -0700694 /**
felipeal61ce3732020-04-03 11:01:00 -0700695 * Gets the initial foreground user after the device boots or resumes from suspension.
696 *
697 * <p>When the OEM supports the User HAL, the initial user won't be available until the HAL
698 * returns the initial value to {@code CarService} - if HAL takes too long or times out, this
699 * method returns {@code null}.
700 *
701 * <p>If the HAL eventually times out, {@code CarService} will fallback to its default behavior
702 * (like switching to the last active user), and this method will return the result of such
703 * operation.
704 *
705 * <p>Notice that if {@code CarService} crashes, subsequent calls to this method will return
706 * {@code null}.
707 *
708 * @hide
709 */
710 @Nullable
711 public UserInfo getInitialUser() {
712 checkInteractAcrossUsersPermission("getInitialUser");
713 synchronized (mLockUser) {
714 return mInitialUser;
715 }
716 }
717
felipeal61ce3732020-04-03 11:01:00 -0700718 /**
719 * Sets the initial foreground user after the device boots or resumes from suspension.
720 */
721 public void setInitialUser(@Nullable UserInfo user) {
felipeal312416a2020-04-14 12:28:24 -0700722 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_INITIAL_USER,
723 user == null ? UserHandle.USER_NULL : user.id);
felipeal61ce3732020-04-03 11:01:00 -0700724 synchronized (mLockUser) {
725 mInitialUser = user;
726 }
727 if (user == null) {
728 // This mean InitialUserSetter failed and could not fallback, so the initial user was
729 // not switched (and most likely is SYSTEM_USER).
730 // TODO(b/153104378): should we set it to ActivityManager.getCurrentUser() instead?
Eric Jeongf75d4132020-12-21 13:48:23 -0800731 Slog.wtf(TAG, "Initial user set to null");
felipeal61ce3732020-04-03 11:01:00 -0700732 }
733 }
734
Mayank Garg7e1450b2020-08-07 18:15:15 -0700735 private void initResumeReplaceGuest() {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700736 int currentUserId = ActivityManager.getCurrentUser();
737 UserInfo currentUser = mUserManager.getUserInfo(currentUserId);
738
739 if (!mInitialUserSetter.canReplaceGuestUser(currentUser)) return; // Not a guest
740
741 InitialUserInfo info =
742 new InitialUserSetter.Builder(InitialUserSetter.TYPE_REPLACE_GUEST).build();
743
744 mInitialUserSetter.set(info);
745 }
746
747 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700748 * Calls to switch user at the power suspend.
Mayank Garg7e1450b2020-08-07 18:15:15 -0700749 *
750 * <p><b>Note:</b> Should be used only by {@link CarPowerManagementService}
751 *
Mayank Garg7e1450b2020-08-07 18:15:15 -0700752 */
Mayank Garg0baf88a2020-08-30 21:57:36 -0700753 public void onSuspend() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800754 if (Log.isLoggable(TAG, Log.DEBUG)) {
755 Slog.d(TAG, "onSuspend called.");
Mayank Garg7e1450b2020-08-07 18:15:15 -0700756 }
757
Mayank Garg0baf88a2020-08-30 21:57:36 -0700758 if (mSwitchGuestUserBeforeSleep) {
759 initResumeReplaceGuest();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700760 }
Mayank Garg1bb1c382020-09-03 17:11:11 -0700761
Mayank Garg02576972021-02-18 16:46:07 -0800762 // No delay required for pre-creating users on suspend.
763 preCreateUsersInternal(/*delay=*/ 0);
Mayank Garg7e1450b2020-08-07 18:15:15 -0700764 }
765
766 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700767 * Calls to switch user at the power resume.
768 *
769 * <p>
770 * <b>Note:</b> Should be used only by {@link CarPowerManagementService}
771 *
772 */
773 public void onResume() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800774 if (Log.isLoggable(TAG, Log.DEBUG)) {
775 Slog.d(TAG, "onResume called.");
Mayank Garg0baf88a2020-08-30 21:57:36 -0700776 }
777
Mayank Garg02576972021-02-18 16:46:07 -0800778 mHandler.post(() -> initBootUser(InitialUserInfoRequestType.RESUME));
Mayank Garg0baf88a2020-08-30 21:57:36 -0700779 }
780
781 /**
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700782 * Calls to start user at the android startup.
Mayank Garg70732a82020-08-05 20:17:47 -0700783 */
784 public void initBootUser() {
Mayank Garg02576972021-02-18 16:46:07 -0800785 mHandler.post(() -> initBootUser(getInitialUserInfoRequestType()));
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700786 }
787
Mayank Garg7e1450b2020-08-07 18:15:15 -0700788 private void initBootUser(int requestType) {
789 boolean replaceGuest =
790 requestType == InitialUserInfoRequestType.RESUME && !mSwitchGuestUserBeforeSleep;
Mayank Garg70732a82020-08-05 20:17:47 -0700791 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ, requestType,
792 mHalTimeoutMs);
793 checkManageUsersPermission("startInitialUser");
794
795 if (!isUserHalSupported()) {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700796 fallbackToDefaultInitialUserBehavior(/* userLocales= */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700797 return;
798 }
799
800 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
801 mHal.getInitialUserInfo(requestType, mHalTimeoutMs, usersInfo, (status, resp) -> {
802 if (resp != null) {
803 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP,
804 status, resp.action, resp.userToSwitchOrCreate.userId,
805 resp.userToSwitchOrCreate.flags, resp.userNameToCreate, resp.userLocales);
806
807 String userLocales = resp.userLocales;
808 InitialUserInfo info;
809 switch (resp.action) {
810 case InitialUserInfoResponseAction.SWITCH:
811 int userId = resp.userToSwitchOrCreate.userId;
812 if (userId <= 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800813 Slog.w(TAG, "invalid (or missing) user id sent by HAL: " + userId);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700814 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700815 break;
816 }
817 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_SWITCH)
818 .setUserLocales(userLocales)
819 .setSwitchUserId(userId)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700820 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700821 .build();
822 mInitialUserSetter.set(info);
823 break;
824
825 case InitialUserInfoResponseAction.CREATE:
826 int halFlags = resp.userToSwitchOrCreate.flags;
827 String userName = resp.userNameToCreate;
828 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_CREATE)
829 .setUserLocales(userLocales)
830 .setNewUserName(userName)
831 .setNewUserFlags(halFlags)
832 .build();
833 mInitialUserSetter.set(info);
834 break;
835
836 case InitialUserInfoResponseAction.DEFAULT:
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700837 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700838 break;
839 default:
Eric Jeongf75d4132020-12-21 13:48:23 -0800840 Slog.w(TAG, "invalid response action on " + resp);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700841 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700842 break;
843
844 }
845 } else {
846 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP, status);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700847 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700848 }
849 });
850 }
851
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700852 private void fallbackToDefaultInitialUserBehavior(String userLocales, boolean replaceGuest) {
Mayank Garg70732a82020-08-05 20:17:47 -0700853 InitialUserInfo info = new InitialUserSetter.Builder(
854 InitialUserSetter.TYPE_DEFAULT_BEHAVIOR)
855 .setUserLocales(userLocales)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700856 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700857 .build();
858 mInitialUserSetter.set(info);
859 }
860
861 @VisibleForTesting
862 int getInitialUserInfoRequestType() {
Mayank Garge90a4082020-09-30 12:57:34 -0700863 if (!mInitialUserSetter.hasInitialUser()) {
Mayank Garg70732a82020-08-05 20:17:47 -0700864 return InitialUserInfoRequestType.FIRST_BOOT;
865 }
866 if (mContext.getPackageManager().isDeviceUpgrading()) {
867 return InitialUserInfoRequestType.FIRST_BOOT_AFTER_OTA;
868 }
869 return InitialUserInfoRequestType.COLD_BOOT;
870 }
871
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800872 /**
873 * Sets the {@link ICarServiceHelper} so it can receive UX restriction updates.
874 */
875 public void setCarServiceHelper(ICarServiceHelper helper) {
876 boolean restricted;
877 synchronized (mLockUser) {
878 mICarServiceHelper = helper;
879 restricted = mUxRestricted;
880 }
881 updateSafetyMode(helper, restricted);
882 }
883
884 private void updateSafetyMode(@Nullable ICarServiceHelper helper, boolean restricted) {
885 if (helper == null) return;
886
887 boolean isSafe = !restricted;
888 try {
889 helper.setSafetyMode(isSafe);
890 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800891 Slog.e(TAG, "Exception calling helper.setDpmSafetyMode(" + isSafe + ")", e);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800892 }
893 }
894
895 private void setUxRestrictions(@Nullable CarUxRestrictions restrictions) {
Felipe Leme5d5ab142020-10-27 13:49:10 -0700896 boolean restricted = restrictions != null
897 && (restrictions.getActiveRestrictions() & UX_RESTRICTIONS_NO_SETUP)
898 == UX_RESTRICTIONS_NO_SETUP;
Eric Jeongf75d4132020-12-21 13:48:23 -0800899 if (Log.isLoggable(TAG, Log.DEBUG)) {
900 Slog.d(TAG, "setUxRestrictions(" + restrictions + "): restricted=" + restricted);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800901 } else {
Eric Jeongf75d4132020-12-21 13:48:23 -0800902 Slog.i(TAG, "Setting UX restricted to " + restricted);
Felipe Leme5d5ab142020-10-27 13:49:10 -0700903 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800904
905 ICarServiceHelper helper = null;
906
907 synchronized (mLockUser) {
908 mUxRestricted = restricted;
909 if (mICarServiceHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800910 Slog.e(TAG, "onUxRestrictionsChanged(): no mICarServiceHelper");
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800911 }
912 helper = mICarServiceHelper;
913 }
914 updateSafetyMode(helper, restricted);
915 }
916
917 private boolean isUxRestricted() {
918 synchronized (mLockUser) {
919 return mUxRestricted;
920 }
Felipe Leme5d5ab142020-10-27 13:49:10 -0700921 }
922
Mayank Garg70732a82020-08-05 20:17:47 -0700923 /**
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700924 * Calls the {@link UserHalService} and {@link IActivityManager} for user switch.
925 *
926 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700927 * When everything works well, the workflow is:
928 * <ol>
929 * <li> {@link UserHalService} is called for HAL user switch with ANDROID_SWITCH request
930 * type, current user id, target user id, and a callback.
931 * <li> HAL called back with SUCCESS.
932 * <li> {@link IActivityManager} is called for Android user switch.
933 * <li> Receiver would receive {@code STATUS_SUCCESSFUL}.
934 * <li> Once user is unlocked, {@link UserHalService} is again called with ANDROID_POST_SWITCH
935 * request type, current user id, and target user id. In this case, the current and target
936 * user IDs would be same.
937 * <ol/>
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700938 *
939 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700940 * Corner cases:
941 * <ul>
942 * <li> If target user is already the current user, no user switch is performed and receiver
Mayank Gargef1b9332020-06-11 17:36:56 -0700943 * would receive {@code STATUS_OK_USER_ALREADY_IN_FOREGROUND} right away.
Mayank Gargb08f6772020-05-01 18:06:48 -0700944 * <li> If HAL user switch call fails, no Android user switch. Receiver would receive
945 * {@code STATUS_HAL_INTERNAL_FAILURE}.
946 * <li> If HAL user switch call is successful, but android user switch call fails,
947 * {@link UserHalService} is again called with request type POST_SWITCH, current user id, and
948 * target user id, but in this case the current and target user IDs would be different.
949 * <li> If another user switch request for the same target user is received while previous
950 * request is in process, receiver would receive
951 * {@code STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO} for the new request right away.
952 * <li> If a user switch request is received while another user switch request for different
953 * target user is in process, the previous request would be abandoned and new request will be
954 * processed. No POST_SWITCH would be sent for the previous request.
955 * <ul/>
Mayank Garg59f22192020-03-27 00:51:45 -0700956 *
Mayank Garge19c2922020-03-30 18:05:53 -0700957 * @param targetUserId - target user Id
Mayank Garg59f22192020-03-27 00:51:45 -0700958 * @param timeoutMs - timeout for HAL to wait
959 * @param receiver - receiver for the results
960 */
Mayank Garge19c2922020-03-30 18:05:53 -0700961 @Override
962 public void switchUser(@UserIdInt int targetUserId, int timeoutMs,
felipeale5bf0322020-04-16 15:10:57 -0700963 @NonNull AndroidFuture<UserSwitchResult> receiver) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700964 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_REQ, targetUserId, timeoutMs);
Felipe Leme17799202020-09-03 12:55:53 -0700965 checkManageOrCreateUsersPermission("switchUser");
Mayank Garge19c2922020-03-30 18:05:53 -0700966 Objects.requireNonNull(receiver);
967 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
felipealf7368962020-04-16 12:55:19 -0700968 Preconditions.checkArgument(targetUser != null, "Target user doesn't exist");
Mayank Garg02576972021-02-18 16:46:07 -0800969 mHandler.post(()-> switchUserInternal(targetUser, timeoutMs, receiver));
970 }
Mayank Garg7a114c82020-04-08 21:25:06 -0700971
Mayank Garg02576972021-02-18 16:46:07 -0800972 private void switchUserInternal(@NonNull UserInfo targetUser, int timeoutMs,
973 @NonNull AndroidFuture<UserSwitchResult> receiver) {
felipealf7368962020-04-16 12:55:19 -0700974 int currentUser = ActivityManager.getCurrentUser();
Mayank Garg02576972021-02-18 16:46:07 -0800975 int targetUserId = targetUser.id;
felipealf7368962020-04-16 12:55:19 -0700976 if (currentUser == targetUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800977 if (Log.isLoggable(TAG, Log.DEBUG)) {
978 Slog.d(TAG, "Current user is same as requested target user: " + targetUserId);
Mayank Garg0e239142020-04-14 19:16:31 -0700979 }
Mayank Gargef1b9332020-06-11 17:36:56 -0700980 int resultStatus = UserSwitchResult.STATUS_OK_USER_ALREADY_IN_FOREGROUND;
felipealdfdf8512020-06-01 09:35:45 -0700981 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg0e239142020-04-14 19:16:31 -0700982 return;
983 }
984
Felipe Leme5d5ab142020-10-27 13:49:10 -0700985 if (isUxRestricted()) {
986 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_UX_RESTRICTION_FAILURE);
987 return;
988 }
989
Mayank Garg9ed099e2020-06-04 16:05:20 -0700990 // If User Hal is not supported, just android user switch.
991 if (!isUserHalSupported()) {
992 try {
993 if (mAm.switchUser(targetUserId)) {
994 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_SUCCESSFUL);
995 return;
996 }
997 } catch (RemoteException e) {
998 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -0800999 Slog.w(TAG, "error while switching user " + targetUser.toFullString(), e);
Mayank Garg9ed099e2020-06-04 16:05:20 -07001000 }
1001 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_ANDROID_FAILURE);
1002 return;
1003 }
1004
Mayank Garg7a114c82020-04-08 21:25:06 -07001005 synchronized (mLockUser) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001006 if (Log.isLoggable(TAG, Log.DEBUG)) {
1007 Slog.d(TAG, "switchUser(" + targetUserId + "): currentuser=" + currentUser
felipealf7368962020-04-16 12:55:19 -07001008 + ", mUserIdForUserSwitchInProcess=" + mUserIdForUserSwitchInProcess);
1009 }
1010
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001011 // If there is another request for the same target user, return another request in
1012 // process, else {@link mUserIdForUserSwitchInProcess} is updated and {@link
1013 // mRequestIdForUserSwitchInProcess} is reset. It is possible that there may be another
1014 // user switch request in process for different target user, but that request is now
1015 // ignored.
felipealf7368962020-04-16 12:55:19 -07001016 if (mUserIdForUserSwitchInProcess == targetUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001017 if (Log.isLoggable(TAG, Log.DEBUG)) {
1018 Slog.d(TAG,
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001019 "Another user switch request in process for the requested target user: "
1020 + targetUserId);
1021 }
1022
1023 int resultStatus = UserSwitchResult.STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO;
felipealdfdf8512020-06-01 09:35:45 -07001024 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg7a114c82020-04-08 21:25:06 -07001025 return;
Mayank Garg02576972021-02-18 16:46:07 -08001026 } else {
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001027 mUserIdForUserSwitchInProcess = targetUserId;
1028 mRequestIdForUserSwitchInProcess = 0;
1029 }
Mayank Garg7a114c82020-04-08 21:25:06 -07001030 }
1031
felipealdfdf8512020-06-01 09:35:45 -07001032 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -07001033 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
1034
Felipe Leme5d5ab142020-10-27 13:49:10 -07001035 mHal.switchUser(request, timeoutMs, (halCallbackStatus, resp) -> {
Eric Jeongf75d4132020-12-21 13:48:23 -08001036 if (Log.isLoggable(TAG, Log.DEBUG)) {
1037 Slog.d(TAG, "switch response: status="
Felipe Leme5d5ab142020-10-27 13:49:10 -07001038 + UserHalHelper.halCallbackStatusToString(halCallbackStatus)
1039 + ", resp=" + resp);
felipealf7368962020-04-16 12:55:19 -07001040 }
1041
felipeale5bf0322020-04-16 15:10:57 -07001042 int resultStatus = UserSwitchResult.STATUS_HAL_INTERNAL_FAILURE;
felipealf7368962020-04-16 12:55:19 -07001043
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001044 synchronized (mLockUser) {
Felipe Leme5d5ab142020-10-27 13:49:10 -07001045 if (halCallbackStatus != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001046 Slog.w(TAG, "invalid callback status ("
Felipe Leme5d5ab142020-10-27 13:49:10 -07001047 + UserHalHelper.halCallbackStatusToString(halCallbackStatus)
1048 + ") for response " + resp);
felipealdfdf8512020-06-01 09:35:45 -07001049 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001050 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1051 return;
1052 }
felipealf7368962020-04-16 12:55:19 -07001053
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001054 if (mUserIdForUserSwitchInProcess != targetUserId) {
1055 // Another user switch request received while HAL responded. No need to process
1056 // this request further
Eric Jeongf75d4132020-12-21 13:48:23 -08001057 if (Log.isLoggable(TAG, Log.DEBUG)) {
1058 Slog.d(TAG, "Another user switch received while HAL responsed. Request"
1059 + " abondoned for : " + targetUserId + ". Current user in process: "
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001060 + mUserIdForUserSwitchInProcess);
felipealf7368962020-04-16 12:55:19 -07001061 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001062 resultStatus =
1063 UserSwitchResult.STATUS_TARGET_USER_ABANDONED_DUE_TO_A_NEW_REQUEST;
felipealdfdf8512020-06-01 09:35:45 -07001064 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001065 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1066 return;
1067 }
1068
1069 switch (resp.status) {
1070 case SwitchUserStatus.SUCCESS:
1071 boolean switched;
1072 try {
1073 switched = mAm.switchUser(targetUserId);
1074 if (switched) {
Mayank Garg587f1942020-05-06 01:41:34 -07001075 sendUserSwitchUiCallback(targetUserId);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001076 resultStatus = UserSwitchResult.STATUS_SUCCESSFUL;
1077 mRequestIdForUserSwitchInProcess = resp.requestId;
1078 } else {
1079 resultStatus = UserSwitchResult.STATUS_ANDROID_FAILURE;
1080 postSwitchHalResponse(resp.requestId, targetUserId);
1081 }
1082 } catch (RemoteException e) {
1083 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001084 Slog.w(TAG,
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001085 "error while switching user " + targetUser.toFullString(), e);
1086 }
1087 break;
1088 case SwitchUserStatus.FAILURE:
1089 // HAL failed to switch user
1090 resultStatus = UserSwitchResult.STATUS_HAL_FAILURE;
1091 break;
felipealdfdf8512020-06-01 09:35:45 -07001092 default:
1093 // Shouldn't happen because UserHalService validates the status
Eric Jeongf75d4132020-12-21 13:48:23 -08001094 Slog.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001095 }
1096
1097 if (mRequestIdForUserSwitchInProcess == 0) {
1098 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1099 }
Mayank Garg59f22192020-03-27 00:51:45 -07001100 }
Felipe Leme5d5ab142020-10-27 13:49:10 -07001101 sendUserSwitchResult(receiver, halCallbackStatus, resultStatus, resp.errorMessage);
Mayank Garg59f22192020-03-27 00:51:45 -07001102 });
1103 }
1104
Mayank Garga55c3092020-05-28 03:19:24 -07001105 @Override
Felipe Leme55236722020-10-16 16:54:32 -07001106 public UserRemovalResult removeUser(@UserIdInt int userId) {
1107 return removeUser(userId, /* hasCallerRestrictions= */ false);
1108 }
1109
1110 /**
1111 * Internal implementation of {@code removeUser()}, which is used by both
1112 * {@code ICarUserService} and {@code ICarDevicePolicyService}.
1113 *
1114 * @param userId user to be removed
1115 * @param hasCallerRestrictions when {@code true}, if the caller user is not an admin, it can
1116 * only remove itself.
1117 *
1118 * @return result of the operation.
1119 */
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001120 public UserRemovalResult removeUser(@UserIdInt int userId, boolean hasCallerRestrictions) {
Felipe Leme17799202020-09-03 12:55:53 -07001121 checkManageOrCreateUsersPermission("removeUser");
Felipe Leme55236722020-10-16 16:54:32 -07001122 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_REQ, userId,
1123 hasCallerRestrictions ? 1 : 0);
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001124
Mayank Garga55c3092020-05-28 03:19:24 -07001125 // If requested user is the only admin user, return error.
1126 UserInfo userInfo = mUserManager.getUserInfo(userId);
1127 if (userInfo == null) {
1128 return logAndGetResults(userId, UserRemovalResult.STATUS_USER_DOES_NOT_EXIST);
1129 }
1130
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001131 if (hasCallerRestrictions) {
1132 // Restrictions: non-admin user can only remove itself, admins have no restrictions
1133 int callingUserId = Binder.getCallingUserHandle().getIdentifier();
1134 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
1135 if (!callingUser.isAdmin() && userId != callingUserId) {
1136 throw new SecurityException("Non-admin user " + callingUserId
1137 + " can only remove itself");
1138 }
1139 }
1140
Mayank Garga55c3092020-05-28 03:19:24 -07001141 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
1142 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1143 halUser.userId = userInfo.id;
1144 halUser.flags = UserHalHelper.convertFlags(userInfo);
1145 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1146
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001147 // check if the user is last admin user.
1148 boolean isLastAdmin = false;
Mayank Garga55c3092020-05-28 03:19:24 -07001149 if (UserHalHelper.isAdmin(halUser.flags)) {
1150 int size = usersInfo.existingUsers.size();
1151 int totalAdminUsers = 0;
1152 for (int i = 0; i < size; i++) {
1153 if (UserHalHelper.isAdmin(usersInfo.existingUsers.get(i).flags)) {
1154 totalAdminUsers++;
1155 }
1156 }
1157 if (totalAdminUsers == 1) {
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001158 isLastAdmin = true;
Mayank Garga55c3092020-05-28 03:19:24 -07001159 }
1160 }
1161
1162 // First remove user from android and then remove from HAL because HAL remove user is one
1163 // way call.
Felipe Leme9a751912021-01-05 17:45:48 -08001164 // TODO(b/170887769): rename hasCallerRestrictions to fromCarDevicePolicyManager (or use an
1165 // int / enum to indicate if it's called from CarUserManager or CarDevicePolicyManager), as
1166 // it's counter-intuitive that it's "allowed even when disallowed" when it
1167 // "has caller restrictions"
1168 boolean evenWhenDisallowed = hasCallerRestrictions;
1169 int result = mUserManager.removeUserOrSetEphemeral(userId, evenWhenDisallowed);
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001170 if (result == UserManager.REMOVE_RESULT_ERROR) {
Mayank Garga55c3092020-05-28 03:19:24 -07001171 return logAndGetResults(userId, UserRemovalResult.STATUS_ANDROID_FAILURE);
1172 }
1173
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001174 if (isLastAdmin) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001175 Slog.w(TAG,
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001176 "Last admin user successfully removed or set ephemeral. User Id: " + userId);
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001177 }
1178
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001179 switch (result) {
1180 case UserManager.REMOVE_RESULT_REMOVED:
1181 case UserManager.REMOVE_RESULT_ALREADY_BEING_REMOVED:
1182 return logAndGetResults(userId,
1183 isLastAdmin ? UserRemovalResult.STATUS_SUCCESSFUL_LAST_ADMIN_REMOVED
1184 : UserRemovalResult.STATUS_SUCCESSFUL);
1185 case UserManager.REMOVE_RESULT_SET_EPHEMERAL:
1186 return logAndGetResults(userId,
1187 isLastAdmin ? UserRemovalResult.STATUS_SUCCESSFUL_LAST_ADMIN_SET_EPHEMERAL
1188 : UserRemovalResult.STATUS_SUCCESSFUL_SET_EPHEMERAL);
1189 default:
1190 throw new IllegalStateException("Unknown user removal result code " + result);
1191 }
Mayank Garga55c3092020-05-28 03:19:24 -07001192 }
1193
Felipe Leme67d564c2020-11-13 15:35:34 -08001194 /**
1195 * Should be called by {@code ICarImpl} only.
1196 */
1197 public void onUserRemoved(@NonNull UserInfo user) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001198 if (Log.isLoggable(TAG, Log.DEBUG)) {
1199 Slog.d(TAG, "onUserRemoved: " + user.toFullString());
Felipe Leme67d564c2020-11-13 15:35:34 -08001200 }
1201 notifyHalUserRemoved(user);
1202 }
1203
1204 private void notifyHalUserRemoved(@NonNull UserInfo user) {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001205 if (!isUserHalSupported()) return;
1206
Felipe Leme67d564c2020-11-13 15:35:34 -08001207 if (user == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001208 Slog.wtf(TAG, "notifyHalUserRemoved() called for null user");
Felipe Leme67d564c2020-11-13 15:35:34 -08001209 return;
1210 }
1211
1212 int userId = user.id;
1213
Felipe Leme6b34fc32020-10-26 15:49:17 -07001214 if (userId == UserHandle.USER_NULL) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001215 Slog.wtf(TAG, "notifyHalUserRemoved() called for UserHandle.USER_NULL");
Felipe Leme6b34fc32020-10-26 15:49:17 -07001216 return;
1217 }
1218
1219 synchronized (mLockUser) {
1220 if (mFailedToCreateUserIds.get(userId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001221 if (Log.isLoggable(TAG, Log.DEBUG)) {
1222 Slog.d(TAG, "notifyHalUserRemoved(): skipping " + userId);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001223 }
1224 mFailedToCreateUserIds.delete(userId);
1225 return;
1226 }
1227 }
1228
1229 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
1230 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1231 halUser.userId = userId;
Felipe Leme67d564c2020-11-13 15:35:34 -08001232 halUser.flags = UserHalHelper.convertFlags(user);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001233
1234 RemoveUserRequest request = new RemoveUserRequest();
1235 request.removedUserInfo = halUser;
1236 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1237 mHal.removeUser(request);
1238 }
1239
Mayank Garga55c3092020-05-28 03:19:24 -07001240 private UserRemovalResult logAndGetResults(@UserIdInt int userId,
1241 @UserRemovalResult.Status int result) {
1242 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_RESP, userId, result);
1243 return new UserRemovalResult(result);
1244 }
1245
Mayank Garg587f1942020-05-06 01:41:34 -07001246 private void sendUserSwitchUiCallback(@UserIdInt int targetUserId) {
1247 if (mUserSwitchUiReceiver == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001248 Slog.w(TAG, "No User switch UI receiver.");
Mayank Garg587f1942020-05-06 01:41:34 -07001249 return;
1250 }
1251
felipealdfdf8512020-06-01 09:35:45 -07001252 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_UI_REQ, targetUserId);
Mayank Garg587f1942020-05-06 01:41:34 -07001253 try {
Mayank Garg587f1942020-05-06 01:41:34 -07001254 mUserSwitchUiReceiver.send(targetUserId, null);
1255 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001256 Slog.e(TAG, "Error calling user switch UI receiver.", e);
Mayank Garg587f1942020-05-06 01:41:34 -07001257 }
1258 }
1259
Felipe Lemecceb2992020-11-18 18:22:44 -08001260 /**
1261 * Used to create the initial user, even when it's disallowed by {@code DevicePolicyManager}.
1262 */
1263 @Nullable
1264 UserInfo createUserEvenWhenDisallowed(@Nullable String name, @NonNull String userType,
1265 @UserInfoFlag int flags) {
1266 if (mICarServiceHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001267 Slog.wtf(TAG, "createUserEvenWhenDisallowed(): mICarServiceHelper not set yet",
Felipe Lemecceb2992020-11-18 18:22:44 -08001268 new Exception());
1269 return null;
1270 }
1271 try {
1272 return mICarServiceHelper.createUserEvenWhenDisallowed(name, userType, flags);
1273 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001274 Slog.e(TAG, "createUserEvenWhenDisallowed(" + UserHelperLite.safeName(name) + ", "
Felipe Lemecceb2992020-11-18 18:22:44 -08001275 + userType + ", " + UserInfo.flagsToString(flags) + ") failed", e);
1276 return null;
1277 }
1278 }
1279
felipeal5e3ede42020-04-23 18:04:07 -07001280 @Override
felipealdfdf8512020-06-01 09:35:45 -07001281 public void createUser(@Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
1282 int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver) {
Felipe Leme8c888ab2020-11-02 17:39:52 -08001283 createUser(name, userType, flags, timeoutMs, receiver, /* hasCallerRestrictions= */ false);
1284 }
1285
1286 /**
1287 * Internal implementation of {@code createUser()}, which is used by both
1288 * {@code ICarUserService} and {@code ICarDevicePolicyService}.
1289 *
1290 * @param hasCallerRestrictions when {@code true}, if the caller user is not an admin, it can
1291 * only create admin users
1292 */
1293 public void createUser(@Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
1294 int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver,
1295 boolean hasCallerRestrictions) {
felipealdfdf8512020-06-01 09:35:45 -07001296 Objects.requireNonNull(userType, "user type cannot be null");
1297 Objects.requireNonNull(receiver, "receiver cannot be null");
Felipe Leme17799202020-09-03 12:55:53 -07001298 checkManageOrCreateUsersPermission(flags);
Mayank Garg94f3eb92020-08-12 12:38:58 -07001299 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_REQ,
Felipe Leme8c888ab2020-11-02 17:39:52 -08001300 UserHelperLite.safeName(name), userType, flags, timeoutMs,
1301 hasCallerRestrictions ? 1 : 0);
Mayank Garg02576972021-02-18 16:46:07 -08001302 mHandler.post(() -> createUserInternal(name, userType, flags, timeoutMs, receiver,
1303 hasCallerRestrictions));
Felipe Leme8c888ab2020-11-02 17:39:52 -08001304
Mayank Garg02576972021-02-18 16:46:07 -08001305 }
1306
1307 private void createUserInternal(@Nullable String name, @NonNull String userType,
1308 @UserInfoFlag int flags, int timeoutMs,
1309 @NonNull AndroidFuture<UserCreationResult> receiver,
1310 boolean hasCallerRestrictions) {
Felipe Leme8c888ab2020-11-02 17:39:52 -08001311 if (hasCallerRestrictions) {
1312 // Restrictions:
1313 // - type/flag can only be normal user, admin, or guest
1314 // - non-admin user can only create non-admin users
1315
1316 boolean validCombination;
1317 switch (userType) {
1318 case UserManager.USER_TYPE_FULL_SECONDARY:
1319 validCombination = flags == 0
1320 || (flags & UserInfo.FLAG_ADMIN) == UserInfo.FLAG_ADMIN;
1321 break;
1322 case UserManager.USER_TYPE_FULL_GUEST:
1323 validCombination = flags == 0;
1324 break;
1325 default:
1326 validCombination = false;
1327 }
1328 if (!validCombination) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001329 if (Log.isLoggable(TAG, Log.DEBUG)) {
1330 Slog.d(TAG, "Invalid combination of user type(" + userType
Felipe Leme71d296f2020-11-04 12:11:42 -08001331 + ") and flags (" + UserInfo.flagsToString(flags)
1332 + ") for caller with restrictions");
1333 }
1334 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_INVALID_REQUEST);
1335 return;
1336
Felipe Leme8c888ab2020-11-02 17:39:52 -08001337 }
1338
1339 int callingUserId = Binder.getCallingUserHandle().getIdentifier();
1340 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
1341 if (!callingUser.isAdmin() && (flags & UserInfo.FLAG_ADMIN) == UserInfo.FLAG_ADMIN) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001342 if (Log.isLoggable(TAG, Log.DEBUG)) {
1343 Slog.d(TAG, "Non-admin user " + callingUserId
Felipe Leme71d296f2020-11-04 12:11:42 -08001344 + " can only create non-admin users");
1345 }
1346 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_INVALID_REQUEST);
1347 return;
Felipe Leme8c888ab2020-11-02 17:39:52 -08001348 }
Felipe Leme71d296f2020-11-04 12:11:42 -08001349
Felipe Leme8c888ab2020-11-02 17:39:52 -08001350 }
felipealdfdf8512020-06-01 09:35:45 -07001351
1352 UserInfo newUser;
1353 try {
1354 newUser = mUserManager.createUser(name, userType, flags);
1355 if (newUser == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001356 Slog.w(TAG, "um.createUser() returned null for user of type " + userType
felipealdfdf8512020-06-01 09:35:45 -07001357 + " and flags " + UserInfo.flagsToString(flags));
1358 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1359 return;
1360 }
Eric Jeongf75d4132020-12-21 13:48:23 -08001361 if (Log.isLoggable(TAG, Log.DEBUG)) {
1362 Slog.d(TAG, "Created user: " + newUser.toFullString());
felipealdfdf8512020-06-01 09:35:45 -07001363 }
1364 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_CREATED, newUser.id,
Mayank Garg94f3eb92020-08-12 12:38:58 -07001365 UserHelperLite.safeName(newUser.name), newUser.userType, newUser.flags);
felipealdfdf8512020-06-01 09:35:45 -07001366 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001367 Slog.e(TAG, "Error creating user of type " + userType + " and flags"
felipealdfdf8512020-06-01 09:35:45 -07001368 + UserInfo.flagsToString(flags), e);
1369 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1370 return;
1371 }
1372
Mayank Garg9ed099e2020-06-04 16:05:20 -07001373 if (!isUserHalSupported()) {
1374 sendUserCreationResult(receiver, UserCreationResult.STATUS_SUCCESSFUL, newUser, null);
1375 return;
1376 }
1377
felipealdfdf8512020-06-01 09:35:45 -07001378 CreateUserRequest request = new CreateUserRequest();
1379 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1380 if (!TextUtils.isEmpty(name)) {
1381 request.newUserName = name;
1382 }
1383 request.newUserInfo.userId = newUser.id;
1384 request.newUserInfo.flags = UserHalHelper.convertFlags(newUser);
Eric Jeongf75d4132020-12-21 13:48:23 -08001385 if (Log.isLoggable(TAG, Log.DEBUG)) {
1386 Slog.d(TAG, "Create user request: " + request);
felipealdfdf8512020-06-01 09:35:45 -07001387 }
1388
1389 try {
1390 mHal.createUser(request, timeoutMs, (status, resp) -> {
1391 int resultStatus = UserCreationResult.STATUS_HAL_INTERNAL_FAILURE;
Eric Jeongf75d4132020-12-21 13:48:23 -08001392 if (Log.isLoggable(TAG, Log.DEBUG)) {
1393 Slog.d(TAG, "createUserResponse: status="
felipealdfdf8512020-06-01 09:35:45 -07001394 + UserHalHelper.halCallbackStatusToString(status) + ", resp=" + resp);
1395 }
1396 UserInfo user = null; // user returned in the result
1397 if (status != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001398 Slog.w(TAG, "invalid callback status ("
felipealdfdf8512020-06-01 09:35:45 -07001399 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1400 + resp);
1401 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1402 resultStatus, resp.errorMessage);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001403 removeCreatedUser(newUser, "HAL call failed with "
felipealdfdf8512020-06-01 09:35:45 -07001404 + UserHalHelper.halCallbackStatusToString(status));
1405 sendUserCreationResult(receiver, resultStatus, user, /* errorMsg= */ null);
1406 return;
1407 }
1408
1409 switch (resp.status) {
1410 case CreateUserStatus.SUCCESS:
1411 resultStatus = UserCreationResult.STATUS_SUCCESSFUL;
1412 user = newUser;
1413 break;
1414 case CreateUserStatus.FAILURE:
1415 // HAL failed to switch user
1416 resultStatus = UserCreationResult.STATUS_HAL_FAILURE;
1417 break;
1418 default:
1419 // Shouldn't happen because UserHalService validates the status
Eric Jeongf75d4132020-12-21 13:48:23 -08001420 Slog.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
felipealdfdf8512020-06-01 09:35:45 -07001421 }
1422 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1423 resultStatus, resp.errorMessage);
1424 if (user == null) {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001425 removeCreatedUser(newUser, "HAL returned "
felipealdfdf8512020-06-01 09:35:45 -07001426 + UserCreationResult.statusToString(resultStatus));
1427 }
1428 sendUserCreationResult(receiver, resultStatus, user, resp.errorMessage);
1429 });
1430 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001431 Slog.w(TAG, "mHal.createUser(" + request + ") failed", e);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001432 removeCreatedUser(newUser, "mHal.createUser() failed");
felipealdfdf8512020-06-01 09:35:45 -07001433 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_HAL_INTERNAL_FAILURE);
1434 }
1435 }
1436
Felipe Leme6b34fc32020-10-26 15:49:17 -07001437 private void removeCreatedUser(@NonNull UserInfo user, @NonNull String reason) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001438 Slog.i(TAG, "removing " + user.toFullString() + "; reason: " + reason);
Felipe Leme67d564c2020-11-13 15:35:34 -08001439
Felipe Leme6b34fc32020-10-26 15:49:17 -07001440 int userId = user.id;
1441 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_REMOVED, userId, reason);
1442
1443 synchronized (mLockUser) {
1444 mFailedToCreateUserIds.put(userId, true);
1445 }
1446
felipealdfdf8512020-06-01 09:35:45 -07001447 try {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001448 if (!mUserManager.removeUser(userId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001449 Slog.w(TAG, "Failed to remove user " + user.toFullString());
felipealdfdf8512020-06-01 09:35:45 -07001450 }
1451 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001452 Slog.e(TAG, "Failed to remove user " + user.toFullString(), e);
felipealdfdf8512020-06-01 09:35:45 -07001453 }
1454 }
1455
1456 @Override
Mayank Garg3f566582020-10-02 22:10:16 -07001457 public UserIdentificationAssociationResponse getUserIdentificationAssociation(
1458 @UserIdentificationAssociationType int[] types) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001459 if (!isUserHalUserAssociationSupported()) {
1460 return UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED);
1461 }
1462
felipeal5e3ede42020-04-23 18:04:07 -07001463 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
Felipe Leme17799202020-09-03 12:55:53 -07001464 checkManageOrCreateUsersPermission("getUserIdentificationAssociation");
felipeal5e3ede42020-04-23 18:04:07 -07001465
1466 int uid = getCallingUid();
1467 int userId = UserHandle.getUserId(uid);
1468 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_REQ, uid, userId);
1469
1470 UserIdentificationGetRequest request = new UserIdentificationGetRequest();
1471 request.userInfo.userId = userId;
1472 request.userInfo.flags = getHalUserInfoFlags(userId);
1473
1474 request.numberAssociationTypes = types.length;
1475 for (int i = 0; i < types.length; i++) {
1476 request.associationTypes.add(types[i]);
1477 }
1478
1479 UserIdentificationResponse halResponse = mHal.getUserAssociation(request);
1480 if (halResponse == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001481 Slog.w(TAG, "getUserIdentificationAssociation(): HAL returned null for "
felipeal5e3ede42020-04-23 18:04:07 -07001482 + Arrays.toString(types));
felipeal159a2a42020-05-08 10:32:11 -07001483 return UserIdentificationAssociationResponse.forFailure();
felipeal5e3ede42020-04-23 18:04:07 -07001484 }
1485
1486 int[] values = new int[halResponse.associations.size()];
1487 for (int i = 0; i < values.length; i++) {
1488 values[i] = halResponse.associations.get(i).value;
1489 }
1490 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_RESP, values.length);
1491
felipeal159a2a42020-05-08 10:32:11 -07001492 return UserIdentificationAssociationResponse.forSuccess(values, halResponse.errorMessage);
1493 }
1494
1495 @Override
Mayank Garg3f566582020-10-02 22:10:16 -07001496 public void setUserIdentificationAssociation(int timeoutMs,
1497 @UserIdentificationAssociationType int[] types,
1498 @UserIdentificationAssociationSetValue int[] values,
felipeal159a2a42020-05-08 10:32:11 -07001499 AndroidFuture<UserIdentificationAssociationResponse> result) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001500 if (!isUserHalUserAssociationSupported()) {
1501 result.complete(
1502 UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED));
1503 return;
1504 }
1505
felipeal159a2a42020-05-08 10:32:11 -07001506 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
1507 Preconditions.checkArgument(!ArrayUtils.isEmpty(values), "must have at least one value");
1508 if (types.length != values.length) {
1509 throw new IllegalArgumentException("types (" + Arrays.toString(types) + ") and values ("
1510 + Arrays.toString(values) + ") should have the same length");
1511 }
Felipe Leme17799202020-09-03 12:55:53 -07001512 checkManageOrCreateUsersPermission("setUserIdentificationAssociation");
felipeal159a2a42020-05-08 10:32:11 -07001513
1514 int uid = getCallingUid();
1515 int userId = UserHandle.getUserId(uid);
1516 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_REQ, uid, userId, types.length);
1517
1518 UserIdentificationSetRequest request = new UserIdentificationSetRequest();
1519 request.userInfo.userId = userId;
1520 request.userInfo.flags = getHalUserInfoFlags(userId);
1521
1522 request.numberAssociations = types.length;
1523 for (int i = 0; i < types.length; i++) {
1524 UserIdentificationSetAssociation association = new UserIdentificationSetAssociation();
1525 association.type = types[i];
1526 association.value = values[i];
1527 request.associations.add(association);
1528 }
1529
1530 mHal.setUserAssociation(timeoutMs, request, (status, resp) -> {
1531 if (status != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001532 Slog.w(TAG, "setUserIdentificationAssociation(): invalid callback status ("
felipeal159a2a42020-05-08 10:32:11 -07001533 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1534 + resp);
1535 if (resp == null || TextUtils.isEmpty(resp.errorMessage)) {
1536 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0);
1537 result.complete(UserIdentificationAssociationResponse.forFailure());
1538 return;
1539 }
1540 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0,
1541 resp.errorMessage);
1542 result.complete(
1543 UserIdentificationAssociationResponse.forFailure(resp.errorMessage));
1544 return;
1545 }
1546 int respSize = resp.associations.size();
1547 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, respSize,
1548 resp.errorMessage);
1549
1550 int[] responseTypes = new int[respSize];
1551 for (int i = 0; i < respSize; i++) {
1552 responseTypes[i] = resp.associations.get(i).value;
1553 }
1554 UserIdentificationAssociationResponse response = UserIdentificationAssociationResponse
1555 .forSuccess(responseTypes, resp.errorMessage);
Eric Jeongf75d4132020-12-21 13:48:23 -08001556 if (Log.isLoggable(TAG, Log.DEBUG)) {
1557 Slog.d(TAG, "setUserIdentificationAssociation(): resp= " + resp
felipeal159a2a42020-05-08 10:32:11 -07001558 + ", converted=" + response);
1559 }
1560 result.complete(response);
1561 });
felipeal5e3ede42020-04-23 18:04:07 -07001562 }
1563
1564 /**
1565 * Gets the User HAL flags for the given user.
1566 *
1567 * @throws IllegalArgumentException if the user does not exist.
1568 */
1569 private int getHalUserInfoFlags(@UserIdInt int userId) {
1570 UserInfo user = mUserManager.getUserInfo(userId);
1571 Preconditions.checkArgument(user != null, "no user for id %d", userId);
1572 return UserHalHelper.convertFlags(user);
1573 }
1574
Mayank Garg0e239142020-04-14 19:16:31 -07001575 private void sendResult(@NonNull IResultReceiver receiver, int resultCode,
1576 @Nullable Bundle resultData) {
1577 try {
1578 receiver.send(resultCode, resultData);
1579 } catch (RemoteException e) {
1580 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001581 Slog.w(TAG, "error while sending results", e);
Mayank Garg0e239142020-04-14 19:16:31 -07001582 }
1583 }
1584
felipealdfdf8512020-06-01 09:35:45 -07001585 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
Felipe Leme5d5ab142020-10-27 13:49:10 -07001586 @UserSwitchResult.Status int userSwitchStatus) {
1587 sendUserSwitchResult(receiver, HalCallback.STATUS_INVALID, userSwitchStatus,
1588 /* errorMessage= */ null);
felipeale5bf0322020-04-16 15:10:57 -07001589 }
1590
felipealdfdf8512020-06-01 09:35:45 -07001591 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
Felipe Leme5d5ab142020-10-27 13:49:10 -07001592 @HalCallback.HalCallbackStatus int halCallbackStatus,
1593 @UserSwitchResult.Status int userSwitchStatus, @Nullable String errorMessage) {
1594 if (errorMessage != null) {
1595 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, halCallbackStatus,
1596 userSwitchStatus, errorMessage);
1597 } else {
1598 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, halCallbackStatus,
1599 userSwitchStatus);
1600 }
1601 receiver.complete(new UserSwitchResult(userSwitchStatus, errorMessage));
felipeale5bf0322020-04-16 15:10:57 -07001602 }
1603
felipealdfdf8512020-06-01 09:35:45 -07001604 private void sendUserCreationResultFailure(@NonNull AndroidFuture<UserCreationResult> receiver,
1605 @UserCreationResult.Status int status) {
1606 sendUserCreationResult(receiver, status, /* user= */ null, /* errorMessage= */ null);
1607 }
1608
1609 private void sendUserCreationResult(@NonNull AndroidFuture<UserCreationResult> receiver,
1610 @UserCreationResult.Status int status, @NonNull UserInfo user,
1611 @Nullable String errorMessage) {
1612 if (TextUtils.isEmpty(errorMessage)) {
1613 errorMessage = null;
1614 }
1615 receiver.complete(new UserCreationResult(status, user, errorMessage));
1616 }
1617
Mayank Garg6307fe42020-04-15 23:09:03 -07001618 /**
1619 * Calls activity manager for user switch.
1620 *
1621 * <p><b>NOTE</b> This method is meant to be called just by UserHalService.
1622 *
1623 * @param requestId for the user switch request
1624 * @param targetUserId of the target user
1625 *
1626 * @hide
1627 */
1628 public void switchAndroidUserFromHal(int requestId, @UserIdInt int targetUserId) {
1629 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_FROM_HAL_REQ, requestId,
1630 targetUserId);
Eric Jeongf75d4132020-12-21 13:48:23 -08001631 Slog.i(TAG, "User hal requested a user switch. Target user id " + targetUserId);
Mayank Garg6307fe42020-04-15 23:09:03 -07001632
1633 try {
1634 boolean result = mAm.switchUser(targetUserId);
1635 if (result) {
1636 updateUserSwitchInProcess(requestId, targetUserId);
1637 } else {
1638 postSwitchHalResponse(requestId, targetUserId);
1639 }
1640 } catch (RemoteException e) {
1641 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001642 Slog.w(TAG, "error while switching user " + targetUserId, e);
Mayank Garg6307fe42020-04-15 23:09:03 -07001643 }
1644 }
1645
1646 private void updateUserSwitchInProcess(int requestId, @UserIdInt int targetUserId) {
1647 synchronized (mLockUser) {
1648 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
1649 // Some other user switch is in process.
Eric Jeongf75d4132020-12-21 13:48:23 -08001650 if (Log.isLoggable(TAG, Log.DEBUG)) {
1651 Slog.d(TAG, "User switch for user: " + mUserIdForUserSwitchInProcess
Mayank Garg6307fe42020-04-15 23:09:03 -07001652 + " is in process. Abandoning it as a new user switch is requested"
1653 + " for the target user: " + targetUserId);
1654 }
1655 }
1656 mUserIdForUserSwitchInProcess = targetUserId;
1657 mRequestIdForUserSwitchInProcess = requestId;
1658 }
1659 }
Mayank Garg9ed099e2020-06-04 16:05:20 -07001660
Mayank Garg7a114c82020-04-08 21:25:06 -07001661 private void postSwitchHalResponse(int requestId, @UserIdInt int targetUserId) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001662 if (!isUserHalSupported()) return;
1663
felipealdfdf8512020-06-01 09:35:45 -07001664 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -07001665 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_POST_SWITCH_USER_REQ, requestId,
1666 targetUserId, usersInfo.currentUser.userId);
1667 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
1668 request.requestId = requestId;
1669 mHal.postSwitchResponse(request);
1670 }
1671
1672 private SwitchUserRequest createUserSwitchRequest(@UserIdInt int targetUserId,
1673 @NonNull UsersInfo usersInfo) {
1674 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
Mayank Garg7a114c82020-04-08 21:25:06 -07001675 android.hardware.automotive.vehicle.V2_0.UserInfo halTargetUser =
1676 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1677 halTargetUser.userId = targetUser.id;
1678 halTargetUser.flags = UserHalHelper.convertFlags(targetUser);
Mayank Gargeb37d092020-06-02 14:37:57 -07001679 SwitchUserRequest request = new SwitchUserRequest();
1680 request.targetUser = halTargetUser;
1681 request.usersInfo = usersInfo;
1682 return request;
Mayank Garg7a114c82020-04-08 21:25:06 -07001683 }
1684
Mayank Garg59f22192020-03-27 00:51:45 -07001685 /**
Felipe Lemee3cab982020-03-12 11:39:29 -07001686 * Checks if the User HAL is supported.
1687 */
1688 public boolean isUserHalSupported() {
1689 return mHal.isSupported();
1690 }
1691
Mayank Garg587f1942020-05-06 01:41:34 -07001692 /**
Mayank Garg9ed099e2020-06-04 16:05:20 -07001693 * Checks if the User HAL user association is supported.
1694 */
1695 @Override
1696 public boolean isUserHalUserAssociationSupported() {
1697 return mHal.isUserAssociationSupported();
1698 }
1699
1700 /**
Mayank Garg587f1942020-05-06 01:41:34 -07001701 * Sets a callback which is invoked before user switch.
1702 *
1703 * <p>
1704 * This method should only be called by the Car System UI. The purpose of this call is to notify
1705 * Car System UI to show the user switch UI before the user switch.
1706 */
1707 @Override
1708 public void setUserSwitchUiCallback(@NonNull IResultReceiver receiver) {
Yan Zhu67a383e2020-05-11 20:46:24 -07001709 checkManageUsersPermission("setUserSwitchUiCallback");
Mayank Garga480dd92020-05-14 03:14:57 -07001710
1711 // Confirm that caller is system UI.
1712 String systemUiPackageName = getSystemUiPackageName();
1713 if (systemUiPackageName == null) {
1714 throw new IllegalStateException("System UI package not found.");
1715 }
1716
1717 try {
1718 int systemUiUid = mContext
1719 .createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0).getPackageManager()
1720 .getPackageUid(systemUiPackageName, PackageManager.MATCH_SYSTEM_ONLY);
1721 int callerUid = Binder.getCallingUid();
1722 if (systemUiUid != callerUid) {
1723 throw new SecurityException("Invalid caller. Only" + systemUiPackageName
1724 + " is allowed to make this call");
1725 }
1726 } catch (NameNotFoundException e) {
1727 throw new IllegalStateException("Package " + systemUiPackageName + " not found.");
1728 }
1729
Mayank Garg587f1942020-05-06 01:41:34 -07001730 mUserSwitchUiReceiver = receiver;
1731 }
1732
Mayank Garga480dd92020-05-14 03:14:57 -07001733 // TODO(157082995): This information can be taken from
1734 // PackageManageInternalImpl.getSystemUiServiceComponent
1735 @Nullable
1736 private String getSystemUiPackageName() {
1737 try {
1738 ComponentName componentName = ComponentName.unflattenFromString(mContext.getResources()
1739 .getString(com.android.internal.R.string.config_systemUIServiceComponent));
1740 return componentName.getPackageName();
1741 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001742 Slog.w(TAG, "error while getting system UI package name.", e);
Mayank Garga480dd92020-05-14 03:14:57 -07001743 return null;
1744 }
1745 }
1746
Keun young Park13a7a822019-04-04 15:53:08 -07001747 private void updateDefaultUserRestriction() {
1748 // We want to set restrictions on system and guest users only once. These are persisted
1749 // onto disk, so it's sufficient to do it once + we minimize the number of disk writes.
1750 if (Settings.Global.getInt(mContext.getContentResolver(),
Eric Jeong1545f3b2019-09-16 13:56:52 -07001751 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, /* default= */ 0) != 0) {
1752 return;
Keun young Park13a7a822019-04-04 15:53:08 -07001753 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001754 // Only apply the system user restrictions if the system user is headless.
1755 if (UserManager.isHeadlessSystemUserMode()) {
1756 setSystemUserRestrictions();
1757 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001758 Settings.Global.putInt(mContext.getContentResolver(),
1759 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, 1);
Keun young Park13a7a822019-04-04 15:53:08 -07001760 }
1761
Eric Jeong1545f3b2019-09-16 13:56:52 -07001762 private boolean isPersistentUser(@UserIdInt int userId) {
Anthony Hugh9932a252019-06-12 16:19:56 -07001763 return !mUserManager.getUserInfo(userId).isEphemeral();
1764 }
1765
Antonio Kantekc8114752020-03-05 21:37:39 -08001766 /**
Antonio Kantekc8114752020-03-05 21:37:39 -08001767 * Adds a new {@link UserLifecycleListener} to listen to user activity events.
1768 */
1769 public void addUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1770 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001771 mHandler.post(() -> mUserLifecycleListeners.add(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001772 }
1773
1774 /**
1775 * Removes previously added {@link UserLifecycleListener}.
1776 */
1777 public void removeUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1778 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001779 mHandler.post(() -> mUserLifecycleListeners.remove(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001780 }
1781
Eric Jeongc91f9452019-08-30 15:04:21 -07001782 /** Adds callback to listen to passenger activity events. */
1783 public void addPassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001784 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001785 mPassengerCallbacks.add(callback);
1786 }
1787
1788 /** Removes previously added callback to listen passenger events. */
1789 public void removePassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001790 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001791 mPassengerCallbacks.remove(callback);
1792 }
1793
1794 /** Sets the implementation of ZoneUserBindingHelper. */
1795 public void setZoneUserBindingHelper(@NonNull ZoneUserBindingHelper helper) {
1796 synchronized (mLockHelper) {
1797 mZoneUserBindingHelper = helper;
1798 }
1799 }
1800
felipeal98900c82020-04-09 09:05:02 -07001801 private void onUserUnlocked(@UserIdInt int userId) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001802 ArrayList<Runnable> tasks = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001803 synchronized (mLockUser) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001804 sendPostSwitchToHalLocked(userId);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001805 if (userId == UserHandle.USER_SYSTEM) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001806 if (!mUser0Unlocked) { // user 0, unlocked, do this only once
1807 updateDefaultUserRestriction();
1808 tasks = new ArrayList<>(mUser0UnlockTasks);
1809 mUser0UnlockTasks.clear();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001810 mUser0Unlocked = true;
Keun young Parkf3523cd2019-04-08 10:09:17 -07001811 }
1812 } else { // none user0
Eric Jeong1545f3b2019-09-16 13:56:52 -07001813 Integer user = userId;
1814 if (isPersistentUser(userId)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001815 // current foreground user should stay in top priority.
Anthony Hughfbb67762019-10-15 12:54:54 -07001816 if (userId == ActivityManager.getCurrentUser()) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001817 mBackgroundUsersToRestart.remove(user);
1818 mBackgroundUsersToRestart.add(0, user);
1819 }
1820 // -1 for user 0
1821 if (mBackgroundUsersToRestart.size() > (mMaxRunningUsers - 1)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001822 int userToDrop = mBackgroundUsersToRestart.get(
Keun young Parkf3523cd2019-04-08 10:09:17 -07001823 mBackgroundUsersToRestart.size() - 1);
Eric Jeongf75d4132020-12-21 13:48:23 -08001824 Slog.i(TAG, "New user unlocked:" + userId
Keun young Parkf3523cd2019-04-08 10:09:17 -07001825 + ", dropping least recently user from restart list:" + userToDrop);
1826 // Drop the least recently used user.
1827 mBackgroundUsersToRestart.remove(mBackgroundUsersToRestart.size() - 1);
1828 }
1829 }
Keun-young Parkd462a912019-02-11 08:53:42 -08001830 }
1831 }
1832 if (tasks != null && tasks.size() > 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001833 Slog.d(TAG, "User0 unlocked, run queued tasks:" + tasks.size());
Keun-young Parkd462a912019-02-11 08:53:42 -08001834 for (Runnable r : tasks) {
1835 r.run();
1836 }
1837 }
1838 }
1839
1840 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001841 * Starts all background users that were active in system.
1842 *
Keun young Parkfb656372019-03-12 18:37:55 -07001843 * @return list of background users started successfully.
1844 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001845 @NonNull
Keun young Parkfb656372019-03-12 18:37:55 -07001846 public ArrayList<Integer> startAllBackgroundUsers() {
1847 ArrayList<Integer> users;
Eric Jeongc91f9452019-08-30 15:04:21 -07001848 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001849 users = new ArrayList<>(mBackgroundUsersToRestart);
1850 mBackgroundUsersRestartedHere.clear();
1851 mBackgroundUsersRestartedHere.addAll(mBackgroundUsersToRestart);
Keun young Parkfb656372019-03-12 18:37:55 -07001852 }
1853 ArrayList<Integer> startedUsers = new ArrayList<>();
1854 for (Integer user : users) {
Anthony Hughfbb67762019-10-15 12:54:54 -07001855 if (user == ActivityManager.getCurrentUser()) {
Keun young Parkfb656372019-03-12 18:37:55 -07001856 continue;
1857 }
1858 try {
1859 if (mAm.startUserInBackground(user)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001860 if (mUserManager.isUserUnlockingOrUnlocked(user)) {
1861 // already unlocked / unlocking. No need to unlock.
Keun young Parkfb656372019-03-12 18:37:55 -07001862 startedUsers.add(user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001863 } else if (mAm.unlockUser(user, null, null, null)) {
1864 startedUsers.add(user);
1865 } else { // started but cannot unlock
Eric Jeongf75d4132020-12-21 13:48:23 -08001866 Slog.w(TAG, "Background user started but cannot be unlocked:" + user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001867 if (mUserManager.isUserRunning(user)) {
1868 // add to started list so that it can be stopped later.
1869 startedUsers.add(user);
1870 }
Keun young Parkfb656372019-03-12 18:37:55 -07001871 }
1872 }
1873 } catch (RemoteException e) {
1874 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001875 Slog.w(TAG, "error while starting user in background", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001876 }
1877 }
Keun young Parkf3523cd2019-04-08 10:09:17 -07001878 // Keep only users that were re-started in mBackgroundUsersRestartedHere
Eric Jeongc91f9452019-08-30 15:04:21 -07001879 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001880 ArrayList<Integer> usersToRemove = new ArrayList<>();
1881 for (Integer user : mBackgroundUsersToRestart) {
1882 if (!startedUsers.contains(user)) {
1883 usersToRemove.add(user);
1884 }
1885 }
1886 mBackgroundUsersRestartedHere.removeAll(usersToRemove);
1887 }
Keun young Parkfb656372019-03-12 18:37:55 -07001888 return startedUsers;
1889 }
1890
1891 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001892 * Stops all background users that were active in system.
1893 *
1894 * @return whether stopping succeeds.
Keun young Parkfb656372019-03-12 18:37:55 -07001895 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001896 public boolean stopBackgroundUser(@UserIdInt int userId) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001897 if (userId == UserHandle.USER_SYSTEM) {
1898 return false;
1899 }
Anthony Hughfbb67762019-10-15 12:54:54 -07001900 if (userId == ActivityManager.getCurrentUser()) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001901 Slog.i(TAG, "stopBackgroundUser, already a FG user:" + userId);
Keun young Parkfb656372019-03-12 18:37:55 -07001902 return false;
1903 }
1904 try {
Keun young Parked9e6282019-09-19 17:38:26 -07001905 int r = mAm.stopUserWithDelayedLocking(userId, true, null);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001906 if (r == ActivityManager.USER_OP_SUCCESS) {
Eric Jeongc91f9452019-08-30 15:04:21 -07001907 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001908 Integer user = userId;
1909 mBackgroundUsersRestartedHere.remove(user);
1910 }
1911 } else if (r == ActivityManager.USER_OP_IS_CURRENT) {
1912 return false;
1913 } else {
Eric Jeongf75d4132020-12-21 13:48:23 -08001914 Slog.i(TAG, "stopBackgroundUser failed, user:" + userId + " err:" + r);
Keun young Parkfb656372019-03-12 18:37:55 -07001915 return false;
1916 }
1917 } catch (RemoteException e) {
1918 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001919 Slog.w(TAG, "error while stopping user", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001920 }
1921 return true;
1922 }
1923
1924 /**
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001925 * Notifies all registered {@link UserLifecycleListener} with the event passed as argument.
Pavel Maltsev17e81832019-04-04 14:38:41 -07001926 */
Mayank Gargccad8062020-08-30 15:05:10 -07001927 public void onUserLifecycleEvent(@UserLifecycleEventType int eventType,
felipeale8c5dce2020-04-15 11:27:06 -07001928 @UserIdInt int fromUserId, @UserIdInt int toUserId) {
1929 int userId = toUserId;
felipeal98900c82020-04-09 09:05:02 -07001930
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001931 // Handle special cases first...
felipeal98900c82020-04-09 09:05:02 -07001932 if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_SWITCHING) {
Mayank Garge5de0f92020-04-23 21:38:38 -07001933 onUserSwitching(fromUserId, toUserId);
felipeal98900c82020-04-09 09:05:02 -07001934 } else if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
1935 onUserUnlocked(userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001936 }
1937
felipeale8c5dce2020-04-15 11:27:06 -07001938 // ...then notify listeners.
Yan Zhue7921522020-04-16 15:59:25 -07001939 UserLifecycleEvent event = new UserLifecycleEvent(eventType, fromUserId, userId);
felipeale8c5dce2020-04-15 11:27:06 -07001940
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001941 mHandler.post(() -> {
1942 handleNotifyServiceUserLifecycleListeners(event);
1943 handleNotifyAppUserLifecycleListeners(event);
1944 });
felipeale8c5dce2020-04-15 11:27:06 -07001945 }
1946
Mayank Garg7a114c82020-04-08 21:25:06 -07001947 private void sendPostSwitchToHalLocked(@UserIdInt int userId) {
felipealf7368962020-04-16 12:55:19 -07001948 if (mUserIdForUserSwitchInProcess == UserHandle.USER_NULL
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001949 || mUserIdForUserSwitchInProcess != userId
1950 || mRequestIdForUserSwitchInProcess == 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001951 if (Log.isLoggable(TAG, Log.DEBUG)) {
1952 Slog.d(TAG, "No user switch request Id. No android post switch sent.");
Mayank Garg7a114c82020-04-08 21:25:06 -07001953 }
1954 return;
1955 }
felipealf7368962020-04-16 12:55:19 -07001956 postSwitchHalResponse(mRequestIdForUserSwitchInProcess, mUserIdForUserSwitchInProcess);
1957 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001958 mRequestIdForUserSwitchInProcess = 0;
Mayank Garg7a114c82020-04-08 21:25:06 -07001959 }
1960
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001961 private void handleNotifyAppUserLifecycleListeners(UserLifecycleEvent event) {
1962 int listenersSize = mAppLifecycleListeners.size();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001963 if (listenersSize == 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001964 if (Log.isLoggable(TAG, Log.DEBUG)) {
1965 Slog.d(TAG, "No app listener to be notified of " + event);
felipeal2a84d512020-04-06 18:52:15 -07001966 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001967 return;
1968 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001969 // Must use a different TimingsTraceLog because it's another thread
Eric Jeongf75d4132020-12-21 13:48:23 -08001970 if (Log.isLoggable(TAG, Log.DEBUG)) {
1971 Slog.d(TAG, "Notifying " + listenersSize + " app listeners of " + event);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001972 }
felipeal2a84d512020-04-06 18:52:15 -07001973 int userId = event.getUserId();
Eric Jeongf75d4132020-12-21 13:48:23 -08001974 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
felipealde1e16d2020-06-03 13:20:48 -07001975 int eventType = event.getEventType();
1976 t.traceBegin("notify-app-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001977 for (int i = 0; i < listenersSize; i++) {
1978 int uid = mAppLifecycleListeners.keyAt(i);
felipealde1e16d2020-06-03 13:20:48 -07001979
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001980 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
1981 Bundle data = new Bundle();
felipealde1e16d2020-06-03 13:20:48 -07001982 data.putInt(CarUserManager.BUNDLE_PARAM_ACTION, eventType);
Yan Zhue7921522020-04-16 15:59:25 -07001983
felipealde1e16d2020-06-03 13:20:48 -07001984 int fromUserId = event.getPreviousUserId();
1985 if (fromUserId != UserHandle.USER_NULL) {
1986 data.putInt(CarUserManager.BUNDLE_PARAM_PREVIOUS_USER_ID, fromUserId);
Yan Zhue7921522020-04-16 15:59:25 -07001987 }
1988
Eric Jeongf75d4132020-12-21 13:48:23 -08001989 if (Log.isLoggable(TAG, Log.DEBUG)) {
1990 Slog.d(TAG, "Notifying listener for uid " + uid);
felipeal2a84d512020-04-06 18:52:15 -07001991 }
felipealde1e16d2020-06-03 13:20:48 -07001992 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_APP_LIFECYCLE_LISTENER,
1993 uid, eventType, fromUserId, userId);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001994 try {
felipealde1e16d2020-06-03 13:20:48 -07001995 t.traceBegin("notify-app-listener-uid-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001996 listener.send(userId, data);
1997 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001998 Slog.e(TAG, "Error calling lifecycle listener", e);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001999 } finally {
2000 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002001 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002002 }
2003 t.traceEnd(); // notify-app-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002004 }
2005
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002006 private void handleNotifyServiceUserLifecycleListeners(UserLifecycleEvent event) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002007 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002008 if (mUserLifecycleListeners.isEmpty()) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002009 Slog.w(TAG, "Not notifying internal UserLifecycleListeners");
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002010 return;
Eric Jeongf75d4132020-12-21 13:48:23 -08002011 } else if (Log.isLoggable(TAG, Log.DEBUG)) {
2012 Slog.d(TAG, "Notifying " + mUserLifecycleListeners.size()
2013 + " service listeners of " + event);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002014 }
felipeal2a84d512020-04-06 18:52:15 -07002015
felipealde1e16d2020-06-03 13:20:48 -07002016 int userId = event.getUserId();
2017 int eventType = event.getEventType();
2018 t.traceBegin("notify-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002019 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipeal2a84d512020-04-06 18:52:15 -07002020 String listenerName = FunctionalUtils.getLambdaName(listener);
felipealde1e16d2020-06-03 13:20:48 -07002021 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_INTERNAL_LIFECYCLE_LISTENER,
2022 listenerName, eventType, event.getPreviousUserId(), userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002023 try {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002024 t.traceBegin("notify-listener-" + listenerName);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002025 listener.onEvent(event);
2026 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002027 Slog.e(TAG,
felipeal2a84d512020-04-06 18:52:15 -07002028 "Exception raised when invoking onEvent for " + listenerName, e);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002029 } finally {
2030 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002031 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002032 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002033 t.traceEnd(); // notify-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002034 }
2035
Mayank Garge5de0f92020-04-23 21:38:38 -07002036 private void onUserSwitching(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002037 Slog.i(TAG, "onUserSwitching() callback for user " + toUserId);
2038 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
Mayank Garge5de0f92020-04-23 21:38:38 -07002039 t.traceBegin("onUserSwitching-" + toUserId);
Felipe Leme5528ff72020-02-10 19:05:14 -08002040
Mayank Garge5de0f92020-04-23 21:38:38 -07002041 // Switch HAL users if user switch is not requested by CarUserService
2042 notifyHalLegacySwitch(fromUserId, toUserId);
2043
Mayank Garge90a4082020-09-30 12:57:34 -07002044 mInitialUserSetter.setLastActiveUser(toUserId);
felipealbf327652020-06-03 11:33:29 -07002045
Eric Jeongc91f9452019-08-30 15:04:21 -07002046 if (mLastPassengerId != UserHandle.USER_NULL) {
2047 stopPassengerInternal(mLastPassengerId, false);
2048 }
2049 if (mEnablePassengerSupport && isPassengerDisplayAvailable()) {
2050 setupPassengerUser();
Mayank Garge5de0f92020-04-23 21:38:38 -07002051 startFirstPassenger(toUserId);
Eric Jeongc91f9452019-08-30 15:04:21 -07002052 }
felipeal98900c82020-04-09 09:05:02 -07002053 t.traceEnd();
Pavel Maltsev17e81832019-04-04 14:38:41 -07002054 }
2055
Mayank Garge5de0f92020-04-23 21:38:38 -07002056 private void notifyHalLegacySwitch(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
2057 synchronized (mLockUser) {
felipeal7d12ee22020-06-05 09:30:19 -07002058 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002059 if (Log.isLoggable(TAG, Log.DEBUG)) {
2060 Slog.d(TAG, "notifyHalLegacySwitch(" + fromUserId + ", " + toUserId
felipeal7d12ee22020-06-05 09:30:19 -07002061 + "): not needed, normal switch for " + mUserIdForUserSwitchInProcess);
2062 }
2063 return;
2064 }
Mayank Garge5de0f92020-04-23 21:38:38 -07002065 }
2066
Mayank Garg9ed099e2020-06-04 16:05:20 -07002067 if (!isUserHalSupported()) return;
2068
Mayank Garge5de0f92020-04-23 21:38:38 -07002069 // switch HAL user
felipeal7d12ee22020-06-05 09:30:19 -07002070 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager, fromUserId);
Mayank Gargeb37d092020-06-02 14:37:57 -07002071 SwitchUserRequest request = createUserSwitchRequest(toUserId, usersInfo);
2072 mHal.legacyUserSwitch(request);
Mayank Garge5de0f92020-04-23 21:38:38 -07002073 }
2074
Pavel Maltsev17e81832019-04-04 14:38:41 -07002075 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07002076 * 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 -08002077 * run inside this call.
Eric Jeong1545f3b2019-09-16 13:56:52 -07002078 *
Keun-young Parkd462a912019-02-11 08:53:42 -08002079 * @param r Runnable to run.
2080 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07002081 public void runOnUser0Unlock(@NonNull Runnable r) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00002082 Objects.requireNonNull(r, "runnable cannot be null");
Keun-young Parkd462a912019-02-11 08:53:42 -08002083 boolean runNow = false;
Eric Jeongc91f9452019-08-30 15:04:21 -07002084 synchronized (mLockUser) {
Keun-young Parkd462a912019-02-11 08:53:42 -08002085 if (mUser0Unlocked) {
2086 runNow = true;
2087 } else {
2088 mUser0UnlockTasks.add(r);
2089 }
2090 }
2091 if (runNow) {
2092 r.run();
2093 }
2094 }
2095
Keun young Parkf3523cd2019-04-08 10:09:17 -07002096 @VisibleForTesting
Eric Jeong1545f3b2019-09-16 13:56:52 -07002097 @NonNull
2098 ArrayList<Integer> getBackgroundUsersToRestart() {
2099 ArrayList<Integer> backgroundUsersToRestart = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07002100 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07002101 backgroundUsersToRestart = new ArrayList<>(mBackgroundUsersToRestart);
2102 }
2103 return backgroundUsersToRestart;
2104 }
2105
Ying Zheng1ab32b62018-06-26 12:47:26 -07002106 private void setSystemUserRestrictions() {
Ying Zheng1ab32b62018-06-26 12:47:26 -07002107 // Disable Location service for system user.
2108 LocationManager locationManager =
2109 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Anthony Hugh04ee04f2019-12-17 16:11:33 -08002110 locationManager.setLocationEnabledForUser(
2111 /* enabled= */ false, UserHandle.of(UserHandle.USER_SYSTEM));
Ying Zheng1ab32b62018-06-26 12:47:26 -07002112 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07002113
2114 /**
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002115 * Assigns a default icon to a user according to the user's id.
2116 *
2117 * @param userInfo User whose avatar is set to default icon.
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002118 */
Eric Jeongb2dc6ff2020-06-05 17:00:26 -07002119 private void assignDefaultIcon(UserInfo userInfo) {
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002120 int idForIcon = userInfo.isGuest() ? UserHandle.USER_NULL : userInfo.id;
2121 Bitmap bitmap = UserIcons.convertToBitmap(
2122 UserIcons.getDefaultUserIcon(mContext.getResources(), idForIcon, false));
2123 mUserManager.setUserIcon(userInfo.id, bitmap);
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002124 }
2125
Eric Jeong1545f3b2019-09-16 13:56:52 -07002126 private interface UserFilter {
2127 boolean isEligibleUser(UserInfo user);
2128 }
2129
2130 /** Returns all users who are matched by the given filter. */
2131 private List<UserInfo> getUsers(UserFilter filter) {
Colin Cross0df71ea2020-08-27 04:12:26 +00002132 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeong1545f3b2019-09-16 13:56:52 -07002133
2134 for (Iterator<UserInfo> iterator = users.iterator(); iterator.hasNext(); ) {
2135 UserInfo user = iterator.next();
2136 if (!filter.isEligibleUser(user)) {
2137 iterator.remove();
2138 }
2139 }
2140 return users;
2141 }
2142
felipeal2d0483c2019-11-02 14:07:22 -07002143 private static void checkManageUsersOrDumpPermission(String message) {
Felipe Leme55236722020-10-16 16:54:32 -07002144 checkHasAtLeastOnePermissionGranted(message,
felipeal2d0483c2019-11-02 14:07:22 -07002145 android.Manifest.permission.MANAGE_USERS,
2146 android.Manifest.permission.DUMP);
2147 }
2148
Felipe Leme5528ff72020-02-10 19:05:14 -08002149 private void checkInteractAcrossUsersPermission(String message) {
Felipe Leme55236722020-10-16 16:54:32 -07002150 checkHasAtLeastOnePermissionGranted(message,
2151 android.Manifest.permission.INTERACT_ACROSS_USERS,
Felipe Leme5528ff72020-02-10 19:05:14 -08002152 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
2153 }
2154
Eric Jeongc91f9452019-08-30 15:04:21 -07002155 private int getNumberOfManagedProfiles(@UserIdInt int userId) {
Colin Cross0df71ea2020-08-27 04:12:26 +00002156 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeongc91f9452019-08-30 15:04:21 -07002157 // Count all users that are managed profiles of the given user.
2158 int managedProfilesCount = 0;
2159 for (UserInfo user : users) {
2160 if (user.isManagedProfile() && user.profileGroupId == userId) {
2161 managedProfilesCount++;
2162 }
2163 }
2164 return managedProfilesCount;
2165 }
2166
2167 /**
2168 * Starts the first passenger of the given driver and assigns the passenger to the front
2169 * passenger zone.
2170 *
2171 * @param driverId User id of the driver.
2172 * @return whether it succeeds.
2173 */
2174 private boolean startFirstPassenger(@UserIdInt int driverId) {
2175 int zoneId = getAvailablePassengerZone();
2176 if (zoneId == OccupantZoneInfo.INVALID_ZONE_ID) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002177 Slog.w(TAG, "passenger occupant zone is not found");
Eric Jeongc91f9452019-08-30 15:04:21 -07002178 return false;
2179 }
2180 List<UserInfo> passengers = getPassengers(driverId);
2181 if (passengers.size() < 1) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002182 Slog.w(TAG, "passenger is not found");
Eric Jeongc91f9452019-08-30 15:04:21 -07002183 return false;
2184 }
2185 // Only one passenger is supported. If there are two or more passengers, the first passenger
2186 // is chosen.
2187 int passengerId = passengers.get(0).id;
2188 if (!startPassenger(passengerId, zoneId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002189 Slog.w(TAG, "cannot start passenger " + passengerId);
Eric Jeongc91f9452019-08-30 15:04:21 -07002190 return false;
2191 }
2192 return true;
2193 }
2194
2195 private int getAvailablePassengerZone() {
2196 int[] occupantTypes = new int[] {CarOccupantZoneManager.OCCUPANT_TYPE_FRONT_PASSENGER,
2197 CarOccupantZoneManager.OCCUPANT_TYPE_REAR_PASSENGER};
2198 for (int occupantType : occupantTypes) {
2199 int zoneId = getZoneId(occupantType);
2200 if (zoneId != OccupantZoneInfo.INVALID_ZONE_ID) {
2201 return zoneId;
2202 }
2203 }
2204 return OccupantZoneInfo.INVALID_ZONE_ID;
2205 }
2206
2207 /**
2208 * Creates a new passenger user when there is no passenger user.
2209 */
2210 private void setupPassengerUser() {
2211 int currentUser = ActivityManager.getCurrentUser();
2212 int profileCount = getNumberOfManagedProfiles(currentUser);
2213 if (profileCount > 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002214 Slog.w(TAG, "max profile of user" + currentUser
Eric Jeongc91f9452019-08-30 15:04:21 -07002215 + " is exceeded: current profile count is " + profileCount);
2216 return;
2217 }
2218 // TODO(b/140311342): Use resource string for the default passenger name.
2219 UserInfo passenger = createPassenger("Passenger", currentUser);
2220 if (passenger == null) {
2221 // Couldn't create user, most likely because there are too many.
Eric Jeongf75d4132020-12-21 13:48:23 -08002222 Slog.w(TAG, "cannot create a passenger user");
Eric Jeongc91f9452019-08-30 15:04:21 -07002223 return;
2224 }
2225 }
2226
2227 @NonNull
2228 private List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType) {
2229 ZoneUserBindingHelper helper = null;
2230 synchronized (mLockHelper) {
2231 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002232 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002233 return new ArrayList<OccupantZoneInfo>();
2234 }
2235 helper = mZoneUserBindingHelper;
2236 }
2237 return helper.getOccupantZones(occupantType);
2238 }
2239
2240 private boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId) {
2241 ZoneUserBindingHelper helper = null;
2242 synchronized (mLockHelper) {
2243 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002244 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002245 return false;
2246 }
2247 helper = mZoneUserBindingHelper;
2248 }
2249 return helper.assignUserToOccupantZone(userId, zoneId);
2250 }
2251
2252 private boolean unassignUserFromOccupantZone(@UserIdInt int userId) {
2253 ZoneUserBindingHelper helper = null;
2254 synchronized (mLockHelper) {
2255 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002256 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002257 return false;
2258 }
2259 helper = mZoneUserBindingHelper;
2260 }
2261 return helper.unassignUserFromOccupantZone(userId);
2262 }
2263
2264 private boolean isPassengerDisplayAvailable() {
2265 ZoneUserBindingHelper helper = null;
2266 synchronized (mLockHelper) {
2267 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002268 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002269 return false;
2270 }
2271 helper = mZoneUserBindingHelper;
2272 }
2273 return helper.isPassengerDisplayAvailable();
2274 }
2275
2276 /**
2277 * Gets the zone id of the given occupant type. If there are two or more zones, the first found
2278 * zone is returned.
2279 *
2280 * @param occupantType The type of an occupant.
2281 * @return The zone id of the given occupant type. {@link OccupantZoneInfo.INVALID_ZONE_ID},
2282 * if not found.
2283 */
2284 private int getZoneId(@OccupantTypeEnum int occupantType) {
2285 List<OccupantZoneInfo> zoneInfos = getOccupantZones(occupantType);
2286 return (zoneInfos.size() > 0) ? zoneInfos.get(0).zoneId : OccupantZoneInfo.INVALID_ZONE_ID;
2287 }
Mayank Garg9732d602020-08-09 21:02:40 -07002288
2289 /**
2290 * Manages the required number of pre-created users.
2291 */
2292 public void preCreateUsers() {
Mayank Garg02576972021-02-18 16:46:07 -08002293 preCreateUsersInternal(mUserPreCreationDelayMs);
2294 }
2295
2296 private void preCreateUsersInternal(int delay) {
2297 mHandler.postDelayed(() -> mUserPreCreator.managePreCreatedUsers(), delay);
Mayank Garg9732d602020-08-09 21:02:40 -07002298 }
Felipe Leme17799202020-09-03 12:55:53 -07002299
2300 // TODO(b/167698977): members below were copied from UserManagerService; it would be better to
2301 // move them to some internal android.os class instead.
2302
2303 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
2304 UserInfo.FLAG_MANAGED_PROFILE
2305 | UserInfo.FLAG_PROFILE
2306 | UserInfo.FLAG_EPHEMERAL
2307 | UserInfo.FLAG_RESTRICTED
2308 | UserInfo.FLAG_GUEST
2309 | UserInfo.FLAG_DEMO
2310 | UserInfo.FLAG_FULL;
2311
2312 private static void checkManageUsersPermission(String message) {
2313 if (!hasManageUsersPermission()) {
2314 throw new SecurityException("You need " + MANAGE_USERS + " permission to: " + message);
2315 }
2316 }
2317
2318 private static void checkManageOrCreateUsersPermission(String message) {
2319 if (!hasManageOrCreateUsersPermission()) {
2320 throw new SecurityException(
2321 "You either need " + MANAGE_USERS + " or " + CREATE_USERS + " permission to: "
2322 + message);
2323 }
2324 }
2325
2326 private static void checkManageOrCreateUsersPermission(int creationFlags) {
2327 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2328 if (!hasManageOrCreateUsersPermission()) {
2329 throw new SecurityException("You either need " + MANAGE_USERS + " or "
2330 + CREATE_USERS + "permission to create a user with flags "
2331 + creationFlags);
2332 }
2333 } else if (!hasManageUsersPermission()) {
2334 throw new SecurityException("You need " + MANAGE_USERS + " permission to create a user"
2335 + " with flags " + creationFlags);
2336 }
2337 }
2338
2339 private static boolean hasManageUsersPermission() {
2340 final int callingUid = Binder.getCallingUid();
2341 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2342 || callingUid == Process.ROOT_UID
2343 || hasPermissionGranted(MANAGE_USERS, callingUid);
2344 }
2345
2346 private static boolean hasManageUsersOrPermission(String alternativePermission) {
2347 final int callingUid = Binder.getCallingUid();
2348 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2349 || callingUid == Process.ROOT_UID
2350 || hasPermissionGranted(MANAGE_USERS, callingUid)
2351 || hasPermissionGranted(alternativePermission, callingUid);
2352 }
2353
2354 private static boolean hasManageOrCreateUsersPermission() {
2355 return hasManageUsersOrPermission(CREATE_USERS);
2356 }
2357
2358 private static boolean hasPermissionGranted(String permission, int uid) {
2359 return ActivityManager.checkComponentPermission(permission, uid, /* owningUid= */ -1,
2360 /* exported= */ true) == PackageManager.PERMISSION_GRANTED;
2361 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002362}