blob: d535c926197cfd467b8a5c47ed80a363f9383de4 [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;
Yan Zhu65a0acd2021-06-21 10:56:53 -070025import static com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport.DEPRECATED_CODE;
Mayank Garg578db012021-06-14 22:17:00 -070026import static com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport.DUMP_INFO;
Eric Jeong1545f3b2019-09-16 13:56:52 -070027
28import android.annotation.NonNull;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070029import android.annotation.Nullable;
Eric Jeong1545f3b2019-09-16 13:56:52 -070030import android.annotation.UserIdInt;
Keun young Parkfb656372019-03-12 18:37:55 -070031import android.app.ActivityManager;
Louis Chang3bf2f202020-08-18 13:04:28 +080032import android.app.ActivityTaskManager.RootTaskInfo;
Keun young Parkfb656372019-03-12 18:37:55 -070033import android.app.IActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070034import android.car.CarOccupantZoneManager;
35import android.car.CarOccupantZoneManager.OccupantTypeEnum;
36import android.car.CarOccupantZoneManager.OccupantZoneInfo;
Eric Jeong1545f3b2019-09-16 13:56:52 -070037import android.car.ICarUserService;
Felipe Leme5d5ab142020-10-27 13:49:10 -070038import android.car.drivingstate.CarUxRestrictions;
Felipe Leme56ef9ad2020-11-05 18:39:03 -080039import android.car.drivingstate.ICarUxRestrictionsChangeListener;
jovanak24470652018-09-11 17:51:57 -070040import android.car.settings.CarSettings;
Felipe Leme5528ff72020-02-10 19:05:14 -080041import android.car.user.CarUserManager;
Mayank Garg3f566582020-10-02 22:10:16 -070042import android.car.user.CarUserManager.UserIdentificationAssociationSetValue;
43import android.car.user.CarUserManager.UserIdentificationAssociationType;
Antonio Kantekc8114752020-03-05 21:37:39 -080044import android.car.user.CarUserManager.UserLifecycleEvent;
45import android.car.user.CarUserManager.UserLifecycleListener;
felipealdfdf8512020-06-01 09:35:45 -070046import android.car.user.UserCreationResult;
felipeal159a2a42020-05-08 10:32:11 -070047import android.car.user.UserIdentificationAssociationResponse;
Mayank Garga55c3092020-05-28 03:19:24 -070048import android.car.user.UserRemovalResult;
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -070049import android.car.user.UserStartResult;
bkchoid77d0bc2021-04-22 13:43:03 -070050import android.car.user.UserStopResult;
felipeale5bf0322020-04-16 15:10:57 -070051import android.car.user.UserSwitchResult;
felipeal19e3d732020-03-18 12:07:32 -070052import android.car.userlib.HalCallback;
53import android.car.userlib.UserHalHelper;
Mayank Garge90a4082020-09-30 12:57:34 -070054import android.car.userlib.UserHelper;
Mayank Garga480dd92020-05-14 03:14:57 -070055import android.content.ComponentName;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070056import android.content.Context;
Mayank Garga480dd92020-05-14 03:14:57 -070057import android.content.pm.PackageManager;
58import android.content.pm.PackageManager.NameNotFoundException;
Eric Jeong1545f3b2019-09-16 13:56:52 -070059import android.content.pm.UserInfo;
felipealdfdf8512020-06-01 09:35:45 -070060import android.content.pm.UserInfo.UserInfoFlag;
Felipe Leme315a53b2020-03-12 10:51:04 -070061import android.content.res.Resources;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070062import android.graphics.Bitmap;
felipealdfdf8512020-06-01 09:35:45 -070063import android.hardware.automotive.vehicle.V2_0.CreateUserRequest;
64import android.hardware.automotive.vehicle.V2_0.CreateUserStatus;
Mayank Garg70732a82020-08-05 20:17:47 -070065import android.hardware.automotive.vehicle.V2_0.InitialUserInfoRequestType;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080066import android.hardware.automotive.vehicle.V2_0.InitialUserInfoResponseAction;
Mayank Garga55c3092020-05-28 03:19:24 -070067import android.hardware.automotive.vehicle.V2_0.RemoveUserRequest;
Mayank Gargeb37d092020-06-02 14:37:57 -070068import android.hardware.automotive.vehicle.V2_0.SwitchUserRequest;
Mayank Garg59f22192020-03-27 00:51:45 -070069import android.hardware.automotive.vehicle.V2_0.SwitchUserStatus;
felipeal5e3ede42020-04-23 18:04:07 -070070import android.hardware.automotive.vehicle.V2_0.UserIdentificationGetRequest;
71import android.hardware.automotive.vehicle.V2_0.UserIdentificationResponse;
felipeal159a2a42020-05-08 10:32:11 -070072import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetAssociation;
73import android.hardware.automotive.vehicle.V2_0.UserIdentificationSetRequest;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080074import android.hardware.automotive.vehicle.V2_0.UsersInfo;
Ying Zheng1ab32b62018-06-26 12:47:26 -070075import android.location.LocationManager;
Eric Jeong1545f3b2019-09-16 13:56:52 -070076import android.os.Binder;
Felipe Leme5528ff72020-02-10 19:05:14 -080077import android.os.Bundle;
Antonio Kantek7236a5b2020-04-06 19:53:55 -070078import android.os.Handler;
79import android.os.HandlerThread;
Felipe Lemefaf67042021-07-08 11:24:00 -070080import android.os.IBinder;
Felipe Leme17799202020-09-03 12:55:53 -070081import android.os.Process;
Keun young Parkfb656372019-03-12 18:37:55 -070082import android.os.RemoteException;
Mayank Garg31e73042020-01-23 00:10:38 -080083import android.os.Trace;
Ying Zhengcf20f442018-06-22 16:54:51 -070084import android.os.UserHandle;
Ying Zheng8f90edb2018-06-13 12:42:31 -070085import android.os.UserManager;
jovanak24470652018-09-11 17:51:57 -070086import android.provider.Settings;
Felipe Lemee3cab982020-03-12 11:39:29 -070087import android.sysprop.CarProperties;
felipeal159a2a42020-05-08 10:32:11 -070088import android.text.TextUtils;
Felipe Lemefaf67042021-07-08 11:24:00 -070089import android.util.ArrayMap;
felipeal312416a2020-04-14 12:28:24 -070090import android.util.EventLog;
Felipe Leme176a5fd2021-01-20 15:48:33 -080091import android.util.IndentingPrintWriter;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070092import android.util.Log;
Eric Jeongf75d4132020-12-21 13:48:23 -080093import android.util.Slog;
Felipe Leme6b34fc32020-10-26 15:49:17 -070094import android.util.SparseBooleanArray;
Mayank Garg31e73042020-01-23 00:10:38 -080095import android.util.TimingsTraceLog;
Felipe Leme56ef9ad2020-11-05 18:39:03 -080096import android.view.Display;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070097
Mayank Garg72c71d22021-02-03 23:54:45 -080098import com.android.car.CarLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070099import com.android.car.CarServiceBase;
Keun young Parkb241d022020-04-20 20:31:34 -0700100import com.android.car.CarServiceUtils;
Felipe Leme5d5ab142020-10-27 13:49:10 -0700101import com.android.car.CarUxRestrictionsManagerService;
Eric Jeongc91f9452019-08-30 15:04:21 -0700102import com.android.car.R;
Felipe Leme58412202020-01-09 13:45:33 -0800103import com.android.car.hal.UserHalService;
Mayank Garg578db012021-06-14 22:17:00 -0700104import com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport;
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800105import com.android.car.internal.ICarServiceHelper;
Mayank Gargf59f95b2020-10-01 14:55:11 -0700106import com.android.car.internal.common.CommonConstants.UserLifecycleEventType;
Mayank Garg801ea6a2020-09-29 15:43:49 -0700107import com.android.car.internal.common.EventLogTags;
108import com.android.car.internal.common.UserHelperLite;
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700109import com.android.car.power.CarPowerManagementService;
Mayank Garg665c20b2020-08-07 16:19:28 -0700110import com.android.car.user.InitialUserSetter.InitialUserInfo;
Keun-young Parkd462a912019-02-11 08:53:42 -0800111import com.android.internal.annotations.GuardedBy;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700112import com.android.internal.annotations.VisibleForTesting;
felipeale5bf0322020-04-16 15:10:57 -0700113import com.android.internal.infra.AndroidFuture;
Felipe Leme5528ff72020-02-10 19:05:14 -0800114import com.android.internal.os.IResultReceiver;
felipeal5e3ede42020-04-23 18:04:07 -0700115import com.android.internal.util.ArrayUtils;
felipeal2a84d512020-04-06 18:52:15 -0700116import com.android.internal.util.FunctionalUtils;
Mayank Garge19c2922020-03-30 18:05:53 -0700117import com.android.internal.util.Preconditions;
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700118import com.android.internal.util.UserIcons;
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -0700119import com.android.server.utils.Slogf;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700120
121import java.io.PrintWriter;
Keun-young Parkd462a912019-02-11 08:53:42 -0800122import java.util.ArrayList;
felipeal2d0483c2019-11-02 14:07:22 -0700123import java.util.Arrays;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700124import java.util.Iterator;
125import java.util.List;
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000126import java.util.Objects;
Pavel Maltsev17e81832019-04-04 14:38:41 -0700127import java.util.concurrent.CopyOnWriteArrayList;
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700128import java.util.concurrent.CountDownLatch;
129import java.util.concurrent.TimeUnit;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700130
131/**
132 * User service for cars. Manages users at boot time. Including:
133 *
134 * <ol>
Eric Jeong1545f3b2019-09-16 13:56:52 -0700135 * <li> Creates a user used as driver.
136 * <li> Creates a user used as passenger.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700137 * <li> Creates a secondary admin user on first run.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700138 * <li> Switch drivers.
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700139 * <ol/>
140 */
Eric Jeong1545f3b2019-09-16 13:56:52 -0700141public final class CarUserService extends ICarUserService.Stub implements CarServiceBase {
Felipe Leme5528ff72020-02-10 19:05:14 -0800142
Mayank Garg72c71d22021-02-03 23:54:45 -0800143 private static final String TAG = CarLog.tagFor(CarUserService.class);
felipealf7368962020-04-16 12:55:19 -0700144
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800145 /** {@code int} extra used to represent a user id in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700146 public static final String BUNDLE_USER_ID = "user.id";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800147 /** {@code int} extra used to represent user flags in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700148 public static final String BUNDLE_USER_FLAGS = "user.flags";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800149 /** {@code String} extra used to represent a user name in a {@link IResultReceiver} response. */
Mayank Garg8f932822020-09-17 16:09:12 -0700150 public static final String BUNDLE_USER_NAME = "user.name";
felipeala68ecef2020-05-19 12:46:08 -0700151 /**
152 * {@code int} extra used to represent the user locales in a {@link IResultReceiver} response.
153 */
Mayank Garg8f932822020-09-17 16:09:12 -0700154 public static final String BUNDLE_USER_LOCALES = "user.locales";
felipeala68ecef2020-05-19 12:46:08 -0700155 /**
156 * {@code int} extra used to represent the info action in a {@link IResultReceiver} response.
157 */
Mayank Garg8f932822020-09-17 16:09:12 -0700158 public static final String BUNDLE_INITIAL_INFO_ACTION = "initial_info.action";
Felipe Leme5528ff72020-02-10 19:05:14 -0800159
Mayank Garg9ed099e2020-06-04 16:05:20 -0700160 public static final String VEHICLE_HAL_NOT_SUPPORTED = "Vehicle Hal not supported.";
161
Mayank Garg02576972021-02-18 16:46:07 -0800162 public static final String HANDLER_THREAD_NAME = "UserService";
163
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700164 private final Context mContext;
Keun young Parkfb656372019-03-12 18:37:55 -0700165 private final IActivityManager mAm;
Anthony Hugh9932a252019-06-12 16:19:56 -0700166 private final UserManager mUserManager;
167 private final int mMaxRunningUsers;
Mayank Garg70732a82020-08-05 20:17:47 -0700168 private final InitialUserSetter mInitialUserSetter;
Eric Jeongc91f9452019-08-30 15:04:21 -0700169 private final boolean mEnablePassengerSupport;
Mayank Garg9732d602020-08-09 21:02:40 -0700170 private final UserPreCreator mUserPreCreator;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700171
Eric Jeongc91f9452019-08-30 15:04:21 -0700172 private final Object mLockUser = new Object();
173 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800174 private boolean mUser0Unlocked;
Eric Jeongc91f9452019-08-30 15:04:21 -0700175 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800176 private final ArrayList<Runnable> mUser0UnlockTasks = new ArrayList<>();
Eric Jeongc91f9452019-08-30 15:04:21 -0700177 // Only one passenger is supported.
178 @GuardedBy("mLockUser")
179 private @UserIdInt int mLastPassengerId;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700180 /**
181 * Background users that will be restarted in garage mode. This list can include the
Mayank Garg31e73042020-01-23 00:10:38 -0800182 * current foreground user but the current foreground user should not be restarted.
Keun young Parkf3523cd2019-04-08 10:09:17 -0700183 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700184 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700185 private final ArrayList<Integer> mBackgroundUsersToRestart = new ArrayList<>();
186 /**
187 * Keep the list of background users started here. This is wholly for debugging purpose.
188 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700189 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700190 private final ArrayList<Integer> mBackgroundUsersRestartedHere = new ArrayList<>();
191
Felipe Leme58412202020-01-09 13:45:33 -0800192 private final UserHalService mHal;
193
Keun young Parkb241d022020-04-20 20:31:34 -0700194 private final HandlerThread mHandlerThread = CarServiceUtils.getHandlerThread(
Mayank Garg02576972021-02-18 16:46:07 -0800195 HANDLER_THREAD_NAME);
196 private final Handler mHandler;
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700197
Felipe Leme5528ff72020-02-10 19:05:14 -0800198 /**
Felipe Lemefaf67042021-07-08 11:24:00 -0700199 * Internal listeners to be notified on new user activities events.
200 *
201 * <p>This collection should be accessed and manipulated by {@code mHandlerThread} only.
Antonio Kantekc8114752020-03-05 21:37:39 -0800202 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700203 private final List<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>();
Antonio Kantekc8114752020-03-05 21:37:39 -0800204
205 /**
Felipe Lemefaf67042021-07-08 11:24:00 -0700206 * App listeners to be notified on new user activities events.
207 *
208 * <p>This collection should be accessed and manipulated by {@code mHandlerThread} only.
Felipe Leme5528ff72020-02-10 19:05:14 -0800209 */
Felipe Lemefaf67042021-07-08 11:24:00 -0700210 private final ArrayMap<IBinder, AppLifecycleListener> mAppLifecycleListeners =
211 new ArrayMap<>();
Felipe Leme5528ff72020-02-10 19:05:14 -0800212
Mayank Garg7a114c82020-04-08 21:25:06 -0700213 /**
214 * User Id for the user switch in process, if any.
215 */
216 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700217 private int mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg7a114c82020-04-08 21:25:06 -0700218 /**
219 * Request Id for the user switch in process, if any.
220 */
221 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700222 private int mRequestIdForUserSwitchInProcess;
Felipe Lemee3cab982020-03-12 11:39:29 -0700223 private final int mHalTimeoutMs = CarProperties.user_hal_timeout().orElse(5_000);
224
Eric Jeongc91f9452019-08-30 15:04:21 -0700225 private final CopyOnWriteArrayList<PassengerCallback> mPassengerCallbacks =
226 new CopyOnWriteArrayList<>();
227
Mayank Garg7e1450b2020-08-07 18:15:15 -0700228 // TODO(b/163566866): Use mSwitchGuestUserBeforeSleep for new create guest request
229 private final boolean mSwitchGuestUserBeforeSleep;
230
felipeal61ce3732020-04-03 11:01:00 -0700231 @Nullable
232 @GuardedBy("mLockUser")
233 private UserInfo mInitialUser;
234
Mayank Garg587f1942020-05-06 01:41:34 -0700235 private IResultReceiver mUserSwitchUiReceiver;
236
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800237 private final CarUxRestrictionsManagerService mCarUxRestrictionService;
238
239 /**
240 * Whether some operations - like user switch - are restricted by driving safety constraints.
241 */
242 @GuardedBy("mLockUser")
243 private boolean mUxRestricted;
244
245 /**
Mayank Garg784a0862021-05-26 00:20:50 -0700246 * If {@code false}, garage mode operations (background users start at garage mode entry and
247 * background users stop at garage mode exit) will be skipped. Controlled using car shell
248 * command {@code adb shell set-start-bg-users-on-garage-mode [true|false]}
249 * Purpose: Garage mode testing and simulation
250 */
251 @GuardedBy("mLockUser")
252 private boolean mStartBackgroundUsersOnGarageMode = true;
253
254 /**
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800255 * Callback to notify {@code CarServiceHelper} about driving safety changes (through
256 * {@link ICarServiceHelper#setSafetyMode(boolean).
257 *
258 * <p>NOTE: in theory, that logic should belong to {@code CarDevicePolicyService}, but it's
259 * simpler to do it here (and that service already depends on this one).
260 */
261 @GuardedBy("mLockUser")
262 private ICarServiceHelper mICarServiceHelper;
263
264 private final ICarUxRestrictionsChangeListener mCarUxRestrictionsChangeListener =
265 new ICarUxRestrictionsChangeListener.Stub() {
266 @Override
267 public void onUxRestrictionsChanged(CarUxRestrictions restrictions) {
268 setUxRestrictions(restrictions);
269 }
270 };
Felipe Leme5d5ab142020-10-27 13:49:10 -0700271
Eric Jeongc91f9452019-08-30 15:04:21 -0700272 /** Interface for callbaks related to passenger activities. */
273 public interface PassengerCallback {
274 /** Called when passenger is started at a certain zone. */
275 void onPassengerStarted(@UserIdInt int passengerId, int zoneId);
276 /** Called when passenger is stopped. */
277 void onPassengerStopped(@UserIdInt int passengerId);
278 }
279
280 /** Interface for delegating zone-related implementation to CarOccupantZoneService. */
281 public interface ZoneUserBindingHelper {
282 /** Gets occupant zones corresponding to the occupant type. */
283 @NonNull
284 List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType);
285 /** Assigns the user to the occupant zone. */
286 boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId);
287 /** Makes the occupant zone unoccupied. */
288 boolean unassignUserFromOccupantZone(@UserIdInt int userId);
289 /** Returns whether there is a passenger display. */
290 boolean isPassengerDisplayAvailable();
291 }
292
293 private final Object mLockHelper = new Object();
294 @GuardedBy("mLockHelper")
295 private ZoneUserBindingHelper mZoneUserBindingHelper;
296
Felipe Leme6b34fc32020-10-26 15:49:17 -0700297 /** Map used to avoid calling UserHAL when a user was removed because HAL creation failed. */
298 @GuardedBy("mLockUser")
299 private final SparseBooleanArray mFailedToCreateUserIds = new SparseBooleanArray(1);
300
Felipe Leme58412202020-01-09 13:45:33 -0800301 public CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garge90a4082020-09-30 12:57:34 -0700302 @NonNull UserManager userManager,
Felipe Leme5d5ab142020-10-27 13:49:10 -0700303 @NonNull IActivityManager am, int maxRunningUsers,
304 @NonNull CarUxRestrictionsManagerService uxRestrictionService) {
Mayank Garge90a4082020-09-30 12:57:34 -0700305 this(context, hal, userManager, am, maxRunningUsers,
Mayank Garg02576972021-02-18 16:46:07 -0800306 /* initialUserSetter= */ null, /* userPreCreator= */ null, uxRestrictionService,
307 null);
Mayank Garg71661ea2020-04-29 01:25:03 -0700308 }
309
310 @VisibleForTesting
311 CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garge90a4082020-09-30 12:57:34 -0700312 @NonNull UserManager userManager,
Mayank Gargccad8062020-08-30 15:05:10 -0700313 @NonNull IActivityManager am, int maxRunningUsers,
Mayank Garg1bb1c382020-09-03 17:11:11 -0700314 @Nullable InitialUserSetter initialUserSetter,
Felipe Leme5d5ab142020-10-27 13:49:10 -0700315 @Nullable UserPreCreator userPreCreator,
Mayank Garg02576972021-02-18 16:46:07 -0800316 @NonNull CarUxRestrictionsManagerService uxRestrictionService,
317 @Nullable Handler handler) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800318 if (Log.isLoggable(TAG, Log.DEBUG)) {
Felipe Leme8725a2f2020-12-09 16:04:51 -0800319 Slog.d(TAG, "constructed for user " + context.getUserId());
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700320 }
321 mContext = context;
Felipe Leme58412202020-01-09 13:45:33 -0800322 mHal = hal;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700323 mAm = am;
324 mMaxRunningUsers = maxRunningUsers;
Anthony Hugh9932a252019-06-12 16:19:56 -0700325 mUserManager = userManager;
Eric Jeongc91f9452019-08-30 15:04:21 -0700326 mLastPassengerId = UserHandle.USER_NULL;
Mayank Garg02576972021-02-18 16:46:07 -0800327 mHandler = handler == null ? new Handler(mHandlerThread.getLooper()) : handler;
Mayank Garg1bb1c382020-09-03 17:11:11 -0700328 mInitialUserSetter =
Felipe Lemecceb2992020-11-18 18:22:44 -0800329 initialUserSetter == null ? new InitialUserSetter(context, this,
330 (u) -> setInitialUser(u)) : initialUserSetter;
Mayank Garg1bb1c382020-09-03 17:11:11 -0700331 mUserPreCreator =
332 userPreCreator == null ? new UserPreCreator(mUserManager) : userPreCreator;
Mayank Garg7e1450b2020-08-07 18:15:15 -0700333 Resources resources = context.getResources();
334 mEnablePassengerSupport = resources.getBoolean(R.bool.enablePassengerSupport);
335 mSwitchGuestUserBeforeSleep = resources.getBoolean(
336 R.bool.config_switchGuestUserBeforeGoingSleep);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800337 mCarUxRestrictionService = uxRestrictionService;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700338 }
339
340 @Override
341 public void init() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800342 if (Log.isLoggable(TAG, Log.DEBUG)) {
343 Slog.d(TAG, "init()");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700344 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800345 mCarUxRestrictionService.registerUxRestrictionsChangeListener(
346 mCarUxRestrictionsChangeListener, Display.DEFAULT_DISPLAY);
347
348 setUxRestrictions(mCarUxRestrictionService.getCurrentUxRestrictions());
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700349 }
350
351 @Override
352 public void release() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800353 if (Log.isLoggable(TAG, Log.DEBUG)) {
354 Slog.d(TAG, "release()");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700355 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800356 mCarUxRestrictionService
357 .unregisterUxRestrictionsChangeListener(mCarUxRestrictionsChangeListener);
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700358 }
359
360 @Override
Mayank Garg578db012021-06-14 22:17:00 -0700361 @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
Felipe Leme176a5fd2021-01-20 15:48:33 -0800362 public void dump(@NonNull IndentingPrintWriter writer) {
Felipe Leme55236722020-10-16 16:54:32 -0700363 checkHasDumpPermissionGranted("dump()");
364
Eric Jeong1545f3b2019-09-16 13:56:52 -0700365 writer.println("*CarUserService*");
Felipe Lemefaf67042021-07-08 11:24:00 -0700366 handleDumpListeners(writer);
Mayank Garg587f1942020-05-06 01:41:34 -0700367 writer.printf("User switch UI receiver %s\n", mUserSwitchUiReceiver);
Eric Jeongc91f9452019-08-30 15:04:21 -0700368 synchronized (mLockUser) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700369 writer.println("User0Unlocked: " + mUser0Unlocked);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700370 writer.println("BackgroundUsersToRestart: " + mBackgroundUsersToRestart);
371 writer.println("BackgroundUsersRestarted: " + mBackgroundUsersRestartedHere);
Felipe Leme6b34fc32020-10-26 15:49:17 -0700372 if (mFailedToCreateUserIds.size() > 0) {
373 writer.println("FailedToCreateUserIds: " + mFailedToCreateUserIds);
374 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800375 writer.printf("Is UX restricted: %b\n", mUxRestricted);
Mayank Garg784a0862021-05-26 00:20:50 -0700376 writer.printf("Start Background Users On Garage Mode=%s\n",
377 mStartBackgroundUsersOnGarageMode);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700378 }
Mayank Garg02576972021-02-18 16:46:07 -0800379
380 writer.println("SwitchGuestUserBeforeSleep: " + mSwitchGuestUserBeforeSleep);
Mayank Garg02576972021-02-18 16:46:07 -0800381
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700382 writer.println("MaxRunningUsers: " + mMaxRunningUsers);
383 List<UserInfo> allDrivers = getAllDrivers();
384 int driversSize = allDrivers.size();
385 writer.println("NumberOfDrivers: " + driversSize);
Felipe Lemefaf67042021-07-08 11:24:00 -0700386 writer.increaseIndent();
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700387 for (int i = 0; i < driversSize; i++) {
388 int driverId = allDrivers.get(i).id;
Felipe Lemefaf67042021-07-08 11:24:00 -0700389 writer.printf("#%d: id=%d", i, driverId);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700390 List<UserInfo> passengers = getPassengers(driverId);
391 int passengersSize = passengers.size();
392 writer.print(" NumberPassengers: " + passengersSize);
393 if (passengersSize > 0) {
394 writer.print(" [");
395 for (int j = 0; j < passengersSize; j++) {
396 writer.print(passengers.get(j).id);
397 if (j < passengersSize - 1) {
398 writer.print(" ");
felipeal2d0483c2019-11-02 14:07:22 -0700399 }
felipeal2d0483c2019-11-02 14:07:22 -0700400 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700401 writer.print("]");
felipeal2d0483c2019-11-02 14:07:22 -0700402 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700403 writer.println();
404 }
Felipe Lemefaf67042021-07-08 11:24:00 -0700405 writer.decreaseIndent();
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700406 writer.printf("EnablePassengerSupport: %s\n", mEnablePassengerSupport);
407 writer.printf("User HAL timeout: %dms\n", mHalTimeoutMs);
408 writer.printf("Initial user: %s\n", mInitialUser);
felipealbf327652020-06-03 11:33:29 -0700409
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700410 writer.println("Relevant overlayable properties");
411 Resources res = mContext.getResources();
Felipe Lemefaf67042021-07-08 11:24:00 -0700412 writer.increaseIndent();
413 writer.printf("owner_name=%s\n", res.getString(com.android.internal.R.string.owner_name));
414 writer.printf("default_guest_name=%s\n", res.getString(R.string.default_guest_name));
415 writer.decreaseIndent();
felipealf7368962020-04-16 12:55:19 -0700416 writer.printf("User switch in process=%d\n", mUserIdForUserSwitchInProcess);
Mayank Garg7a114c82020-04-08 21:25:06 -0700417 writer.printf("Request Id for the user switch in process=%d\n ",
418 mRequestIdForUserSwitchInProcess);
Mayank Garga480dd92020-05-14 03:14:57 -0700419 writer.printf("System UI package name=%s\n", getSystemUiPackageName());
felipeale8c5dce2020-04-15 11:27:06 -0700420
felipealbf327652020-06-03 11:33:29 -0700421 writer.println("Relevant Global settings");
Felipe Lemefaf67042021-07-08 11:24:00 -0700422 writer.increaseIndent();
423 dumpGlobalProperty(writer, CarSettings.Global.LAST_ACTIVE_USER_ID);
424 dumpGlobalProperty(writer, CarSettings.Global.LAST_ACTIVE_PERSISTENT_USER_ID);
425 writer.decreaseIndent();
felipealbf327652020-06-03 11:33:29 -0700426
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700427 mInitialUserSetter.dump(writer);
felipeale8c5dce2020-04-15 11:27:06 -0700428 }
429
Felipe Lemefaf67042021-07-08 11:24:00 -0700430 private void dumpGlobalProperty(IndentingPrintWriter writer, String property) {
felipealbf327652020-06-03 11:33:29 -0700431 String value = Settings.Global.getString(mContext.getContentResolver(), property);
Felipe Lemefaf67042021-07-08 11:24:00 -0700432 writer.printf("%s=%s\n", property, value);
felipealbf327652020-06-03 11:33:29 -0700433 }
434
Felipe Lemefaf67042021-07-08 11:24:00 -0700435 private void handleDumpListeners(IndentingPrintWriter writer) {
436 writer.increaseIndent();
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700437 CountDownLatch latch = new CountDownLatch(1);
438 mHandler.post(() -> {
felipealde1e16d2020-06-03 13:20:48 -0700439 handleDumpServiceLifecycleListeners(writer);
Felipe Lemefaf67042021-07-08 11:24:00 -0700440 handleDumpAppLifecycleListeners(writer);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700441 latch.countDown();
442 });
443 int timeout = 5;
444 try {
445 if (!latch.await(timeout, TimeUnit.SECONDS)) {
446 writer.printf("Handler thread didn't respond in %ds when dumping listeners\n",
447 timeout);
448 }
449 } catch (InterruptedException e) {
450 Thread.currentThread().interrupt();
451 writer.println("Interrupted waiting for handler thread to dump app and user listeners");
452 }
Felipe Lemefaf67042021-07-08 11:24:00 -0700453 writer.decreaseIndent();
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700454 }
455
Felipe Lemefaf67042021-07-08 11:24:00 -0700456 private void handleDumpServiceLifecycleListeners(PrintWriter writer) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700457 if (mUserLifecycleListeners.isEmpty()) {
felipealde1e16d2020-06-03 13:20:48 -0700458 writer.println("No lifecycle listeners for internal services");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700459 return;
460 }
felipealde1e16d2020-06-03 13:20:48 -0700461 int size = mUserLifecycleListeners.size();
462 writer.printf("%d lifecycle listener%s for services\n", size, size == 1 ? "" : "s");
463 String indent = " ";
Felipe Lemefaf67042021-07-08 11:24:00 -0700464 for (int i = 0; i < size; i++) {
465 UserLifecycleListener listener = mUserLifecycleListeners.get(i);
felipealde1e16d2020-06-03 13:20:48 -0700466 writer.printf("%s%s\n", indent, FunctionalUtils.getLambdaName(listener));
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700467 }
468 }
469
Felipe Lemefaf67042021-07-08 11:24:00 -0700470 private void handleDumpAppLifecycleListeners(IndentingPrintWriter writer) {
felipealde1e16d2020-06-03 13:20:48 -0700471 int size = mAppLifecycleListeners.size();
472 if (size == 0) {
473 writer.println("No lifecycle listeners for apps");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700474 return;
475 }
Felipe Lemefaf67042021-07-08 11:24:00 -0700476 writer.printf("%d lifecycle listener%s for apps\n", size, size == 1 ? "" : "s");
477 writer.increaseIndent();
felipealde1e16d2020-06-03 13:20:48 -0700478 for (int i = 0; i < size; i++) {
Felipe Lemefaf67042021-07-08 11:24:00 -0700479 mAppLifecycleListeners.valueAt(i).dump(writer);
Keun-young Parkd462a912019-02-11 08:53:42 -0800480 }
Felipe Lemefaf67042021-07-08 11:24:00 -0700481 writer.decreaseIndent();
Eric Jeong1545f3b2019-09-16 13:56:52 -0700482 }
483
484 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700485 * @see ExperimentalCarUserManager.createDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700486 */
487 @Override
Yan Zhu65a0acd2021-06-21 10:56:53 -0700488 @ExcludeFromCodeCoverageGeneratedReport(reason = DEPRECATED_CODE,
489 details = "TODO(b/172262561) remove annotation after refactoring")
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700490 public AndroidFuture<UserCreationResult> createDriver(@NonNull String name, boolean admin) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700491 checkManageUsersPermission("createDriver");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000492 Objects.requireNonNull(name, "name cannot be null");
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700493
494 AndroidFuture<UserCreationResult> future = new AndroidFuture<UserCreationResult>() {
495 @Override
496 protected void onCompleted(UserCreationResult result, Throwable err) {
497 if (result == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800498 Slog.w(TAG, "createDriver(" + name + "," + admin + ") failed: " + err);
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700499 } else {
500 if (result.getStatus() == UserCreationResult.STATUS_SUCCESSFUL) {
501 assignDefaultIcon(result.getUser());
502 }
503 }
504 super.onCompleted(result, err);
505 };
506 };
507 int flags = 0;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700508 if (admin) {
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700509 if (!(mUserManager.isAdminUser() || mUserManager.isSystemUser())) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800510 Slog.e(TAG, "Only admin users and system user can create other admins.");
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700511 sendUserCreationResultFailure(future, UserCreationResult.STATUS_INVALID_REQUEST);
512 return future;
513 }
514 flags = UserInfo.FLAG_ADMIN;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700515 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700516 createUser(name, UserInfo.getDefaultUserType(flags), flags, mHalTimeoutMs, future);
517 return future;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700518 }
519
520 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700521 * @see ExperimentalCarUserManager.createPassenger
Eric Jeong1545f3b2019-09-16 13:56:52 -0700522 */
523 @Override
524 @Nullable
Yan Zhu65a0acd2021-06-21 10:56:53 -0700525 @ExcludeFromCodeCoverageGeneratedReport(reason = DEPRECATED_CODE,
526 details = "TODO(b/172262561) remove annotation after refactoring")
Eric Jeong1545f3b2019-09-16 13:56:52 -0700527 public UserInfo createPassenger(@NonNull String name, @UserIdInt int driverId) {
528 checkManageUsersPermission("createPassenger");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000529 Objects.requireNonNull(name, "name cannot be null");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700530 UserInfo driver = mUserManager.getUserInfo(driverId);
531 if (driver == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800532 Slog.w(TAG, "the driver is invalid");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700533 return null;
534 }
535 if (driver.isGuest()) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800536 Slog.w(TAG, "a guest driver cannot create a passenger");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700537 return null;
538 }
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700539 // createPassenger doesn't use user HAL because user HAL doesn't support profile user yet.
Bookatz42fb1a62019-10-30 11:45:01 -0700540 UserInfo user = mUserManager.createProfileForUser(name,
541 UserManager.USER_TYPE_PROFILE_MANAGED, /* flags */ 0, driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700542 if (user == null) {
543 // Couldn't create user, most likely because there are too many.
Eric Jeongf75d4132020-12-21 13:48:23 -0800544 Slog.w(TAG, "can't create a profile for user" + driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700545 return null;
546 }
547 // Passenger user should be a non-admin user.
Mayank Garge90a4082020-09-30 12:57:34 -0700548 UserHelper.setDefaultNonAdminRestrictions(mContext, user, /* enable= */ true);
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700549 assignDefaultIcon(user);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700550 return user;
551 }
552
553 /**
Eric Jeongb2dc6ff2020-06-05 17:00:26 -0700554 * @see ExperimentalCarUserManager.switchDriver
Eric Jeong1545f3b2019-09-16 13:56:52 -0700555 */
556 @Override
Yan Zhu65a0acd2021-06-21 10:56:53 -0700557 @ExcludeFromCodeCoverageGeneratedReport(reason = DEPRECATED_CODE,
558 details = "TODO(b/172262561) remove annotation after refactoring")
Eric Jeong25666cf2020-05-14 15:16:27 -0700559 public void switchDriver(@UserIdInt int driverId, AndroidFuture<UserSwitchResult> receiver) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700560 checkManageUsersPermission("switchDriver");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700561 if (UserHelperLite.isHeadlessSystemUser(driverId)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700562 // System user doesn't associate with real person, can not be switched to.
Eric Jeongf75d4132020-12-21 13:48:23 -0800563 Slog.w(TAG, "switching to system user in headless system user mode is not allowed");
felipealdfdf8512020-06-01 09:35:45 -0700564 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700565 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700566 }
567 int userSwitchable = mUserManager.getUserSwitchability();
568 if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800569 Slog.w(TAG, "current process is not allowed to switch user");
felipealdfdf8512020-06-01 09:35:45 -0700570 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_INVALID_REQUEST);
Eric Jeong25666cf2020-05-14 15:16:27 -0700571 return;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700572 }
Eric Jeong25666cf2020-05-14 15:16:27 -0700573 switchUser(driverId, mHalTimeoutMs, receiver);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700574 }
575
576 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800577 * Returns all drivers who can occupy the driving zone. Guest users are included in the list.
578 *
579 * @return the list of {@link UserInfo} who can be a driver on the device.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700580 */
581 @Override
582 @NonNull
583 public List<UserInfo> getAllDrivers() {
felipeal2d0483c2019-11-02 14:07:22 -0700584 checkManageUsersOrDumpPermission("getAllDrivers");
Mayank Garg94f3eb92020-08-12 12:38:58 -0700585 return getUsers((user) -> !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700586 && !user.isManagedProfile() && !user.isEphemeral());
Eric Jeong1545f3b2019-09-16 13:56:52 -0700587 }
588
589 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800590 * Returns all passengers under the given driver.
591 *
592 * @param driverId User id of a driver.
593 * @return the list of {@link UserInfo} who is a passenger under the given driver.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700594 */
595 @Override
596 @NonNull
597 public List<UserInfo> getPassengers(@UserIdInt int driverId) {
felipeal2d0483c2019-11-02 14:07:22 -0700598 checkManageUsersOrDumpPermission("getPassengers");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700599 return getUsers((user) -> {
Mayank Garg94f3eb92020-08-12 12:38:58 -0700600 return !UserHelperLite.isHeadlessSystemUser(user.id) && user.isEnabled()
Eric Jeong40f8fa32020-05-12 12:23:33 -0700601 && user.isManagedProfile() && user.profileGroupId == driverId;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700602 });
603 }
604
605 /**
606 * @see CarUserManager.startPassenger
607 */
608 @Override
609 public boolean startPassenger(@UserIdInt int passengerId, int zoneId) {
610 checkManageUsersPermission("startPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700611 synchronized (mLockUser) {
612 try {
613 if (!mAm.startUserInBackgroundWithListener(passengerId, null)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800614 Slog.w(TAG, "could not start passenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700615 return false;
616 }
617 } catch (RemoteException e) {
618 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -0800619 Slog.w(TAG, "error while starting passenger", e);
Eric Jeongc91f9452019-08-30 15:04:21 -0700620 return false;
621 }
622 if (!assignUserToOccupantZone(passengerId, zoneId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800623 Slog.w(TAG, "could not assign passenger to zone");
Eric Jeongc91f9452019-08-30 15:04:21 -0700624 return false;
625 }
626 mLastPassengerId = passengerId;
627 }
628 for (PassengerCallback callback : mPassengerCallbacks) {
629 callback.onPassengerStarted(passengerId, zoneId);
630 }
631 return true;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700632 }
633
634 /**
635 * @see CarUserManager.stopPassenger
636 */
637 @Override
638 public boolean stopPassenger(@UserIdInt int passengerId) {
639 checkManageUsersPermission("stopPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700640 return stopPassengerInternal(passengerId, true);
641 }
642
643 private boolean stopPassengerInternal(@UserIdInt int passengerId, boolean checkCurrentDriver) {
644 synchronized (mLockUser) {
645 UserInfo passenger = mUserManager.getUserInfo(passengerId);
646 if (passenger == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800647 Slog.w(TAG, "passenger " + passengerId + " doesn't exist");
Eric Jeongc91f9452019-08-30 15:04:21 -0700648 return false;
649 }
650 if (mLastPassengerId != passengerId) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800651 Slog.w(TAG, "passenger " + passengerId + " hasn't been started");
Eric Jeongc91f9452019-08-30 15:04:21 -0700652 return true;
653 }
654 if (checkCurrentDriver) {
655 int currentUser = ActivityManager.getCurrentUser();
656 if (passenger.profileGroupId != currentUser) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800657 Slog.w(TAG, "passenger " + passengerId
Eric Jeongc91f9452019-08-30 15:04:21 -0700658 + " is not a profile of the current user");
659 return false;
660 }
661 }
662 // Passenger is a profile, so cannot be stopped through activity manager.
663 // Instead, activities started by the passenger are stopped and the passenger is
664 // unassigned from the zone.
665 stopAllTasks(passengerId);
666 if (!unassignUserFromOccupantZone(passengerId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800667 Slog.w(TAG, "could not unassign user from occupant zone");
Eric Jeongc91f9452019-08-30 15:04:21 -0700668 return false;
669 }
670 mLastPassengerId = UserHandle.USER_NULL;
671 }
672 for (PassengerCallback callback : mPassengerCallbacks) {
673 callback.onPassengerStopped(passengerId);
674 }
675 return true;
676 }
677
678 private void stopAllTasks(@UserIdInt int userId) {
679 try {
Louis Chang3bf2f202020-08-18 13:04:28 +0800680 for (RootTaskInfo info : mAm.getAllRootTaskInfos()) {
681 for (int i = 0; i < info.childTaskIds.length; i++) {
682 if (info.childTaskUserIds[i] == userId) {
683 int taskId = info.childTaskIds[i];
Eric Jeongc91f9452019-08-30 15:04:21 -0700684 if (!mAm.removeTask(taskId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800685 Slog.w(TAG, "could not remove task " + taskId);
Eric Jeongc91f9452019-08-30 15:04:21 -0700686 }
687 }
688 }
689 }
690 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800691 Slog.e(TAG, "could not get stack info", e);
Eric Jeongc91f9452019-08-30 15:04:21 -0700692 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700693 }
694
Felipe Leme5528ff72020-02-10 19:05:14 -0800695 @Override
Felipe Lemefaf67042021-07-08 11:24:00 -0700696 public void setLifecycleListenerForApp(String packageName, IResultReceiver receiver) {
Felipe Leme5528ff72020-02-10 19:05:14 -0800697 int uid = Binder.getCallingUid();
Felipe Lemefaf67042021-07-08 11:24:00 -0700698 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_LIFECYCLE_LISTENER, uid, packageName);
699 checkInteractAcrossUsersPermission("setLifecycleListenerForApp-" + uid + "-" + packageName);
Felipe Leme5528ff72020-02-10 19:05:14 -0800700
Felipe Lemefaf67042021-07-08 11:24:00 -0700701 IBinder receiverBinder = receiver.asBinder();
Felipe Leme11a82462021-07-14 16:14:13 -0700702 AppLifecycleListener listener = new AppLifecycleListener(uid, packageName, receiver,
703 (l) -> onListenerDeath(l));
Felipe Lemefaf67042021-07-08 11:24:00 -0700704 Slogf.d(TAG, "Adding %s (using binder %s)", listener, receiverBinder);
Felipe Lemefaf67042021-07-08 11:24:00 -0700705 mHandler.post(() -> mAppLifecycleListeners.put(receiverBinder, listener));
Felipe Leme5528ff72020-02-10 19:05:14 -0800706 }
707
Felipe Lemefaf67042021-07-08 11:24:00 -0700708 private void onListenerDeath(AppLifecycleListener listener) {
709 Slogf.i(TAG, "Removing listener %s on binder death", listener);
710 mHandler.post(() -> mAppLifecycleListeners.remove(listener.receiver.asBinder()));
Felipe Leme5528ff72020-02-10 19:05:14 -0800711 }
712
713 @Override
Felipe Lemefaf67042021-07-08 11:24:00 -0700714 public void resetLifecycleListenerForApp(IResultReceiver receiver) {
Felipe Leme5528ff72020-02-10 19:05:14 -0800715 int uid = Binder.getCallingUid();
Felipe Lemefaf67042021-07-08 11:24:00 -0700716 checkInteractAcrossUsersPermission("resetLifecycleListenerForApp-" + uid);
717 IBinder receiverBinder = receiver.asBinder();
718 mHandler.post(() -> {
719 AppLifecycleListener listener = mAppLifecycleListeners.get(receiverBinder);
720 if (listener == null) {
721 Slogf.e(TAG, "resetLifecycleListenerForApp(uid=%d): no listener for receiver", uid);
722 return;
723 }
724 if (listener.uid != uid) {
725 Slogf.e(TAG, "resetLifecycleListenerForApp(): uid mismatch (called by %d) for "
726 + "listener %s", uid, listener);
727 }
728 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_RESET_LIFECYCLE_LISTENER, uid,
729 listener.packageName);
730 Slogf.d(TAG, "Removing %s (using binder %s)", listener, receiverBinder);
731 mAppLifecycleListeners.remove(receiverBinder);
Felipe Leme11a82462021-07-14 16:14:13 -0700732
733 listener.onDestroy();
Felipe Lemefaf67042021-07-08 11:24:00 -0700734 });
Felipe Leme5528ff72020-02-10 19:05:14 -0800735 }
736
Felipe Lemee3cab982020-03-12 11:39:29 -0700737 /**
felipeal61ce3732020-04-03 11:01:00 -0700738 * Gets the initial foreground user after the device boots or resumes from suspension.
739 *
740 * <p>When the OEM supports the User HAL, the initial user won't be available until the HAL
741 * returns the initial value to {@code CarService} - if HAL takes too long or times out, this
742 * method returns {@code null}.
743 *
744 * <p>If the HAL eventually times out, {@code CarService} will fallback to its default behavior
745 * (like switching to the last active user), and this method will return the result of such
746 * operation.
747 *
748 * <p>Notice that if {@code CarService} crashes, subsequent calls to this method will return
749 * {@code null}.
750 *
751 * @hide
752 */
753 @Nullable
754 public UserInfo getInitialUser() {
755 checkInteractAcrossUsersPermission("getInitialUser");
756 synchronized (mLockUser) {
757 return mInitialUser;
758 }
759 }
760
felipeal61ce3732020-04-03 11:01:00 -0700761 /**
762 * Sets the initial foreground user after the device boots or resumes from suspension.
763 */
764 public void setInitialUser(@Nullable UserInfo user) {
felipeal312416a2020-04-14 12:28:24 -0700765 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_INITIAL_USER,
766 user == null ? UserHandle.USER_NULL : user.id);
felipeal61ce3732020-04-03 11:01:00 -0700767 synchronized (mLockUser) {
768 mInitialUser = user;
769 }
770 if (user == null) {
771 // This mean InitialUserSetter failed and could not fallback, so the initial user was
772 // not switched (and most likely is SYSTEM_USER).
773 // TODO(b/153104378): should we set it to ActivityManager.getCurrentUser() instead?
Eric Jeongf75d4132020-12-21 13:48:23 -0800774 Slog.wtf(TAG, "Initial user set to null");
felipeal61ce3732020-04-03 11:01:00 -0700775 }
776 }
777
Mayank Garg7e1450b2020-08-07 18:15:15 -0700778 private void initResumeReplaceGuest() {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700779 int currentUserId = ActivityManager.getCurrentUser();
780 UserInfo currentUser = mUserManager.getUserInfo(currentUserId);
781
782 if (!mInitialUserSetter.canReplaceGuestUser(currentUser)) return; // Not a guest
783
784 InitialUserInfo info =
785 new InitialUserSetter.Builder(InitialUserSetter.TYPE_REPLACE_GUEST).build();
786
787 mInitialUserSetter.set(info);
788 }
789
790 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700791 * Calls to switch user at the power suspend.
Mayank Garg7e1450b2020-08-07 18:15:15 -0700792 *
793 * <p><b>Note:</b> Should be used only by {@link CarPowerManagementService}
794 *
Mayank Garg7e1450b2020-08-07 18:15:15 -0700795 */
Mayank Garg0baf88a2020-08-30 21:57:36 -0700796 public void onSuspend() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800797 if (Log.isLoggable(TAG, Log.DEBUG)) {
798 Slog.d(TAG, "onSuspend called.");
Mayank Garg7e1450b2020-08-07 18:15:15 -0700799 }
800
Mayank Garg0baf88a2020-08-30 21:57:36 -0700801 if (mSwitchGuestUserBeforeSleep) {
802 initResumeReplaceGuest();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700803 }
Mayank Garg1bb1c382020-09-03 17:11:11 -0700804
Mayank Garga3b72d02021-03-14 23:05:51 -0700805 preCreateUsersInternal();
Mayank Garg7e1450b2020-08-07 18:15:15 -0700806 }
807
808 /**
Mayank Garg0baf88a2020-08-30 21:57:36 -0700809 * Calls to switch user at the power resume.
810 *
811 * <p>
812 * <b>Note:</b> Should be used only by {@link CarPowerManagementService}
813 *
814 */
815 public void onResume() {
Eric Jeongf75d4132020-12-21 13:48:23 -0800816 if (Log.isLoggable(TAG, Log.DEBUG)) {
817 Slog.d(TAG, "onResume called.");
Mayank Garg0baf88a2020-08-30 21:57:36 -0700818 }
819
Mayank Garg02576972021-02-18 16:46:07 -0800820 mHandler.post(() -> initBootUser(InitialUserInfoRequestType.RESUME));
Mayank Garg0baf88a2020-08-30 21:57:36 -0700821 }
822
823 /**
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700824 * Calls to start user at the android startup.
Mayank Garg70732a82020-08-05 20:17:47 -0700825 */
826 public void initBootUser() {
Mayank Garg02576972021-02-18 16:46:07 -0800827 mHandler.post(() -> initBootUser(getInitialUserInfoRequestType()));
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700828 }
829
Mayank Garg7e1450b2020-08-07 18:15:15 -0700830 private void initBootUser(int requestType) {
831 boolean replaceGuest =
832 requestType == InitialUserInfoRequestType.RESUME && !mSwitchGuestUserBeforeSleep;
Mayank Garg70732a82020-08-05 20:17:47 -0700833 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ, requestType,
834 mHalTimeoutMs);
835 checkManageUsersPermission("startInitialUser");
836
837 if (!isUserHalSupported()) {
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700838 fallbackToDefaultInitialUserBehavior(/* userLocales= */ null, replaceGuest);
Mayank Gargfd1e0692021-05-25 13:33:48 -0700839 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ_COMPLETE,
840 requestType);
Mayank Garg70732a82020-08-05 20:17:47 -0700841 return;
842 }
843
844 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
845 mHal.getInitialUserInfo(requestType, mHalTimeoutMs, usersInfo, (status, resp) -> {
846 if (resp != null) {
847 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP,
848 status, resp.action, resp.userToSwitchOrCreate.userId,
849 resp.userToSwitchOrCreate.flags, resp.userNameToCreate, resp.userLocales);
850
851 String userLocales = resp.userLocales;
852 InitialUserInfo info;
853 switch (resp.action) {
854 case InitialUserInfoResponseAction.SWITCH:
855 int userId = resp.userToSwitchOrCreate.userId;
856 if (userId <= 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800857 Slog.w(TAG, "invalid (or missing) user id sent by HAL: " + userId);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700858 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700859 break;
860 }
861 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_SWITCH)
862 .setUserLocales(userLocales)
863 .setSwitchUserId(userId)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700864 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700865 .build();
866 mInitialUserSetter.set(info);
867 break;
868
869 case InitialUserInfoResponseAction.CREATE:
870 int halFlags = resp.userToSwitchOrCreate.flags;
871 String userName = resp.userNameToCreate;
872 info = new InitialUserSetter.Builder(InitialUserSetter.TYPE_CREATE)
873 .setUserLocales(userLocales)
874 .setNewUserName(userName)
875 .setNewUserFlags(halFlags)
876 .build();
877 mInitialUserSetter.set(info);
878 break;
879
880 case InitialUserInfoResponseAction.DEFAULT:
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700881 fallbackToDefaultInitialUserBehavior(userLocales, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700882 break;
883 default:
Eric Jeongf75d4132020-12-21 13:48:23 -0800884 Slog.w(TAG, "invalid response action on " + resp);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700885 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700886 break;
887
888 }
889 } else {
890 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP, status);
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700891 fallbackToDefaultInitialUserBehavior(/* user locale */ null, replaceGuest);
Mayank Garg70732a82020-08-05 20:17:47 -0700892 }
Mayank Gargfd1e0692021-05-25 13:33:48 -0700893 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ_COMPLETE,
894 requestType);
Mayank Garg70732a82020-08-05 20:17:47 -0700895 });
896 }
897
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700898 private void fallbackToDefaultInitialUserBehavior(String userLocales, boolean replaceGuest) {
Mayank Garg70732a82020-08-05 20:17:47 -0700899 InitialUserInfo info = new InitialUserSetter.Builder(
900 InitialUserSetter.TYPE_DEFAULT_BEHAVIOR)
901 .setUserLocales(userLocales)
Mayank Garg4bdfbf72020-08-06 13:27:43 -0700902 .setReplaceGuest(replaceGuest)
Mayank Garg70732a82020-08-05 20:17:47 -0700903 .build();
904 mInitialUserSetter.set(info);
905 }
906
907 @VisibleForTesting
908 int getInitialUserInfoRequestType() {
Mayank Garge90a4082020-09-30 12:57:34 -0700909 if (!mInitialUserSetter.hasInitialUser()) {
Mayank Garg70732a82020-08-05 20:17:47 -0700910 return InitialUserInfoRequestType.FIRST_BOOT;
911 }
912 if (mContext.getPackageManager().isDeviceUpgrading()) {
913 return InitialUserInfoRequestType.FIRST_BOOT_AFTER_OTA;
914 }
915 return InitialUserInfoRequestType.COLD_BOOT;
916 }
917
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800918 /**
919 * Sets the {@link ICarServiceHelper} so it can receive UX restriction updates.
920 */
921 public void setCarServiceHelper(ICarServiceHelper helper) {
922 boolean restricted;
923 synchronized (mLockUser) {
924 mICarServiceHelper = helper;
925 restricted = mUxRestricted;
926 }
927 updateSafetyMode(helper, restricted);
928 }
929
930 private void updateSafetyMode(@Nullable ICarServiceHelper helper, boolean restricted) {
931 if (helper == null) return;
932
933 boolean isSafe = !restricted;
934 try {
935 helper.setSafetyMode(isSafe);
936 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800937 Slog.e(TAG, "Exception calling helper.setDpmSafetyMode(" + isSafe + ")", e);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800938 }
939 }
940
941 private void setUxRestrictions(@Nullable CarUxRestrictions restrictions) {
Felipe Leme5d5ab142020-10-27 13:49:10 -0700942 boolean restricted = restrictions != null
943 && (restrictions.getActiveRestrictions() & UX_RESTRICTIONS_NO_SETUP)
944 == UX_RESTRICTIONS_NO_SETUP;
Eric Jeongf75d4132020-12-21 13:48:23 -0800945 if (Log.isLoggable(TAG, Log.DEBUG)) {
946 Slog.d(TAG, "setUxRestrictions(" + restrictions + "): restricted=" + restricted);
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800947 } else {
Eric Jeongf75d4132020-12-21 13:48:23 -0800948 Slog.i(TAG, "Setting UX restricted to " + restricted);
Felipe Leme5d5ab142020-10-27 13:49:10 -0700949 }
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800950
951 ICarServiceHelper helper = null;
952
953 synchronized (mLockUser) {
954 mUxRestricted = restricted;
955 if (mICarServiceHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -0800956 Slog.e(TAG, "onUxRestrictionsChanged(): no mICarServiceHelper");
Felipe Leme56ef9ad2020-11-05 18:39:03 -0800957 }
958 helper = mICarServiceHelper;
959 }
960 updateSafetyMode(helper, restricted);
961 }
962
963 private boolean isUxRestricted() {
964 synchronized (mLockUser) {
965 return mUxRestricted;
966 }
Felipe Leme5d5ab142020-10-27 13:49:10 -0700967 }
968
Mayank Garg70732a82020-08-05 20:17:47 -0700969 /**
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700970 * Calls the {@link UserHalService} and {@link IActivityManager} for user switch.
971 *
972 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700973 * When everything works well, the workflow is:
974 * <ol>
975 * <li> {@link UserHalService} is called for HAL user switch with ANDROID_SWITCH request
976 * type, current user id, target user id, and a callback.
977 * <li> HAL called back with SUCCESS.
978 * <li> {@link IActivityManager} is called for Android user switch.
979 * <li> Receiver would receive {@code STATUS_SUCCESSFUL}.
980 * <li> Once user is unlocked, {@link UserHalService} is again called with ANDROID_POST_SWITCH
981 * request type, current user id, and target user id. In this case, the current and target
982 * user IDs would be same.
983 * <ol/>
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700984 *
985 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700986 * Corner cases:
987 * <ul>
988 * <li> If target user is already the current user, no user switch is performed and receiver
Mayank Gargef1b9332020-06-11 17:36:56 -0700989 * would receive {@code STATUS_OK_USER_ALREADY_IN_FOREGROUND} right away.
Mayank Gargb08f6772020-05-01 18:06:48 -0700990 * <li> If HAL user switch call fails, no Android user switch. Receiver would receive
991 * {@code STATUS_HAL_INTERNAL_FAILURE}.
992 * <li> If HAL user switch call is successful, but android user switch call fails,
993 * {@link UserHalService} is again called with request type POST_SWITCH, current user id, and
994 * target user id, but in this case the current and target user IDs would be different.
995 * <li> If another user switch request for the same target user is received while previous
996 * request is in process, receiver would receive
997 * {@code STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO} for the new request right away.
998 * <li> If a user switch request is received while another user switch request for different
999 * target user is in process, the previous request would be abandoned and new request will be
1000 * processed. No POST_SWITCH would be sent for the previous request.
1001 * <ul/>
Mayank Garg59f22192020-03-27 00:51:45 -07001002 *
Mayank Garge19c2922020-03-30 18:05:53 -07001003 * @param targetUserId - target user Id
Mayank Garg59f22192020-03-27 00:51:45 -07001004 * @param timeoutMs - timeout for HAL to wait
1005 * @param receiver - receiver for the results
1006 */
Mayank Garge19c2922020-03-30 18:05:53 -07001007 @Override
1008 public void switchUser(@UserIdInt int targetUserId, int timeoutMs,
felipeale5bf0322020-04-16 15:10:57 -07001009 @NonNull AndroidFuture<UserSwitchResult> receiver) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001010 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_REQ, targetUserId, timeoutMs);
Felipe Leme17799202020-09-03 12:55:53 -07001011 checkManageOrCreateUsersPermission("switchUser");
Mayank Garge19c2922020-03-30 18:05:53 -07001012 Objects.requireNonNull(receiver);
1013 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
felipealf7368962020-04-16 12:55:19 -07001014 Preconditions.checkArgument(targetUser != null, "Target user doesn't exist");
Mayank Garga479cb32021-04-05 22:23:04 -07001015 if (mUserManager.getUserSwitchability() != UserManager.SWITCHABILITY_STATUS_OK) {
1016 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_NOT_SWITCHABLE);
1017 return;
1018 }
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001019 mHandler.post(() -> handleSwitchUser(targetUser, timeoutMs, receiver));
Mayank Garg02576972021-02-18 16:46:07 -08001020 }
Mayank Garg7a114c82020-04-08 21:25:06 -07001021
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001022 private void handleSwitchUser(@NonNull UserInfo targetUser, int timeoutMs,
Mayank Garg02576972021-02-18 16:46:07 -08001023 @NonNull AndroidFuture<UserSwitchResult> receiver) {
felipealf7368962020-04-16 12:55:19 -07001024 int currentUser = ActivityManager.getCurrentUser();
Mayank Garg02576972021-02-18 16:46:07 -08001025 int targetUserId = targetUser.id;
felipealf7368962020-04-16 12:55:19 -07001026 if (currentUser == targetUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001027 if (Log.isLoggable(TAG, Log.DEBUG)) {
1028 Slog.d(TAG, "Current user is same as requested target user: " + targetUserId);
Mayank Garg0e239142020-04-14 19:16:31 -07001029 }
Mayank Gargef1b9332020-06-11 17:36:56 -07001030 int resultStatus = UserSwitchResult.STATUS_OK_USER_ALREADY_IN_FOREGROUND;
felipealdfdf8512020-06-01 09:35:45 -07001031 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg0e239142020-04-14 19:16:31 -07001032 return;
1033 }
1034
Felipe Leme5d5ab142020-10-27 13:49:10 -07001035 if (isUxRestricted()) {
1036 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_UX_RESTRICTION_FAILURE);
1037 return;
1038 }
1039
Mayank Garg9ed099e2020-06-04 16:05:20 -07001040 // If User Hal is not supported, just android user switch.
1041 if (!isUserHalSupported()) {
1042 try {
1043 if (mAm.switchUser(targetUserId)) {
1044 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_SUCCESSFUL);
1045 return;
1046 }
1047 } catch (RemoteException e) {
1048 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001049 Slog.w(TAG, "error while switching user " + targetUser.toFullString(), e);
Mayank Garg9ed099e2020-06-04 16:05:20 -07001050 }
1051 sendUserSwitchResult(receiver, UserSwitchResult.STATUS_ANDROID_FAILURE);
1052 return;
1053 }
1054
Mayank Garg7a114c82020-04-08 21:25:06 -07001055 synchronized (mLockUser) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001056 if (Log.isLoggable(TAG, Log.DEBUG)) {
1057 Slog.d(TAG, "switchUser(" + targetUserId + "): currentuser=" + currentUser
felipealf7368962020-04-16 12:55:19 -07001058 + ", mUserIdForUserSwitchInProcess=" + mUserIdForUserSwitchInProcess);
1059 }
1060
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001061 // If there is another request for the same target user, return another request in
1062 // process, else {@link mUserIdForUserSwitchInProcess} is updated and {@link
1063 // mRequestIdForUserSwitchInProcess} is reset. It is possible that there may be another
1064 // user switch request in process for different target user, but that request is now
1065 // ignored.
felipealf7368962020-04-16 12:55:19 -07001066 if (mUserIdForUserSwitchInProcess == targetUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001067 if (Log.isLoggable(TAG, Log.DEBUG)) {
1068 Slog.d(TAG,
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001069 "Another user switch request in process for the requested target user: "
1070 + targetUserId);
1071 }
1072
1073 int resultStatus = UserSwitchResult.STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO;
felipealdfdf8512020-06-01 09:35:45 -07001074 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg7a114c82020-04-08 21:25:06 -07001075 return;
Mayank Garg02576972021-02-18 16:46:07 -08001076 } else {
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001077 mUserIdForUserSwitchInProcess = targetUserId;
1078 mRequestIdForUserSwitchInProcess = 0;
1079 }
Mayank Garg7a114c82020-04-08 21:25:06 -07001080 }
1081
felipealdfdf8512020-06-01 09:35:45 -07001082 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -07001083 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
1084
Felipe Leme5d5ab142020-10-27 13:49:10 -07001085 mHal.switchUser(request, timeoutMs, (halCallbackStatus, resp) -> {
Eric Jeongf75d4132020-12-21 13:48:23 -08001086 if (Log.isLoggable(TAG, Log.DEBUG)) {
1087 Slog.d(TAG, "switch response: status="
Felipe Leme5d5ab142020-10-27 13:49:10 -07001088 + UserHalHelper.halCallbackStatusToString(halCallbackStatus)
1089 + ", resp=" + resp);
felipealf7368962020-04-16 12:55:19 -07001090 }
1091
felipeale5bf0322020-04-16 15:10:57 -07001092 int resultStatus = UserSwitchResult.STATUS_HAL_INTERNAL_FAILURE;
felipealf7368962020-04-16 12:55:19 -07001093
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001094 synchronized (mLockUser) {
Felipe Leme5d5ab142020-10-27 13:49:10 -07001095 if (halCallbackStatus != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001096 Slog.w(TAG, "invalid callback status ("
Felipe Leme5d5ab142020-10-27 13:49:10 -07001097 + UserHalHelper.halCallbackStatusToString(halCallbackStatus)
1098 + ") for response " + resp);
felipealdfdf8512020-06-01 09:35:45 -07001099 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001100 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1101 return;
1102 }
felipealf7368962020-04-16 12:55:19 -07001103
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001104 if (mUserIdForUserSwitchInProcess != targetUserId) {
1105 // Another user switch request received while HAL responded. No need to process
1106 // this request further
Eric Jeongf75d4132020-12-21 13:48:23 -08001107 if (Log.isLoggable(TAG, Log.DEBUG)) {
1108 Slog.d(TAG, "Another user switch received while HAL responsed. Request"
1109 + " abondoned for : " + targetUserId + ". Current user in process: "
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001110 + mUserIdForUserSwitchInProcess);
felipealf7368962020-04-16 12:55:19 -07001111 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001112 resultStatus =
1113 UserSwitchResult.STATUS_TARGET_USER_ABANDONED_DUE_TO_A_NEW_REQUEST;
felipealdfdf8512020-06-01 09:35:45 -07001114 sendUserSwitchResult(receiver, resultStatus);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001115 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1116 return;
1117 }
1118
1119 switch (resp.status) {
1120 case SwitchUserStatus.SUCCESS:
1121 boolean switched;
1122 try {
1123 switched = mAm.switchUser(targetUserId);
1124 if (switched) {
Mayank Garg587f1942020-05-06 01:41:34 -07001125 sendUserSwitchUiCallback(targetUserId);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001126 resultStatus = UserSwitchResult.STATUS_SUCCESSFUL;
1127 mRequestIdForUserSwitchInProcess = resp.requestId;
1128 } else {
1129 resultStatus = UserSwitchResult.STATUS_ANDROID_FAILURE;
1130 postSwitchHalResponse(resp.requestId, targetUserId);
1131 }
1132 } catch (RemoteException e) {
1133 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001134 Slog.w(TAG,
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001135 "error while switching user " + targetUser.toFullString(), e);
1136 }
1137 break;
1138 case SwitchUserStatus.FAILURE:
1139 // HAL failed to switch user
1140 resultStatus = UserSwitchResult.STATUS_HAL_FAILURE;
1141 break;
felipealdfdf8512020-06-01 09:35:45 -07001142 default:
1143 // Shouldn't happen because UserHalService validates the status
Eric Jeongf75d4132020-12-21 13:48:23 -08001144 Slog.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001145 }
1146
1147 if (mRequestIdForUserSwitchInProcess == 0) {
1148 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
1149 }
Mayank Garg59f22192020-03-27 00:51:45 -07001150 }
Felipe Leme5d5ab142020-10-27 13:49:10 -07001151 sendUserSwitchResult(receiver, halCallbackStatus, resultStatus, resp.errorMessage);
Mayank Garg59f22192020-03-27 00:51:45 -07001152 });
1153 }
1154
Mayank Garga55c3092020-05-28 03:19:24 -07001155 @Override
Mayank Gargc9266482021-03-01 10:27:37 -08001156 public void removeUser(@UserIdInt int userId, AndroidFuture<UserRemovalResult> receiver) {
1157 removeUser(userId, /* hasCallerRestrictions= */ false, receiver);
Felipe Leme55236722020-10-16 16:54:32 -07001158 }
1159
1160 /**
1161 * Internal implementation of {@code removeUser()}, which is used by both
1162 * {@code ICarUserService} and {@code ICarDevicePolicyService}.
1163 *
1164 * @param userId user to be removed
1165 * @param hasCallerRestrictions when {@code true}, if the caller user is not an admin, it can
1166 * only remove itself.
Mayank Gargc9266482021-03-01 10:27:37 -08001167 * @param receiver to post results
Felipe Leme55236722020-10-16 16:54:32 -07001168 */
Mayank Gargc9266482021-03-01 10:27:37 -08001169 public void removeUser(@UserIdInt int userId, boolean hasCallerRestrictions,
1170 AndroidFuture<UserRemovalResult> receiver) {
Felipe Leme17799202020-09-03 12:55:53 -07001171 checkManageOrCreateUsersPermission("removeUser");
Felipe Leme55236722020-10-16 16:54:32 -07001172 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_REQ, userId,
1173 hasCallerRestrictions ? 1 : 0);
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001174
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001175 if (hasCallerRestrictions) {
1176 // Restrictions: non-admin user can only remove itself, admins have no restrictions
1177 int callingUserId = Binder.getCallingUserHandle().getIdentifier();
1178 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
1179 if (!callingUser.isAdmin() && userId != callingUserId) {
1180 throw new SecurityException("Non-admin user " + callingUserId
1181 + " can only remove itself");
1182 }
1183 }
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001184 mHandler.post(() -> handleRemoveUser(userId, hasCallerRestrictions, receiver));
Mayank Gargc9266482021-03-01 10:27:37 -08001185 }
Felipe Lemee5bb26b2020-10-26 15:49:17 -07001186
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001187 private void handleRemoveUser(@UserIdInt int userId, boolean hasCallerRestrictions,
Mayank Gargc9266482021-03-01 10:27:37 -08001188 AndroidFuture<UserRemovalResult> receiver) {
1189 UserInfo userInfo = mUserManager.getUserInfo(userId);
1190 if (userInfo == null) {
1191 sendUserRemovalResult(userId, UserRemovalResult.STATUS_USER_DOES_NOT_EXIST, receiver);
1192 return;
1193 }
Mayank Garga55c3092020-05-28 03:19:24 -07001194 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
1195 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1196 halUser.userId = userInfo.id;
1197 halUser.flags = UserHalHelper.convertFlags(userInfo);
1198 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1199
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001200 // check if the user is last admin user.
1201 boolean isLastAdmin = false;
Mayank Garga55c3092020-05-28 03:19:24 -07001202 if (UserHalHelper.isAdmin(halUser.flags)) {
1203 int size = usersInfo.existingUsers.size();
1204 int totalAdminUsers = 0;
1205 for (int i = 0; i < size; i++) {
1206 if (UserHalHelper.isAdmin(usersInfo.existingUsers.get(i).flags)) {
1207 totalAdminUsers++;
1208 }
1209 }
1210 if (totalAdminUsers == 1) {
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001211 isLastAdmin = true;
Mayank Garga55c3092020-05-28 03:19:24 -07001212 }
1213 }
1214
1215 // First remove user from android and then remove from HAL because HAL remove user is one
1216 // way call.
Felipe Leme9a751912021-01-05 17:45:48 -08001217 // TODO(b/170887769): rename hasCallerRestrictions to fromCarDevicePolicyManager (or use an
1218 // int / enum to indicate if it's called from CarUserManager or CarDevicePolicyManager), as
1219 // it's counter-intuitive that it's "allowed even when disallowed" when it
1220 // "has caller restrictions"
1221 boolean evenWhenDisallowed = hasCallerRestrictions;
1222 int result = mUserManager.removeUserOrSetEphemeral(userId, evenWhenDisallowed);
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001223 if (result == UserManager.REMOVE_RESULT_ERROR) {
Mayank Gargc9266482021-03-01 10:27:37 -08001224 sendUserRemovalResult(userId, UserRemovalResult.STATUS_ANDROID_FAILURE, receiver);
1225 return;
Mayank Garga55c3092020-05-28 03:19:24 -07001226 }
1227
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001228 if (isLastAdmin) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001229 Slog.w(TAG,
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001230 "Last admin user successfully removed or set ephemeral. User Id: " + userId);
Mayank Garge9b7d2c2020-09-15 12:36:06 -07001231 }
1232
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001233 switch (result) {
1234 case UserManager.REMOVE_RESULT_REMOVED:
1235 case UserManager.REMOVE_RESULT_ALREADY_BEING_REMOVED:
Mayank Gargc9266482021-03-01 10:27:37 -08001236 sendUserRemovalResult(userId,
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001237 isLastAdmin ? UserRemovalResult.STATUS_SUCCESSFUL_LAST_ADMIN_REMOVED
Mayank Gargc9266482021-03-01 10:27:37 -08001238 : UserRemovalResult.STATUS_SUCCESSFUL, receiver);
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001239 case UserManager.REMOVE_RESULT_SET_EPHEMERAL:
Mayank Gargc9266482021-03-01 10:27:37 -08001240 sendUserRemovalResult(userId,
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001241 isLastAdmin ? UserRemovalResult.STATUS_SUCCESSFUL_LAST_ADMIN_SET_EPHEMERAL
Mayank Gargc9266482021-03-01 10:27:37 -08001242 : UserRemovalResult.STATUS_SUCCESSFUL_SET_EPHEMERAL, receiver);
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001243 default:
Mayank Gargc9266482021-03-01 10:27:37 -08001244 sendUserRemovalResult(userId, UserRemovalResult.STATUS_ANDROID_FAILURE, receiver);
Jordan Jozwiakffcdca52020-10-15 15:22:01 -07001245 }
Mayank Garga55c3092020-05-28 03:19:24 -07001246 }
1247
Felipe Leme67d564c2020-11-13 15:35:34 -08001248 /**
1249 * Should be called by {@code ICarImpl} only.
1250 */
1251 public void onUserRemoved(@NonNull UserInfo user) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001252 if (Log.isLoggable(TAG, Log.DEBUG)) {
1253 Slog.d(TAG, "onUserRemoved: " + user.toFullString());
Felipe Leme67d564c2020-11-13 15:35:34 -08001254 }
1255 notifyHalUserRemoved(user);
1256 }
1257
1258 private void notifyHalUserRemoved(@NonNull UserInfo user) {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001259 if (!isUserHalSupported()) return;
1260
Felipe Leme67d564c2020-11-13 15:35:34 -08001261 if (user == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001262 Slog.wtf(TAG, "notifyHalUserRemoved() called for null user");
Felipe Leme67d564c2020-11-13 15:35:34 -08001263 return;
1264 }
1265
1266 int userId = user.id;
1267
Felipe Leme6b34fc32020-10-26 15:49:17 -07001268 if (userId == UserHandle.USER_NULL) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001269 Slog.wtf(TAG, "notifyHalUserRemoved() called for UserHandle.USER_NULL");
Felipe Leme6b34fc32020-10-26 15:49:17 -07001270 return;
1271 }
1272
1273 synchronized (mLockUser) {
1274 if (mFailedToCreateUserIds.get(userId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001275 if (Log.isLoggable(TAG, Log.DEBUG)) {
1276 Slog.d(TAG, "notifyHalUserRemoved(): skipping " + userId);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001277 }
1278 mFailedToCreateUserIds.delete(userId);
1279 return;
1280 }
1281 }
1282
1283 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
1284 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1285 halUser.userId = userId;
Felipe Leme67d564c2020-11-13 15:35:34 -08001286 halUser.flags = UserHalHelper.convertFlags(user);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001287
1288 RemoveUserRequest request = new RemoveUserRequest();
1289 request.removedUserInfo = halUser;
1290 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1291 mHal.removeUser(request);
1292 }
1293
Mayank Gargc9266482021-03-01 10:27:37 -08001294 private void sendUserRemovalResult(@UserIdInt int userId, @UserRemovalResult.Status int result,
1295 AndroidFuture<UserRemovalResult> receiver) {
Mayank Garga55c3092020-05-28 03:19:24 -07001296 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_REMOVE_USER_RESP, userId, result);
Mayank Gargc9266482021-03-01 10:27:37 -08001297 receiver.complete(new UserRemovalResult(result));
Mayank Garga55c3092020-05-28 03:19:24 -07001298 }
1299
Mayank Garg587f1942020-05-06 01:41:34 -07001300 private void sendUserSwitchUiCallback(@UserIdInt int targetUserId) {
1301 if (mUserSwitchUiReceiver == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001302 Slog.w(TAG, "No User switch UI receiver.");
Mayank Garg587f1942020-05-06 01:41:34 -07001303 return;
1304 }
1305
felipealdfdf8512020-06-01 09:35:45 -07001306 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_UI_REQ, targetUserId);
Mayank Garg587f1942020-05-06 01:41:34 -07001307 try {
Mayank Garg587f1942020-05-06 01:41:34 -07001308 mUserSwitchUiReceiver.send(targetUserId, null);
1309 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001310 Slog.e(TAG, "Error calling user switch UI receiver.", e);
Mayank Garg587f1942020-05-06 01:41:34 -07001311 }
1312 }
1313
Felipe Lemecceb2992020-11-18 18:22:44 -08001314 /**
1315 * Used to create the initial user, even when it's disallowed by {@code DevicePolicyManager}.
1316 */
1317 @Nullable
1318 UserInfo createUserEvenWhenDisallowed(@Nullable String name, @NonNull String userType,
1319 @UserInfoFlag int flags) {
1320 if (mICarServiceHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001321 Slog.wtf(TAG, "createUserEvenWhenDisallowed(): mICarServiceHelper not set yet",
Felipe Lemecceb2992020-11-18 18:22:44 -08001322 new Exception());
1323 return null;
1324 }
1325 try {
1326 return mICarServiceHelper.createUserEvenWhenDisallowed(name, userType, flags);
1327 } catch (RemoteException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001328 Slog.e(TAG, "createUserEvenWhenDisallowed(" + UserHelperLite.safeName(name) + ", "
Felipe Lemecceb2992020-11-18 18:22:44 -08001329 + userType + ", " + UserInfo.flagsToString(flags) + ") failed", e);
1330 return null;
1331 }
1332 }
1333
felipeal5e3ede42020-04-23 18:04:07 -07001334 @Override
felipealdfdf8512020-06-01 09:35:45 -07001335 public void createUser(@Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
1336 int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver) {
Felipe Leme8c888ab2020-11-02 17:39:52 -08001337 createUser(name, userType, flags, timeoutMs, receiver, /* hasCallerRestrictions= */ false);
1338 }
1339
1340 /**
1341 * Internal implementation of {@code createUser()}, which is used by both
1342 * {@code ICarUserService} and {@code ICarDevicePolicyService}.
1343 *
1344 * @param hasCallerRestrictions when {@code true}, if the caller user is not an admin, it can
1345 * only create admin users
1346 */
1347 public void createUser(@Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
1348 int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver,
1349 boolean hasCallerRestrictions) {
felipealdfdf8512020-06-01 09:35:45 -07001350 Objects.requireNonNull(userType, "user type cannot be null");
1351 Objects.requireNonNull(receiver, "receiver cannot be null");
Felipe Leme17799202020-09-03 12:55:53 -07001352 checkManageOrCreateUsersPermission(flags);
Mayank Garg94f3eb92020-08-12 12:38:58 -07001353 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_REQ,
Felipe Leme8c888ab2020-11-02 17:39:52 -08001354 UserHelperLite.safeName(name), userType, flags, timeoutMs,
1355 hasCallerRestrictions ? 1 : 0);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001356 mHandler.post(() -> handleCreateUser(name, userType, flags, timeoutMs, receiver,
Mayank Garg02576972021-02-18 16:46:07 -08001357 hasCallerRestrictions));
Felipe Leme8c888ab2020-11-02 17:39:52 -08001358
Mayank Garg02576972021-02-18 16:46:07 -08001359 }
1360
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001361 private void handleCreateUser(@Nullable String name, @NonNull String userType,
Mayank Garg02576972021-02-18 16:46:07 -08001362 @UserInfoFlag int flags, int timeoutMs,
1363 @NonNull AndroidFuture<UserCreationResult> receiver,
1364 boolean hasCallerRestrictions) {
Felipe Leme8c888ab2020-11-02 17:39:52 -08001365 if (hasCallerRestrictions) {
1366 // Restrictions:
1367 // - type/flag can only be normal user, admin, or guest
1368 // - non-admin user can only create non-admin users
1369
1370 boolean validCombination;
1371 switch (userType) {
1372 case UserManager.USER_TYPE_FULL_SECONDARY:
1373 validCombination = flags == 0
1374 || (flags & UserInfo.FLAG_ADMIN) == UserInfo.FLAG_ADMIN;
1375 break;
1376 case UserManager.USER_TYPE_FULL_GUEST:
1377 validCombination = flags == 0;
1378 break;
1379 default:
1380 validCombination = false;
1381 }
1382 if (!validCombination) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001383 if (Log.isLoggable(TAG, Log.DEBUG)) {
1384 Slog.d(TAG, "Invalid combination of user type(" + userType
Felipe Leme71d296f2020-11-04 12:11:42 -08001385 + ") and flags (" + UserInfo.flagsToString(flags)
1386 + ") for caller with restrictions");
1387 }
1388 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_INVALID_REQUEST);
1389 return;
1390
Felipe Leme8c888ab2020-11-02 17:39:52 -08001391 }
1392
1393 int callingUserId = Binder.getCallingUserHandle().getIdentifier();
1394 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
1395 if (!callingUser.isAdmin() && (flags & UserInfo.FLAG_ADMIN) == UserInfo.FLAG_ADMIN) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001396 if (Log.isLoggable(TAG, Log.DEBUG)) {
1397 Slog.d(TAG, "Non-admin user " + callingUserId
Felipe Leme71d296f2020-11-04 12:11:42 -08001398 + " can only create non-admin users");
1399 }
1400 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_INVALID_REQUEST);
1401 return;
Felipe Leme8c888ab2020-11-02 17:39:52 -08001402 }
Felipe Leme71d296f2020-11-04 12:11:42 -08001403
Felipe Leme8c888ab2020-11-02 17:39:52 -08001404 }
felipealdfdf8512020-06-01 09:35:45 -07001405
1406 UserInfo newUser;
1407 try {
1408 newUser = mUserManager.createUser(name, userType, flags);
1409 if (newUser == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001410 Slog.w(TAG, "um.createUser() returned null for user of type " + userType
felipealdfdf8512020-06-01 09:35:45 -07001411 + " and flags " + UserInfo.flagsToString(flags));
1412 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1413 return;
1414 }
Eric Jeongf75d4132020-12-21 13:48:23 -08001415 if (Log.isLoggable(TAG, Log.DEBUG)) {
1416 Slog.d(TAG, "Created user: " + newUser.toFullString());
felipealdfdf8512020-06-01 09:35:45 -07001417 }
1418 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_CREATED, newUser.id,
Mayank Garg94f3eb92020-08-12 12:38:58 -07001419 UserHelperLite.safeName(newUser.name), newUser.userType, newUser.flags);
felipealdfdf8512020-06-01 09:35:45 -07001420 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001421 Slog.e(TAG, "Error creating user of type " + userType + " and flags"
felipealdfdf8512020-06-01 09:35:45 -07001422 + UserInfo.flagsToString(flags), e);
1423 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_ANDROID_FAILURE);
1424 return;
1425 }
1426
Mayank Garg9ed099e2020-06-04 16:05:20 -07001427 if (!isUserHalSupported()) {
1428 sendUserCreationResult(receiver, UserCreationResult.STATUS_SUCCESSFUL, newUser, null);
1429 return;
1430 }
1431
felipealdfdf8512020-06-01 09:35:45 -07001432 CreateUserRequest request = new CreateUserRequest();
1433 request.usersInfo = UserHalHelper.newUsersInfo(mUserManager);
1434 if (!TextUtils.isEmpty(name)) {
1435 request.newUserName = name;
1436 }
1437 request.newUserInfo.userId = newUser.id;
1438 request.newUserInfo.flags = UserHalHelper.convertFlags(newUser);
Eric Jeongf75d4132020-12-21 13:48:23 -08001439 if (Log.isLoggable(TAG, Log.DEBUG)) {
1440 Slog.d(TAG, "Create user request: " + request);
felipealdfdf8512020-06-01 09:35:45 -07001441 }
1442
1443 try {
1444 mHal.createUser(request, timeoutMs, (status, resp) -> {
1445 int resultStatus = UserCreationResult.STATUS_HAL_INTERNAL_FAILURE;
Eric Jeongf75d4132020-12-21 13:48:23 -08001446 if (Log.isLoggable(TAG, Log.DEBUG)) {
1447 Slog.d(TAG, "createUserResponse: status="
felipealdfdf8512020-06-01 09:35:45 -07001448 + UserHalHelper.halCallbackStatusToString(status) + ", resp=" + resp);
1449 }
1450 UserInfo user = null; // user returned in the result
1451 if (status != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001452 Slog.w(TAG, "invalid callback status ("
felipealdfdf8512020-06-01 09:35:45 -07001453 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1454 + resp);
1455 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1456 resultStatus, resp.errorMessage);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001457 removeCreatedUser(newUser, "HAL call failed with "
felipealdfdf8512020-06-01 09:35:45 -07001458 + UserHalHelper.halCallbackStatusToString(status));
1459 sendUserCreationResult(receiver, resultStatus, user, /* errorMsg= */ null);
1460 return;
1461 }
1462
1463 switch (resp.status) {
1464 case CreateUserStatus.SUCCESS:
1465 resultStatus = UserCreationResult.STATUS_SUCCESSFUL;
1466 user = newUser;
1467 break;
1468 case CreateUserStatus.FAILURE:
1469 // HAL failed to switch user
1470 resultStatus = UserCreationResult.STATUS_HAL_FAILURE;
1471 break;
1472 default:
1473 // Shouldn't happen because UserHalService validates the status
Eric Jeongf75d4132020-12-21 13:48:23 -08001474 Slog.wtf(TAG, "Received invalid user switch status from HAL: " + resp);
felipealdfdf8512020-06-01 09:35:45 -07001475 }
1476 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_RESP, status,
1477 resultStatus, resp.errorMessage);
1478 if (user == null) {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001479 removeCreatedUser(newUser, "HAL returned "
felipealdfdf8512020-06-01 09:35:45 -07001480 + UserCreationResult.statusToString(resultStatus));
1481 }
1482 sendUserCreationResult(receiver, resultStatus, user, resp.errorMessage);
1483 });
1484 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001485 Slog.w(TAG, "mHal.createUser(" + request + ") failed", e);
Felipe Leme6b34fc32020-10-26 15:49:17 -07001486 removeCreatedUser(newUser, "mHal.createUser() failed");
felipealdfdf8512020-06-01 09:35:45 -07001487 sendUserCreationResultFailure(receiver, UserCreationResult.STATUS_HAL_INTERNAL_FAILURE);
1488 }
1489 }
1490
Felipe Leme6b34fc32020-10-26 15:49:17 -07001491 private void removeCreatedUser(@NonNull UserInfo user, @NonNull String reason) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001492 Slog.i(TAG, "removing " + user.toFullString() + "; reason: " + reason);
Felipe Leme67d564c2020-11-13 15:35:34 -08001493
Felipe Leme6b34fc32020-10-26 15:49:17 -07001494 int userId = user.id;
1495 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_CREATE_USER_USER_REMOVED, userId, reason);
1496
1497 synchronized (mLockUser) {
1498 mFailedToCreateUserIds.put(userId, true);
1499 }
1500
felipealdfdf8512020-06-01 09:35:45 -07001501 try {
Felipe Leme6b34fc32020-10-26 15:49:17 -07001502 if (!mUserManager.removeUser(userId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001503 Slog.w(TAG, "Failed to remove user " + user.toFullString());
felipealdfdf8512020-06-01 09:35:45 -07001504 }
1505 } catch (Exception e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001506 Slog.e(TAG, "Failed to remove user " + user.toFullString(), e);
felipealdfdf8512020-06-01 09:35:45 -07001507 }
1508 }
1509
1510 @Override
Mayank Garg3f566582020-10-02 22:10:16 -07001511 public UserIdentificationAssociationResponse getUserIdentificationAssociation(
1512 @UserIdentificationAssociationType int[] types) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001513 if (!isUserHalUserAssociationSupported()) {
1514 return UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED);
1515 }
1516
felipeal5e3ede42020-04-23 18:04:07 -07001517 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
Felipe Leme17799202020-09-03 12:55:53 -07001518 checkManageOrCreateUsersPermission("getUserIdentificationAssociation");
felipeal5e3ede42020-04-23 18:04:07 -07001519
1520 int uid = getCallingUid();
1521 int userId = UserHandle.getUserId(uid);
1522 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_REQ, uid, userId);
1523
1524 UserIdentificationGetRequest request = new UserIdentificationGetRequest();
1525 request.userInfo.userId = userId;
1526 request.userInfo.flags = getHalUserInfoFlags(userId);
1527
1528 request.numberAssociationTypes = types.length;
1529 for (int i = 0; i < types.length; i++) {
1530 request.associationTypes.add(types[i]);
1531 }
1532
1533 UserIdentificationResponse halResponse = mHal.getUserAssociation(request);
1534 if (halResponse == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001535 Slog.w(TAG, "getUserIdentificationAssociation(): HAL returned null for "
felipeal5e3ede42020-04-23 18:04:07 -07001536 + Arrays.toString(types));
felipeal159a2a42020-05-08 10:32:11 -07001537 return UserIdentificationAssociationResponse.forFailure();
felipeal5e3ede42020-04-23 18:04:07 -07001538 }
1539
1540 int[] values = new int[halResponse.associations.size()];
1541 for (int i = 0; i < values.length; i++) {
1542 values[i] = halResponse.associations.get(i).value;
1543 }
1544 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_RESP, values.length);
1545
felipeal159a2a42020-05-08 10:32:11 -07001546 return UserIdentificationAssociationResponse.forSuccess(values, halResponse.errorMessage);
1547 }
1548
1549 @Override
Mayank Garg3f566582020-10-02 22:10:16 -07001550 public void setUserIdentificationAssociation(int timeoutMs,
1551 @UserIdentificationAssociationType int[] types,
1552 @UserIdentificationAssociationSetValue int[] values,
felipeal159a2a42020-05-08 10:32:11 -07001553 AndroidFuture<UserIdentificationAssociationResponse> result) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001554 if (!isUserHalUserAssociationSupported()) {
1555 result.complete(
1556 UserIdentificationAssociationResponse.forFailure(VEHICLE_HAL_NOT_SUPPORTED));
1557 return;
1558 }
1559
felipeal159a2a42020-05-08 10:32:11 -07001560 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
1561 Preconditions.checkArgument(!ArrayUtils.isEmpty(values), "must have at least one value");
1562 if (types.length != values.length) {
1563 throw new IllegalArgumentException("types (" + Arrays.toString(types) + ") and values ("
1564 + Arrays.toString(values) + ") should have the same length");
1565 }
Felipe Leme17799202020-09-03 12:55:53 -07001566 checkManageOrCreateUsersPermission("setUserIdentificationAssociation");
felipeal159a2a42020-05-08 10:32:11 -07001567
1568 int uid = getCallingUid();
1569 int userId = UserHandle.getUserId(uid);
1570 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_REQ, uid, userId, types.length);
1571
1572 UserIdentificationSetRequest request = new UserIdentificationSetRequest();
1573 request.userInfo.userId = userId;
1574 request.userInfo.flags = getHalUserInfoFlags(userId);
1575
1576 request.numberAssociations = types.length;
1577 for (int i = 0; i < types.length; i++) {
1578 UserIdentificationSetAssociation association = new UserIdentificationSetAssociation();
1579 association.type = types[i];
1580 association.value = values[i];
1581 request.associations.add(association);
1582 }
1583
1584 mHal.setUserAssociation(timeoutMs, request, (status, resp) -> {
1585 if (status != HalCallback.STATUS_OK) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001586 Slog.w(TAG, "setUserIdentificationAssociation(): invalid callback status ("
felipeal159a2a42020-05-08 10:32:11 -07001587 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
1588 + resp);
1589 if (resp == null || TextUtils.isEmpty(resp.errorMessage)) {
1590 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0);
1591 result.complete(UserIdentificationAssociationResponse.forFailure());
1592 return;
1593 }
1594 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, 0,
1595 resp.errorMessage);
1596 result.complete(
1597 UserIdentificationAssociationResponse.forFailure(resp.errorMessage));
1598 return;
1599 }
1600 int respSize = resp.associations.size();
1601 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_SET_USER_AUTH_RESP, respSize,
1602 resp.errorMessage);
1603
1604 int[] responseTypes = new int[respSize];
1605 for (int i = 0; i < respSize; i++) {
1606 responseTypes[i] = resp.associations.get(i).value;
1607 }
1608 UserIdentificationAssociationResponse response = UserIdentificationAssociationResponse
1609 .forSuccess(responseTypes, resp.errorMessage);
Eric Jeongf75d4132020-12-21 13:48:23 -08001610 if (Log.isLoggable(TAG, Log.DEBUG)) {
1611 Slog.d(TAG, "setUserIdentificationAssociation(): resp= " + resp
felipeal159a2a42020-05-08 10:32:11 -07001612 + ", converted=" + response);
1613 }
1614 result.complete(response);
1615 });
felipeal5e3ede42020-04-23 18:04:07 -07001616 }
1617
1618 /**
1619 * Gets the User HAL flags for the given user.
1620 *
1621 * @throws IllegalArgumentException if the user does not exist.
1622 */
1623 private int getHalUserInfoFlags(@UserIdInt int userId) {
1624 UserInfo user = mUserManager.getUserInfo(userId);
1625 Preconditions.checkArgument(user != null, "no user for id %d", userId);
1626 return UserHalHelper.convertFlags(user);
1627 }
1628
Mayank Garg0e239142020-04-14 19:16:31 -07001629 private void sendResult(@NonNull IResultReceiver receiver, int resultCode,
1630 @Nullable Bundle resultData) {
1631 try {
1632 receiver.send(resultCode, resultData);
1633 } catch (RemoteException e) {
1634 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001635 Slog.w(TAG, "error while sending results", e);
Mayank Garg0e239142020-04-14 19:16:31 -07001636 }
1637 }
1638
felipealdfdf8512020-06-01 09:35:45 -07001639 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
Felipe Leme5d5ab142020-10-27 13:49:10 -07001640 @UserSwitchResult.Status int userSwitchStatus) {
1641 sendUserSwitchResult(receiver, HalCallback.STATUS_INVALID, userSwitchStatus,
1642 /* errorMessage= */ null);
felipeale5bf0322020-04-16 15:10:57 -07001643 }
1644
felipealdfdf8512020-06-01 09:35:45 -07001645 private void sendUserSwitchResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
Felipe Leme5d5ab142020-10-27 13:49:10 -07001646 @HalCallback.HalCallbackStatus int halCallbackStatus,
1647 @UserSwitchResult.Status int userSwitchStatus, @Nullable String errorMessage) {
1648 if (errorMessage != null) {
1649 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, halCallbackStatus,
1650 userSwitchStatus, errorMessage);
1651 } else {
1652 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, halCallbackStatus,
1653 userSwitchStatus);
1654 }
1655 receiver.complete(new UserSwitchResult(userSwitchStatus, errorMessage));
felipeale5bf0322020-04-16 15:10:57 -07001656 }
1657
felipealdfdf8512020-06-01 09:35:45 -07001658 private void sendUserCreationResultFailure(@NonNull AndroidFuture<UserCreationResult> receiver,
1659 @UserCreationResult.Status int status) {
1660 sendUserCreationResult(receiver, status, /* user= */ null, /* errorMessage= */ null);
1661 }
1662
1663 private void sendUserCreationResult(@NonNull AndroidFuture<UserCreationResult> receiver,
1664 @UserCreationResult.Status int status, @NonNull UserInfo user,
1665 @Nullable String errorMessage) {
1666 if (TextUtils.isEmpty(errorMessage)) {
1667 errorMessage = null;
1668 }
1669 receiver.complete(new UserCreationResult(status, user, errorMessage));
1670 }
1671
Mayank Garg6307fe42020-04-15 23:09:03 -07001672 /**
1673 * Calls activity manager for user switch.
1674 *
1675 * <p><b>NOTE</b> This method is meant to be called just by UserHalService.
1676 *
1677 * @param requestId for the user switch request
1678 * @param targetUserId of the target user
1679 *
1680 * @hide
1681 */
1682 public void switchAndroidUserFromHal(int requestId, @UserIdInt int targetUserId) {
1683 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_FROM_HAL_REQ, requestId,
1684 targetUserId);
Eric Jeongf75d4132020-12-21 13:48:23 -08001685 Slog.i(TAG, "User hal requested a user switch. Target user id " + targetUserId);
Mayank Garg6307fe42020-04-15 23:09:03 -07001686
1687 try {
1688 boolean result = mAm.switchUser(targetUserId);
1689 if (result) {
1690 updateUserSwitchInProcess(requestId, targetUserId);
1691 } else {
1692 postSwitchHalResponse(requestId, targetUserId);
1693 }
1694 } catch (RemoteException e) {
1695 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001696 Slog.w(TAG, "error while switching user " + targetUserId, e);
Mayank Garg6307fe42020-04-15 23:09:03 -07001697 }
1698 }
1699
1700 private void updateUserSwitchInProcess(int requestId, @UserIdInt int targetUserId) {
1701 synchronized (mLockUser) {
1702 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
1703 // Some other user switch is in process.
Eric Jeongf75d4132020-12-21 13:48:23 -08001704 if (Log.isLoggable(TAG, Log.DEBUG)) {
1705 Slog.d(TAG, "User switch for user: " + mUserIdForUserSwitchInProcess
Mayank Garg6307fe42020-04-15 23:09:03 -07001706 + " is in process. Abandoning it as a new user switch is requested"
1707 + " for the target user: " + targetUserId);
1708 }
1709 }
1710 mUserIdForUserSwitchInProcess = targetUserId;
1711 mRequestIdForUserSwitchInProcess = requestId;
1712 }
1713 }
Mayank Garg9ed099e2020-06-04 16:05:20 -07001714
Mayank Garg7a114c82020-04-08 21:25:06 -07001715 private void postSwitchHalResponse(int requestId, @UserIdInt int targetUserId) {
Mayank Garg9ed099e2020-06-04 16:05:20 -07001716 if (!isUserHalSupported()) return;
1717
felipealdfdf8512020-06-01 09:35:45 -07001718 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager);
Mayank Gargeb37d092020-06-02 14:37:57 -07001719 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_POST_SWITCH_USER_REQ, requestId,
1720 targetUserId, usersInfo.currentUser.userId);
1721 SwitchUserRequest request = createUserSwitchRequest(targetUserId, usersInfo);
1722 request.requestId = requestId;
1723 mHal.postSwitchResponse(request);
1724 }
1725
1726 private SwitchUserRequest createUserSwitchRequest(@UserIdInt int targetUserId,
1727 @NonNull UsersInfo usersInfo) {
1728 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
Mayank Garg7a114c82020-04-08 21:25:06 -07001729 android.hardware.automotive.vehicle.V2_0.UserInfo halTargetUser =
1730 new android.hardware.automotive.vehicle.V2_0.UserInfo();
1731 halTargetUser.userId = targetUser.id;
1732 halTargetUser.flags = UserHalHelper.convertFlags(targetUser);
Mayank Gargeb37d092020-06-02 14:37:57 -07001733 SwitchUserRequest request = new SwitchUserRequest();
1734 request.targetUser = halTargetUser;
1735 request.usersInfo = usersInfo;
1736 return request;
Mayank Garg7a114c82020-04-08 21:25:06 -07001737 }
1738
Mayank Garg59f22192020-03-27 00:51:45 -07001739 /**
Felipe Lemee3cab982020-03-12 11:39:29 -07001740 * Checks if the User HAL is supported.
1741 */
1742 public boolean isUserHalSupported() {
1743 return mHal.isSupported();
1744 }
1745
Mayank Garg587f1942020-05-06 01:41:34 -07001746 /**
Mayank Garg9ed099e2020-06-04 16:05:20 -07001747 * Checks if the User HAL user association is supported.
1748 */
1749 @Override
1750 public boolean isUserHalUserAssociationSupported() {
1751 return mHal.isUserAssociationSupported();
1752 }
1753
1754 /**
Mayank Garg587f1942020-05-06 01:41:34 -07001755 * Sets a callback which is invoked before user switch.
1756 *
1757 * <p>
1758 * This method should only be called by the Car System UI. The purpose of this call is to notify
1759 * Car System UI to show the user switch UI before the user switch.
1760 */
1761 @Override
1762 public void setUserSwitchUiCallback(@NonNull IResultReceiver receiver) {
Yan Zhu67a383e2020-05-11 20:46:24 -07001763 checkManageUsersPermission("setUserSwitchUiCallback");
Mayank Garga480dd92020-05-14 03:14:57 -07001764
1765 // Confirm that caller is system UI.
1766 String systemUiPackageName = getSystemUiPackageName();
1767 if (systemUiPackageName == null) {
1768 throw new IllegalStateException("System UI package not found.");
1769 }
1770
1771 try {
1772 int systemUiUid = mContext
1773 .createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0).getPackageManager()
1774 .getPackageUid(systemUiPackageName, PackageManager.MATCH_SYSTEM_ONLY);
1775 int callerUid = Binder.getCallingUid();
1776 if (systemUiUid != callerUid) {
1777 throw new SecurityException("Invalid caller. Only" + systemUiPackageName
1778 + " is allowed to make this call");
1779 }
1780 } catch (NameNotFoundException e) {
1781 throw new IllegalStateException("Package " + systemUiPackageName + " not found.");
1782 }
1783
Mayank Garg587f1942020-05-06 01:41:34 -07001784 mUserSwitchUiReceiver = receiver;
1785 }
1786
Mayank Garga480dd92020-05-14 03:14:57 -07001787 // TODO(157082995): This information can be taken from
1788 // PackageManageInternalImpl.getSystemUiServiceComponent
1789 @Nullable
1790 private String getSystemUiPackageName() {
1791 try {
1792 ComponentName componentName = ComponentName.unflattenFromString(mContext.getResources()
1793 .getString(com.android.internal.R.string.config_systemUIServiceComponent));
1794 return componentName.getPackageName();
1795 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001796 Slog.w(TAG, "error while getting system UI package name.", e);
Mayank Garga480dd92020-05-14 03:14:57 -07001797 return null;
1798 }
1799 }
1800
Keun young Park13a7a822019-04-04 15:53:08 -07001801 private void updateDefaultUserRestriction() {
1802 // We want to set restrictions on system and guest users only once. These are persisted
1803 // onto disk, so it's sufficient to do it once + we minimize the number of disk writes.
1804 if (Settings.Global.getInt(mContext.getContentResolver(),
Eric Jeong1545f3b2019-09-16 13:56:52 -07001805 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, /* default= */ 0) != 0) {
1806 return;
Keun young Park13a7a822019-04-04 15:53:08 -07001807 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001808 // Only apply the system user restrictions if the system user is headless.
1809 if (UserManager.isHeadlessSystemUserMode()) {
1810 setSystemUserRestrictions();
1811 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001812 Settings.Global.putInt(mContext.getContentResolver(),
1813 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, 1);
Keun young Park13a7a822019-04-04 15:53:08 -07001814 }
1815
Eric Jeong1545f3b2019-09-16 13:56:52 -07001816 private boolean isPersistentUser(@UserIdInt int userId) {
Anthony Hugh9932a252019-06-12 16:19:56 -07001817 return !mUserManager.getUserInfo(userId).isEphemeral();
1818 }
1819
Antonio Kantekc8114752020-03-05 21:37:39 -08001820 /**
Antonio Kantekc8114752020-03-05 21:37:39 -08001821 * Adds a new {@link UserLifecycleListener} to listen to user activity events.
1822 */
1823 public void addUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1824 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001825 mHandler.post(() -> mUserLifecycleListeners.add(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001826 }
1827
1828 /**
1829 * Removes previously added {@link UserLifecycleListener}.
1830 */
1831 public void removeUserLifecycleListener(@NonNull UserLifecycleListener listener) {
1832 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001833 mHandler.post(() -> mUserLifecycleListeners.remove(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001834 }
1835
Eric Jeongc91f9452019-08-30 15:04:21 -07001836 /** Adds callback to listen to passenger activity events. */
1837 public void addPassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001838 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001839 mPassengerCallbacks.add(callback);
1840 }
1841
1842 /** Removes previously added callback to listen passenger events. */
1843 public void removePassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001844 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001845 mPassengerCallbacks.remove(callback);
1846 }
1847
1848 /** Sets the implementation of ZoneUserBindingHelper. */
1849 public void setZoneUserBindingHelper(@NonNull ZoneUserBindingHelper helper) {
1850 synchronized (mLockHelper) {
1851 mZoneUserBindingHelper = helper;
1852 }
1853 }
1854
felipeal98900c82020-04-09 09:05:02 -07001855 private void onUserUnlocked(@UserIdInt int userId) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001856 ArrayList<Runnable> tasks = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001857 synchronized (mLockUser) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001858 sendPostSwitchToHalLocked(userId);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001859 if (userId == UserHandle.USER_SYSTEM) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001860 if (!mUser0Unlocked) { // user 0, unlocked, do this only once
1861 updateDefaultUserRestriction();
1862 tasks = new ArrayList<>(mUser0UnlockTasks);
1863 mUser0UnlockTasks.clear();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001864 mUser0Unlocked = true;
Keun young Parkf3523cd2019-04-08 10:09:17 -07001865 }
1866 } else { // none user0
Eric Jeong1545f3b2019-09-16 13:56:52 -07001867 Integer user = userId;
1868 if (isPersistentUser(userId)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001869 // current foreground user should stay in top priority.
Anthony Hughfbb67762019-10-15 12:54:54 -07001870 if (userId == ActivityManager.getCurrentUser()) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001871 mBackgroundUsersToRestart.remove(user);
1872 mBackgroundUsersToRestart.add(0, user);
1873 }
1874 // -1 for user 0
1875 if (mBackgroundUsersToRestart.size() > (mMaxRunningUsers - 1)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001876 int userToDrop = mBackgroundUsersToRestart.get(
Keun young Parkf3523cd2019-04-08 10:09:17 -07001877 mBackgroundUsersToRestart.size() - 1);
Eric Jeongf75d4132020-12-21 13:48:23 -08001878 Slog.i(TAG, "New user unlocked:" + userId
Keun young Parkf3523cd2019-04-08 10:09:17 -07001879 + ", dropping least recently user from restart list:" + userToDrop);
1880 // Drop the least recently used user.
1881 mBackgroundUsersToRestart.remove(mBackgroundUsersToRestart.size() - 1);
1882 }
1883 }
Keun-young Parkd462a912019-02-11 08:53:42 -08001884 }
1885 }
1886 if (tasks != null && tasks.size() > 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08001887 Slog.d(TAG, "User0 unlocked, run queued tasks:" + tasks.size());
Keun-young Parkd462a912019-02-11 08:53:42 -08001888 for (Runnable r : tasks) {
1889 r.run();
1890 }
1891 }
1892 }
1893
1894 /**
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001895 * Starts the specified user in the background.
1896 *
1897 * @param userId user to start in background
1898 * @param receiver to post results
1899 */
1900 public void startUserInBackground(@UserIdInt int userId,
1901 @NonNull AndroidFuture<UserStartResult> receiver) {
bkchoi5ab7aa32021-04-27 11:50:53 -07001902 checkManageOrCreateUsersPermission("startUserInBackground");
1903 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_START_USER_IN_BACKGROUND_REQ, userId);
1904
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001905 mHandler.post(() -> handleStartUserInBackground(userId, receiver));
1906 }
1907
1908 private void handleStartUserInBackground(@UserIdInt int userId,
1909 @NonNull AndroidFuture<UserStartResult> receiver) {
1910 // If the requested user is the current user, do nothing and return success.
1911 if (ActivityManager.getCurrentUser() == userId) {
bkchoi5ab7aa32021-04-27 11:50:53 -07001912 sendUserStartResult(
1913 userId, UserStartResult.STATUS_SUCCESSFUL_USER_IS_CURRENT_USER, receiver);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001914 return;
1915 }
1916 // If requested user does not exist, return error.
1917 if (mUserManager.getUserInfo(userId) == null) {
1918 Slogf.w(TAG, "User %d does not exist", userId);
bkchoi5ab7aa32021-04-27 11:50:53 -07001919 sendUserStartResult(userId, UserStartResult.STATUS_USER_DOES_NOT_EXIST, receiver);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001920 return;
1921 }
1922
1923 try {
1924 if (!mAm.startUserInBackground(userId)) {
1925 Slogf.w(TAG, "Failed to start user %d in background", userId);
bkchoi5ab7aa32021-04-27 11:50:53 -07001926 sendUserStartResult(userId, UserStartResult.STATUS_ANDROID_FAILURE, receiver);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001927 return;
1928 }
1929 } catch (RemoteException e) {
1930 Slogf.w(TAG, e, "Failed to start user %d in background", userId);
1931 }
1932
1933 // TODO(b/181331178): We are not updating mBackgroundUsersToRestart or
1934 // mBackgroundUsersRestartedHere, which were only used for the garage mode. Consider
1935 // renaming them to make it more clear.
bkchoi5ab7aa32021-04-27 11:50:53 -07001936 sendUserStartResult(userId, UserStartResult.STATUS_SUCCESSFUL, receiver);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001937 }
1938
bkchoi5ab7aa32021-04-27 11:50:53 -07001939 private void sendUserStartResult(@UserIdInt int userId, @UserStartResult.Status int result,
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001940 @NonNull AndroidFuture<UserStartResult> receiver) {
bkchoi5ab7aa32021-04-27 11:50:53 -07001941 EventLog.writeEvent(
1942 EventLogTags.CAR_USER_SVC_START_USER_IN_BACKGROUND_RESP, userId, result);
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07001943 receiver.complete(new UserStartResult(result));
1944 }
1945
1946 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001947 * Starts all background users that were active in system.
1948 *
Keun young Parkfb656372019-03-12 18:37:55 -07001949 * @return list of background users started successfully.
1950 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001951 @NonNull
Mayank Garg784a0862021-05-26 00:20:50 -07001952 public ArrayList<Integer> startAllBackgroundUsersInGarageMode() {
1953 synchronized (mLockUser) {
1954 if (!mStartBackgroundUsersOnGarageMode) {
1955 Slogf.i(TAG, "Background users are not started as mStartBackgroundUsersOnGarageMode"
1956 + " is false.");
1957 return new ArrayList<>();
1958 }
1959 }
1960
Keun young Parkfb656372019-03-12 18:37:55 -07001961 ArrayList<Integer> users;
Eric Jeongc91f9452019-08-30 15:04:21 -07001962 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001963 users = new ArrayList<>(mBackgroundUsersToRestart);
1964 mBackgroundUsersRestartedHere.clear();
1965 mBackgroundUsersRestartedHere.addAll(mBackgroundUsersToRestart);
Keun young Parkfb656372019-03-12 18:37:55 -07001966 }
1967 ArrayList<Integer> startedUsers = new ArrayList<>();
1968 for (Integer user : users) {
Anthony Hughfbb67762019-10-15 12:54:54 -07001969 if (user == ActivityManager.getCurrentUser()) {
Keun young Parkfb656372019-03-12 18:37:55 -07001970 continue;
1971 }
1972 try {
1973 if (mAm.startUserInBackground(user)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001974 if (mUserManager.isUserUnlockingOrUnlocked(user)) {
1975 // already unlocked / unlocking. No need to unlock.
Keun young Parkfb656372019-03-12 18:37:55 -07001976 startedUsers.add(user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001977 } else if (mAm.unlockUser(user, null, null, null)) {
1978 startedUsers.add(user);
1979 } else { // started but cannot unlock
Eric Jeongf75d4132020-12-21 13:48:23 -08001980 Slog.w(TAG, "Background user started but cannot be unlocked:" + user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001981 if (mUserManager.isUserRunning(user)) {
1982 // add to started list so that it can be stopped later.
1983 startedUsers.add(user);
1984 }
Keun young Parkfb656372019-03-12 18:37:55 -07001985 }
1986 }
1987 } catch (RemoteException e) {
1988 // ignore
Eric Jeongf75d4132020-12-21 13:48:23 -08001989 Slog.w(TAG, "error while starting user in background", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001990 }
1991 }
Keun young Parkf3523cd2019-04-08 10:09:17 -07001992 // Keep only users that were re-started in mBackgroundUsersRestartedHere
Eric Jeongc91f9452019-08-30 15:04:21 -07001993 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001994 ArrayList<Integer> usersToRemove = new ArrayList<>();
1995 for (Integer user : mBackgroundUsersToRestart) {
1996 if (!startedUsers.contains(user)) {
1997 usersToRemove.add(user);
1998 }
1999 }
2000 mBackgroundUsersRestartedHere.removeAll(usersToRemove);
2001 }
Keun young Parkfb656372019-03-12 18:37:55 -07002002 return startedUsers;
2003 }
2004
2005 /**
bkchoid77d0bc2021-04-22 13:43:03 -07002006 * Stops the specified background user.
2007 *
2008 * @param userId user to stop
2009 * @param receiver to post results
2010 */
2011 public void stopUser(@UserIdInt int userId, @NonNull AndroidFuture<UserStopResult> receiver) {
bkchoia8c7fb92021-04-28 10:58:57 -07002012 checkManageOrCreateUsersPermission("stopUser");
2013 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_STOP_USER_REQ, userId);
2014
bkchoid77d0bc2021-04-22 13:43:03 -07002015 mHandler.post(() -> handleStopUser(userId, receiver));
2016 }
2017
2018 private void handleStopUser(
2019 @UserIdInt int userId, @NonNull AndroidFuture<UserStopResult> receiver) {
2020 @UserStopResult.Status int userStopStatus = stopBackgroundUserInternal(userId);
bkchoia8c7fb92021-04-28 10:58:57 -07002021 sendUserStopResult(userId, userStopStatus, receiver);
bkchoid77d0bc2021-04-22 13:43:03 -07002022 }
2023
bkchoia8c7fb92021-04-28 10:58:57 -07002024 private void sendUserStopResult(@UserIdInt int userId, @UserStopResult.Status int result,
bkchoid77d0bc2021-04-22 13:43:03 -07002025 @NonNull AndroidFuture<UserStopResult> receiver) {
bkchoia8c7fb92021-04-28 10:58:57 -07002026 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_STOP_USER_RESP, userId, result);
bkchoid77d0bc2021-04-22 13:43:03 -07002027 receiver.complete(new UserStopResult(result));
2028 }
2029
2030 private @UserStopResult.Status int stopBackgroundUserInternal(@UserIdInt int userId) {
2031 try {
2032 int r = mAm.stopUserWithDelayedLocking(userId, true, null);
2033 switch(r) {
2034 case ActivityManager.USER_OP_SUCCESS:
2035 return UserStopResult.STATUS_SUCCESSFUL;
2036 case ActivityManager.USER_OP_ERROR_IS_SYSTEM:
2037 Slogf.w(TAG, "Cannot stop the system user: %d", userId);
2038 return UserStopResult.STATUS_FAILURE_SYSTEM_USER;
2039 case ActivityManager.USER_OP_IS_CURRENT:
2040 Slogf.w(TAG, "Cannot stop the current user: %d", userId);
2041 return UserStopResult.STATUS_FAILURE_CURRENT_USER;
2042 case ActivityManager.USER_OP_UNKNOWN_USER:
2043 Slogf.w(TAG, "Cannot stop the user that does not exist: %d", userId);
2044 return UserStopResult.STATUS_USER_DOES_NOT_EXIST;
2045 default:
2046 Slogf.w(TAG, "stopUser failed, user: %d, err: %d", userId, r);
2047 }
2048 } catch (RemoteException e) {
2049 // ignore the exception
2050 Slogf.w(TAG, e, "error while stopping user: %d", userId);
2051 }
2052 return UserStopResult.STATUS_ANDROID_FAILURE;
2053 }
2054
2055 /**
Mayank Garg784a0862021-05-26 00:20:50 -07002056 * Sets boolean to control background user operations during garage mode.
2057 */
2058 public void setStartBackgroundUsersOnGarageMode(boolean enable) {
2059 synchronized (mLockUser) {
2060 mStartBackgroundUsersOnGarageMode = enable;
2061 }
2062 }
2063
2064 /**
Bo-Kyung (BK) Choia6503f42021-04-19 14:34:00 -07002065 * Stops a background user.
Eric Jeong1545f3b2019-09-16 13:56:52 -07002066 *
2067 * @return whether stopping succeeds.
Keun young Parkfb656372019-03-12 18:37:55 -07002068 */
Mayank Garg784a0862021-05-26 00:20:50 -07002069 public boolean stopBackgroundUserInGagageMode(@UserIdInt int userId) {
2070 synchronized (mLockUser) {
2071 if (!mStartBackgroundUsersOnGarageMode) {
2072 Slogf.i(TAG, "Background users are not stopped as mStartBackgroundUsersOnGarageMode"
2073 + " is false.");
2074 return false;
2075 }
2076 }
2077
bkchoid77d0bc2021-04-22 13:43:03 -07002078 @UserStopResult.Status int userStopStatus = stopBackgroundUserInternal(userId);
2079 if (UserStopResult.isSuccess(userStopStatus)) {
2080 // Remove the stopped user from the mBackgroundUserRestartedHere list.
2081 synchronized (mLockUser) {
2082 mBackgroundUsersRestartedHere.remove(Integer.valueOf(userId));
Keun young Parkfb656372019-03-12 18:37:55 -07002083 }
bkchoid77d0bc2021-04-22 13:43:03 -07002084 return true;
Keun young Parkfb656372019-03-12 18:37:55 -07002085 }
bkchoid77d0bc2021-04-22 13:43:03 -07002086 return false;
Keun young Parkfb656372019-03-12 18:37:55 -07002087 }
2088
2089 /**
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002090 * Notifies all registered {@link UserLifecycleListener} with the event passed as argument.
Pavel Maltsev17e81832019-04-04 14:38:41 -07002091 */
Mayank Gargccad8062020-08-30 15:05:10 -07002092 public void onUserLifecycleEvent(@UserLifecycleEventType int eventType,
felipeale8c5dce2020-04-15 11:27:06 -07002093 @UserIdInt int fromUserId, @UserIdInt int toUserId) {
2094 int userId = toUserId;
felipeal98900c82020-04-09 09:05:02 -07002095
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002096 // Handle special cases first...
felipeal98900c82020-04-09 09:05:02 -07002097 if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_SWITCHING) {
Mayank Garge5de0f92020-04-23 21:38:38 -07002098 onUserSwitching(fromUserId, toUserId);
felipeal98900c82020-04-09 09:05:02 -07002099 } else if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
2100 onUserUnlocked(userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002101 }
2102
felipeale8c5dce2020-04-15 11:27:06 -07002103 // ...then notify listeners.
Yan Zhue7921522020-04-16 15:59:25 -07002104 UserLifecycleEvent event = new UserLifecycleEvent(eventType, fromUserId, userId);
felipeale8c5dce2020-04-15 11:27:06 -07002105
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002106 mHandler.post(() -> {
2107 handleNotifyServiceUserLifecycleListeners(event);
2108 handleNotifyAppUserLifecycleListeners(event);
2109 });
felipeale8c5dce2020-04-15 11:27:06 -07002110 }
2111
Mayank Garg7a114c82020-04-08 21:25:06 -07002112 private void sendPostSwitchToHalLocked(@UserIdInt int userId) {
felipealf7368962020-04-16 12:55:19 -07002113 if (mUserIdForUserSwitchInProcess == UserHandle.USER_NULL
Mayank Garg1f20dcd2020-04-22 17:46:01 -07002114 || mUserIdForUserSwitchInProcess != userId
2115 || mRequestIdForUserSwitchInProcess == 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002116 if (Log.isLoggable(TAG, Log.DEBUG)) {
2117 Slog.d(TAG, "No user switch request Id. No android post switch sent.");
Mayank Garg7a114c82020-04-08 21:25:06 -07002118 }
2119 return;
2120 }
felipealf7368962020-04-16 12:55:19 -07002121 postSwitchHalResponse(mRequestIdForUserSwitchInProcess, mUserIdForUserSwitchInProcess);
2122 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg1f20dcd2020-04-22 17:46:01 -07002123 mRequestIdForUserSwitchInProcess = 0;
Mayank Garg7a114c82020-04-08 21:25:06 -07002124 }
2125
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002126 private void handleNotifyAppUserLifecycleListeners(UserLifecycleEvent event) {
2127 int listenersSize = mAppLifecycleListeners.size();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002128 if (listenersSize == 0) {
Felipe Lemefaf67042021-07-08 11:24:00 -07002129 Slogf.d(TAG, "No app listener to be notified of %s", event);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002130 return;
2131 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002132 // Must use a different TimingsTraceLog because it's another thread
Felipe Lemefaf67042021-07-08 11:24:00 -07002133 Slogf.d(TAG, "Notifying %d app listeners of %s", listenersSize, event);
felipeal2a84d512020-04-06 18:52:15 -07002134 int userId = event.getUserId();
Eric Jeongf75d4132020-12-21 13:48:23 -08002135 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
felipealde1e16d2020-06-03 13:20:48 -07002136 int eventType = event.getEventType();
2137 t.traceBegin("notify-app-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002138 for (int i = 0; i < listenersSize; i++) {
Felipe Lemefaf67042021-07-08 11:24:00 -07002139 AppLifecycleListener listener = mAppLifecycleListeners.valueAt(i);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002140 Bundle data = new Bundle();
felipealde1e16d2020-06-03 13:20:48 -07002141 data.putInt(CarUserManager.BUNDLE_PARAM_ACTION, eventType);
Yan Zhue7921522020-04-16 15:59:25 -07002142
felipealde1e16d2020-06-03 13:20:48 -07002143 int fromUserId = event.getPreviousUserId();
2144 if (fromUserId != UserHandle.USER_NULL) {
2145 data.putInt(CarUserManager.BUNDLE_PARAM_PREVIOUS_USER_ID, fromUserId);
Yan Zhue7921522020-04-16 15:59:25 -07002146 }
Felipe Lemefaf67042021-07-08 11:24:00 -07002147 Slogf.d(TAG, "Notifying listener %s", listener);
felipealde1e16d2020-06-03 13:20:48 -07002148 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_APP_LIFECYCLE_LISTENER,
Felipe Lemefaf67042021-07-08 11:24:00 -07002149 listener.uid, listener.packageName, eventType, fromUserId, userId);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002150 try {
Felipe Lemefaf67042021-07-08 11:24:00 -07002151 t.traceBegin("notify-app-listener-" + listener.toShortString());
2152 listener.receiver.send(userId, data);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002153 } catch (RemoteException e) {
Felipe Lemefaf67042021-07-08 11:24:00 -07002154 Slogf.e(TAG, e, "Error calling lifecycle listener %s", listener);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002155 } finally {
2156 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002157 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002158 }
2159 t.traceEnd(); // notify-app-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002160 }
2161
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002162 private void handleNotifyServiceUserLifecycleListeners(UserLifecycleEvent event) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002163 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002164 if (mUserLifecycleListeners.isEmpty()) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002165 Slog.w(TAG, "Not notifying internal UserLifecycleListeners");
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002166 return;
Eric Jeongf75d4132020-12-21 13:48:23 -08002167 } else if (Log.isLoggable(TAG, Log.DEBUG)) {
2168 Slog.d(TAG, "Notifying " + mUserLifecycleListeners.size()
2169 + " service listeners of " + event);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002170 }
felipeal2a84d512020-04-06 18:52:15 -07002171
felipealde1e16d2020-06-03 13:20:48 -07002172 int userId = event.getUserId();
2173 int eventType = event.getEventType();
2174 t.traceBegin("notify-listeners-user-" + userId + "-event-" + eventType);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002175 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipeal2a84d512020-04-06 18:52:15 -07002176 String listenerName = FunctionalUtils.getLambdaName(listener);
felipealde1e16d2020-06-03 13:20:48 -07002177 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_NOTIFY_INTERNAL_LIFECYCLE_LISTENER,
2178 listenerName, eventType, event.getPreviousUserId(), userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002179 try {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002180 t.traceBegin("notify-listener-" + listenerName);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002181 listener.onEvent(event);
2182 } catch (RuntimeException e) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002183 Slog.e(TAG,
felipeal2a84d512020-04-06 18:52:15 -07002184 "Exception raised when invoking onEvent for " + listenerName, e);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002185 } finally {
2186 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002187 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002188 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07002189 t.traceEnd(); // notify-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002190 }
2191
Mayank Garge5de0f92020-04-23 21:38:38 -07002192 private void onUserSwitching(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002193 Slog.i(TAG, "onUserSwitching() callback for user " + toUserId);
2194 TimingsTraceLog t = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
Mayank Garge5de0f92020-04-23 21:38:38 -07002195 t.traceBegin("onUserSwitching-" + toUserId);
Felipe Leme5528ff72020-02-10 19:05:14 -08002196
Mayank Garge5de0f92020-04-23 21:38:38 -07002197 // Switch HAL users if user switch is not requested by CarUserService
2198 notifyHalLegacySwitch(fromUserId, toUserId);
2199
Mayank Garge90a4082020-09-30 12:57:34 -07002200 mInitialUserSetter.setLastActiveUser(toUserId);
felipealbf327652020-06-03 11:33:29 -07002201
Eric Jeongc91f9452019-08-30 15:04:21 -07002202 if (mLastPassengerId != UserHandle.USER_NULL) {
2203 stopPassengerInternal(mLastPassengerId, false);
2204 }
2205 if (mEnablePassengerSupport && isPassengerDisplayAvailable()) {
2206 setupPassengerUser();
Mayank Garge5de0f92020-04-23 21:38:38 -07002207 startFirstPassenger(toUserId);
Eric Jeongc91f9452019-08-30 15:04:21 -07002208 }
felipeal98900c82020-04-09 09:05:02 -07002209 t.traceEnd();
Pavel Maltsev17e81832019-04-04 14:38:41 -07002210 }
2211
Mayank Garge5de0f92020-04-23 21:38:38 -07002212 private void notifyHalLegacySwitch(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
2213 synchronized (mLockUser) {
felipeal7d12ee22020-06-05 09:30:19 -07002214 if (mUserIdForUserSwitchInProcess != UserHandle.USER_NULL) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002215 if (Log.isLoggable(TAG, Log.DEBUG)) {
2216 Slog.d(TAG, "notifyHalLegacySwitch(" + fromUserId + ", " + toUserId
felipeal7d12ee22020-06-05 09:30:19 -07002217 + "): not needed, normal switch for " + mUserIdForUserSwitchInProcess);
2218 }
2219 return;
2220 }
Mayank Garge5de0f92020-04-23 21:38:38 -07002221 }
2222
Mayank Garg9ed099e2020-06-04 16:05:20 -07002223 if (!isUserHalSupported()) return;
2224
Mayank Garge5de0f92020-04-23 21:38:38 -07002225 // switch HAL user
felipeal7d12ee22020-06-05 09:30:19 -07002226 UsersInfo usersInfo = UserHalHelper.newUsersInfo(mUserManager, fromUserId);
Mayank Gargeb37d092020-06-02 14:37:57 -07002227 SwitchUserRequest request = createUserSwitchRequest(toUserId, usersInfo);
2228 mHal.legacyUserSwitch(request);
Mayank Garge5de0f92020-04-23 21:38:38 -07002229 }
2230
Pavel Maltsev17e81832019-04-04 14:38:41 -07002231 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07002232 * 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 -08002233 * run inside this call.
Eric Jeong1545f3b2019-09-16 13:56:52 -07002234 *
Keun-young Parkd462a912019-02-11 08:53:42 -08002235 * @param r Runnable to run.
2236 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07002237 public void runOnUser0Unlock(@NonNull Runnable r) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00002238 Objects.requireNonNull(r, "runnable cannot be null");
Keun-young Parkd462a912019-02-11 08:53:42 -08002239 boolean runNow = false;
Eric Jeongc91f9452019-08-30 15:04:21 -07002240 synchronized (mLockUser) {
Keun-young Parkd462a912019-02-11 08:53:42 -08002241 if (mUser0Unlocked) {
2242 runNow = true;
2243 } else {
2244 mUser0UnlockTasks.add(r);
2245 }
2246 }
2247 if (runNow) {
2248 r.run();
2249 }
2250 }
2251
Keun young Parkf3523cd2019-04-08 10:09:17 -07002252 @VisibleForTesting
Eric Jeong1545f3b2019-09-16 13:56:52 -07002253 @NonNull
2254 ArrayList<Integer> getBackgroundUsersToRestart() {
2255 ArrayList<Integer> backgroundUsersToRestart = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07002256 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07002257 backgroundUsersToRestart = new ArrayList<>(mBackgroundUsersToRestart);
2258 }
2259 return backgroundUsersToRestart;
2260 }
2261
Ying Zheng1ab32b62018-06-26 12:47:26 -07002262 private void setSystemUserRestrictions() {
Ying Zheng1ab32b62018-06-26 12:47:26 -07002263 // Disable Location service for system user.
2264 LocationManager locationManager =
2265 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Anthony Hugh04ee04f2019-12-17 16:11:33 -08002266 locationManager.setLocationEnabledForUser(
2267 /* enabled= */ false, UserHandle.of(UserHandle.USER_SYSTEM));
Grace Cheng39219492021-10-08 15:42:57 -07002268 locationManager.setAdasGnssLocationEnabled(false);
Ying Zheng1ab32b62018-06-26 12:47:26 -07002269 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07002270
2271 /**
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002272 * Assigns a default icon to a user according to the user's id.
2273 *
2274 * @param userInfo User whose avatar is set to default icon.
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002275 */
Eric Jeongb2dc6ff2020-06-05 17:00:26 -07002276 private void assignDefaultIcon(UserInfo userInfo) {
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002277 int idForIcon = userInfo.isGuest() ? UserHandle.USER_NULL : userInfo.id;
2278 Bitmap bitmap = UserIcons.convertToBitmap(
2279 UserIcons.getDefaultUserIcon(mContext.getResources(), idForIcon, false));
2280 mUserManager.setUserIcon(userInfo.id, bitmap);
Anthony Hugh6fed1e92019-10-22 16:22:03 -07002281 }
2282
Eric Jeong1545f3b2019-09-16 13:56:52 -07002283 private interface UserFilter {
2284 boolean isEligibleUser(UserInfo user);
2285 }
2286
2287 /** Returns all users who are matched by the given filter. */
2288 private List<UserInfo> getUsers(UserFilter filter) {
Colin Cross0df71ea2020-08-27 04:12:26 +00002289 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeong1545f3b2019-09-16 13:56:52 -07002290
2291 for (Iterator<UserInfo> iterator = users.iterator(); iterator.hasNext(); ) {
2292 UserInfo user = iterator.next();
2293 if (!filter.isEligibleUser(user)) {
2294 iterator.remove();
2295 }
2296 }
2297 return users;
2298 }
2299
felipeal2d0483c2019-11-02 14:07:22 -07002300 private static void checkManageUsersOrDumpPermission(String message) {
Felipe Leme55236722020-10-16 16:54:32 -07002301 checkHasAtLeastOnePermissionGranted(message,
felipeal2d0483c2019-11-02 14:07:22 -07002302 android.Manifest.permission.MANAGE_USERS,
2303 android.Manifest.permission.DUMP);
2304 }
2305
Felipe Leme5528ff72020-02-10 19:05:14 -08002306 private void checkInteractAcrossUsersPermission(String message) {
Felipe Leme55236722020-10-16 16:54:32 -07002307 checkHasAtLeastOnePermissionGranted(message,
2308 android.Manifest.permission.INTERACT_ACROSS_USERS,
Felipe Leme5528ff72020-02-10 19:05:14 -08002309 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
2310 }
2311
Eric Jeongc91f9452019-08-30 15:04:21 -07002312 private int getNumberOfManagedProfiles(@UserIdInt int userId) {
Colin Cross0df71ea2020-08-27 04:12:26 +00002313 List<UserInfo> users = mUserManager.getAliveUsers();
Eric Jeongc91f9452019-08-30 15:04:21 -07002314 // Count all users that are managed profiles of the given user.
2315 int managedProfilesCount = 0;
2316 for (UserInfo user : users) {
2317 if (user.isManagedProfile() && user.profileGroupId == userId) {
2318 managedProfilesCount++;
2319 }
2320 }
2321 return managedProfilesCount;
2322 }
2323
2324 /**
2325 * Starts the first passenger of the given driver and assigns the passenger to the front
2326 * passenger zone.
2327 *
2328 * @param driverId User id of the driver.
2329 * @return whether it succeeds.
2330 */
2331 private boolean startFirstPassenger(@UserIdInt int driverId) {
2332 int zoneId = getAvailablePassengerZone();
2333 if (zoneId == OccupantZoneInfo.INVALID_ZONE_ID) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002334 Slog.w(TAG, "passenger occupant zone is not found");
Eric Jeongc91f9452019-08-30 15:04:21 -07002335 return false;
2336 }
2337 List<UserInfo> passengers = getPassengers(driverId);
2338 if (passengers.size() < 1) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002339 Slog.w(TAG, "passenger is not found");
Eric Jeongc91f9452019-08-30 15:04:21 -07002340 return false;
2341 }
2342 // Only one passenger is supported. If there are two or more passengers, the first passenger
2343 // is chosen.
2344 int passengerId = passengers.get(0).id;
2345 if (!startPassenger(passengerId, zoneId)) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002346 Slog.w(TAG, "cannot start passenger " + passengerId);
Eric Jeongc91f9452019-08-30 15:04:21 -07002347 return false;
2348 }
2349 return true;
2350 }
2351
2352 private int getAvailablePassengerZone() {
2353 int[] occupantTypes = new int[] {CarOccupantZoneManager.OCCUPANT_TYPE_FRONT_PASSENGER,
2354 CarOccupantZoneManager.OCCUPANT_TYPE_REAR_PASSENGER};
2355 for (int occupantType : occupantTypes) {
2356 int zoneId = getZoneId(occupantType);
2357 if (zoneId != OccupantZoneInfo.INVALID_ZONE_ID) {
2358 return zoneId;
2359 }
2360 }
2361 return OccupantZoneInfo.INVALID_ZONE_ID;
2362 }
2363
2364 /**
2365 * Creates a new passenger user when there is no passenger user.
2366 */
2367 private void setupPassengerUser() {
2368 int currentUser = ActivityManager.getCurrentUser();
2369 int profileCount = getNumberOfManagedProfiles(currentUser);
2370 if (profileCount > 0) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002371 Slog.w(TAG, "max profile of user" + currentUser
Eric Jeongc91f9452019-08-30 15:04:21 -07002372 + " is exceeded: current profile count is " + profileCount);
2373 return;
2374 }
2375 // TODO(b/140311342): Use resource string for the default passenger name.
2376 UserInfo passenger = createPassenger("Passenger", currentUser);
2377 if (passenger == null) {
2378 // Couldn't create user, most likely because there are too many.
Eric Jeongf75d4132020-12-21 13:48:23 -08002379 Slog.w(TAG, "cannot create a passenger user");
Eric Jeongc91f9452019-08-30 15:04:21 -07002380 return;
2381 }
2382 }
2383
2384 @NonNull
2385 private List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType) {
2386 ZoneUserBindingHelper helper = null;
2387 synchronized (mLockHelper) {
2388 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002389 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002390 return new ArrayList<OccupantZoneInfo>();
2391 }
2392 helper = mZoneUserBindingHelper;
2393 }
2394 return helper.getOccupantZones(occupantType);
2395 }
2396
2397 private boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId) {
2398 ZoneUserBindingHelper helper = null;
2399 synchronized (mLockHelper) {
2400 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002401 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002402 return false;
2403 }
2404 helper = mZoneUserBindingHelper;
2405 }
2406 return helper.assignUserToOccupantZone(userId, zoneId);
2407 }
2408
2409 private boolean unassignUserFromOccupantZone(@UserIdInt int userId) {
2410 ZoneUserBindingHelper helper = null;
2411 synchronized (mLockHelper) {
2412 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002413 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002414 return false;
2415 }
2416 helper = mZoneUserBindingHelper;
2417 }
2418 return helper.unassignUserFromOccupantZone(userId);
2419 }
2420
2421 private boolean isPassengerDisplayAvailable() {
2422 ZoneUserBindingHelper helper = null;
2423 synchronized (mLockHelper) {
2424 if (mZoneUserBindingHelper == null) {
Eric Jeongf75d4132020-12-21 13:48:23 -08002425 Slog.w(TAG, "implementation is not delegated");
Eric Jeongc91f9452019-08-30 15:04:21 -07002426 return false;
2427 }
2428 helper = mZoneUserBindingHelper;
2429 }
2430 return helper.isPassengerDisplayAvailable();
2431 }
2432
2433 /**
2434 * Gets the zone id of the given occupant type. If there are two or more zones, the first found
2435 * zone is returned.
2436 *
2437 * @param occupantType The type of an occupant.
2438 * @return The zone id of the given occupant type. {@link OccupantZoneInfo.INVALID_ZONE_ID},
2439 * if not found.
2440 */
2441 private int getZoneId(@OccupantTypeEnum int occupantType) {
2442 List<OccupantZoneInfo> zoneInfos = getOccupantZones(occupantType);
2443 return (zoneInfos.size() > 0) ? zoneInfos.get(0).zoneId : OccupantZoneInfo.INVALID_ZONE_ID;
2444 }
Mayank Garg9732d602020-08-09 21:02:40 -07002445
2446 /**
2447 * Manages the required number of pre-created users.
2448 */
Mayank Garga3b72d02021-03-14 23:05:51 -07002449 @Override
2450 public void updatePreCreatedUsers() {
2451 checkManageOrCreateUsersPermission("preCreateUsers");
2452 preCreateUsersInternal();
Mayank Garg02576972021-02-18 16:46:07 -08002453 }
2454
Mayank Garga3b72d02021-03-14 23:05:51 -07002455 private void preCreateUsersInternal() {
2456 mHandler.post(() -> mUserPreCreator.managePreCreatedUsers());
Mayank Garg9732d602020-08-09 21:02:40 -07002457 }
Felipe Leme17799202020-09-03 12:55:53 -07002458
2459 // TODO(b/167698977): members below were copied from UserManagerService; it would be better to
2460 // move them to some internal android.os class instead.
2461
2462 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
2463 UserInfo.FLAG_MANAGED_PROFILE
2464 | UserInfo.FLAG_PROFILE
2465 | UserInfo.FLAG_EPHEMERAL
2466 | UserInfo.FLAG_RESTRICTED
2467 | UserInfo.FLAG_GUEST
2468 | UserInfo.FLAG_DEMO
2469 | UserInfo.FLAG_FULL;
2470
2471 private static void checkManageUsersPermission(String message) {
2472 if (!hasManageUsersPermission()) {
2473 throw new SecurityException("You need " + MANAGE_USERS + " permission to: " + message);
2474 }
2475 }
2476
2477 private static void checkManageOrCreateUsersPermission(String message) {
2478 if (!hasManageOrCreateUsersPermission()) {
2479 throw new SecurityException(
2480 "You either need " + MANAGE_USERS + " or " + CREATE_USERS + " permission to: "
2481 + message);
2482 }
2483 }
2484
2485 private static void checkManageOrCreateUsersPermission(int creationFlags) {
2486 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2487 if (!hasManageOrCreateUsersPermission()) {
2488 throw new SecurityException("You either need " + MANAGE_USERS + " or "
2489 + CREATE_USERS + "permission to create a user with flags "
2490 + creationFlags);
2491 }
2492 } else if (!hasManageUsersPermission()) {
2493 throw new SecurityException("You need " + MANAGE_USERS + " permission to create a user"
2494 + " with flags " + creationFlags);
2495 }
2496 }
2497
2498 private static boolean hasManageUsersPermission() {
2499 final int callingUid = Binder.getCallingUid();
2500 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2501 || callingUid == Process.ROOT_UID
2502 || hasPermissionGranted(MANAGE_USERS, callingUid);
2503 }
2504
2505 private static boolean hasManageUsersOrPermission(String alternativePermission) {
2506 final int callingUid = Binder.getCallingUid();
2507 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2508 || callingUid == Process.ROOT_UID
2509 || hasPermissionGranted(MANAGE_USERS, callingUid)
2510 || hasPermissionGranted(alternativePermission, callingUid);
2511 }
2512
2513 private static boolean hasManageOrCreateUsersPermission() {
2514 return hasManageUsersOrPermission(CREATE_USERS);
2515 }
2516
2517 private static boolean hasPermissionGranted(String permission, int uid) {
2518 return ActivityManager.checkComponentPermission(permission, uid, /* owningUid= */ -1,
2519 /* exported= */ true) == PackageManager.PERMISSION_GRANTED;
2520 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07002521}