blob: f19381553523f1be965c0b68cde8c51d73f83f86 [file] [log] [blame]
Ying Zhengd3cb98e2018-05-11 11:42:48 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.car.user;
18
Eric Jeong1545f3b2019-09-16 13:56:52 -070019import static com.android.car.CarLog.TAG_USER;
20
21import android.annotation.NonNull;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070022import android.annotation.Nullable;
Eric Jeong1545f3b2019-09-16 13:56:52 -070023import android.annotation.UserIdInt;
Keun young Parkfb656372019-03-12 18:37:55 -070024import android.app.ActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070025import android.app.ActivityManager.StackInfo;
Keun young Parkfb656372019-03-12 18:37:55 -070026import android.app.IActivityManager;
Eric Jeongc91f9452019-08-30 15:04:21 -070027import android.car.CarOccupantZoneManager;
28import android.car.CarOccupantZoneManager.OccupantTypeEnum;
29import android.car.CarOccupantZoneManager.OccupantZoneInfo;
Eric Jeong1545f3b2019-09-16 13:56:52 -070030import android.car.ICarUserService;
jovanak24470652018-09-11 17:51:57 -070031import android.car.settings.CarSettings;
Felipe Leme5528ff72020-02-10 19:05:14 -080032import android.car.user.CarUserManager;
Antonio Kantekc8114752020-03-05 21:37:39 -080033import android.car.user.CarUserManager.UserLifecycleEvent;
felipeale8c5dce2020-04-15 11:27:06 -070034import android.car.user.CarUserManager.UserLifecycleEventType;
Antonio Kantekc8114752020-03-05 21:37:39 -080035import android.car.user.CarUserManager.UserLifecycleListener;
felipeal5e3ede42020-04-23 18:04:07 -070036import android.car.user.GetUserIdentificationAssociationResponse;
felipeale5bf0322020-04-16 15:10:57 -070037import android.car.user.UserSwitchResult;
Eric Jeong3a793b02019-09-30 16:12:53 -070038import android.car.userlib.CarUserManagerHelper;
felipeal19e3d732020-03-18 12:07:32 -070039import android.car.userlib.HalCallback;
40import android.car.userlib.UserHalHelper;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070041import android.content.Context;
Eric Jeong1545f3b2019-09-16 13:56:52 -070042import android.content.pm.UserInfo;
Felipe Leme315a53b2020-03-12 10:51:04 -070043import android.content.res.Resources;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070044import android.graphics.Bitmap;
Felipe Lemee3cab982020-03-12 11:39:29 -070045import android.hardware.automotive.vehicle.V2_0.InitialUserInfoResponse;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080046import android.hardware.automotive.vehicle.V2_0.InitialUserInfoResponseAction;
Mayank Garg59f22192020-03-27 00:51:45 -070047import android.hardware.automotive.vehicle.V2_0.SwitchUserStatus;
felipeal5e3ede42020-04-23 18:04:07 -070048import android.hardware.automotive.vehicle.V2_0.UserIdentificationGetRequest;
49import android.hardware.automotive.vehicle.V2_0.UserIdentificationResponse;
Felipe Lemec6e3c2a2020-02-19 16:53:57 -080050import android.hardware.automotive.vehicle.V2_0.UsersInfo;
Ying Zheng1ab32b62018-06-26 12:47:26 -070051import android.location.LocationManager;
Eric Jeong1545f3b2019-09-16 13:56:52 -070052import android.os.Binder;
Felipe Leme5528ff72020-02-10 19:05:14 -080053import android.os.Bundle;
Antonio Kantek7236a5b2020-04-06 19:53:55 -070054import android.os.Handler;
55import android.os.HandlerThread;
Keun young Parkfb656372019-03-12 18:37:55 -070056import android.os.RemoteException;
Mayank Garg31e73042020-01-23 00:10:38 -080057import android.os.Trace;
Ying Zhengcf20f442018-06-22 16:54:51 -070058import android.os.UserHandle;
Ying Zheng8f90edb2018-06-13 12:42:31 -070059import android.os.UserManager;
jovanak24470652018-09-11 17:51:57 -070060import android.provider.Settings;
Felipe Lemee3cab982020-03-12 11:39:29 -070061import android.sysprop.CarProperties;
felipeal312416a2020-04-14 12:28:24 -070062import android.util.EventLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070063import android.util.Log;
Felipe Leme5528ff72020-02-10 19:05:14 -080064import android.util.SparseArray;
Mayank Garg31e73042020-01-23 00:10:38 -080065import android.util.TimingsTraceLog;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070066
67import com.android.car.CarServiceBase;
Keun young Parkb241d022020-04-20 20:31:34 -070068import com.android.car.CarServiceUtils;
Eric Jeongc91f9452019-08-30 15:04:21 -070069import com.android.car.R;
Felipe Leme58412202020-01-09 13:45:33 -080070import com.android.car.hal.UserHalService;
Keun-young Parkd462a912019-02-11 08:53:42 -080071import com.android.internal.annotations.GuardedBy;
Keun young Parkf3523cd2019-04-08 10:09:17 -070072import com.android.internal.annotations.VisibleForTesting;
felipeal312416a2020-04-14 12:28:24 -070073import com.android.internal.car.EventLogTags;
felipeale5bf0322020-04-16 15:10:57 -070074import com.android.internal.infra.AndroidFuture;
Felipe Leme5528ff72020-02-10 19:05:14 -080075import com.android.internal.os.IResultReceiver;
felipeal5e3ede42020-04-23 18:04:07 -070076import com.android.internal.util.ArrayUtils;
felipeal2a84d512020-04-06 18:52:15 -070077import com.android.internal.util.FunctionalUtils;
Mayank Garge19c2922020-03-30 18:05:53 -070078import com.android.internal.util.Preconditions;
Anthony Hugh6fed1e92019-10-22 16:22:03 -070079import com.android.internal.util.UserIcons;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070080
81import java.io.PrintWriter;
Keun-young Parkd462a912019-02-11 08:53:42 -080082import java.util.ArrayList;
felipeal2d0483c2019-11-02 14:07:22 -070083import java.util.Arrays;
Eric Jeong1545f3b2019-09-16 13:56:52 -070084import java.util.Iterator;
85import java.util.List;
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +000086import java.util.Objects;
Pavel Maltsev17e81832019-04-04 14:38:41 -070087import java.util.concurrent.CopyOnWriteArrayList;
Antonio Kantek7236a5b2020-04-06 19:53:55 -070088import java.util.concurrent.CountDownLatch;
89import java.util.concurrent.TimeUnit;
Ying Zhengd3cb98e2018-05-11 11:42:48 -070090
91/**
92 * User service for cars. Manages users at boot time. Including:
93 *
94 * <ol>
Eric Jeong1545f3b2019-09-16 13:56:52 -070095 * <li> Creates a user used as driver.
96 * <li> Creates a user used as passenger.
Ying Zhengd3cb98e2018-05-11 11:42:48 -070097 * <li> Creates a secondary admin user on first run.
Eric Jeong1545f3b2019-09-16 13:56:52 -070098 * <li> Switch drivers.
Ying Zhengd3cb98e2018-05-11 11:42:48 -070099 * <ol/>
100 */
Eric Jeong1545f3b2019-09-16 13:56:52 -0700101public final class CarUserService extends ICarUserService.Stub implements CarServiceBase {
Felipe Leme5528ff72020-02-10 19:05:14 -0800102
felipealf7368962020-04-16 12:55:19 -0700103 private static final String TAG = TAG_USER;
104
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800105 /** {@code int} extra used to represent a user id in a {@link IResultReceiver} response. */
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800106 public static final String BUNDLE_USER_ID = "user.id";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800107 /** {@code int} extra used to represent user flags in a {@link IResultReceiver} response. */
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800108 public static final String BUNDLE_USER_FLAGS = "user.flags";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800109 /** {@code String} extra used to represent a user name in a {@link IResultReceiver} response. */
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800110 public static final String BUNDLE_USER_NAME = "user.name";
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800111 /** {@code int} extra used to represent the info action {@link IResultReceiver} response. */
112 public static final String BUNDLE_INITIAL_INFO_ACTION = "initial_info.action";
Felipe Leme5528ff72020-02-10 19:05:14 -0800113
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700114 private final Context mContext;
Eric Jeong3a793b02019-09-30 16:12:53 -0700115 private final CarUserManagerHelper mCarUserManagerHelper;
Keun young Parkfb656372019-03-12 18:37:55 -0700116 private final IActivityManager mAm;
Anthony Hugh9932a252019-06-12 16:19:56 -0700117 private final UserManager mUserManager;
118 private final int mMaxRunningUsers;
Eric Jeongc91f9452019-08-30 15:04:21 -0700119 private final boolean mEnablePassengerSupport;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700120
Eric Jeongc91f9452019-08-30 15:04:21 -0700121 private final Object mLockUser = new Object();
122 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800123 private boolean mUser0Unlocked;
Eric Jeongc91f9452019-08-30 15:04:21 -0700124 @GuardedBy("mLockUser")
Keun-young Parkd462a912019-02-11 08:53:42 -0800125 private final ArrayList<Runnable> mUser0UnlockTasks = new ArrayList<>();
Eric Jeongc91f9452019-08-30 15:04:21 -0700126 // Only one passenger is supported.
127 @GuardedBy("mLockUser")
128 private @UserIdInt int mLastPassengerId;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700129 /**
130 * Background users that will be restarted in garage mode. This list can include the
Mayank Garg31e73042020-01-23 00:10:38 -0800131 * current foreground user but the current foreground user should not be restarted.
Keun young Parkf3523cd2019-04-08 10:09:17 -0700132 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700133 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700134 private final ArrayList<Integer> mBackgroundUsersToRestart = new ArrayList<>();
135 /**
136 * Keep the list of background users started here. This is wholly for debugging purpose.
137 */
Eric Jeongc91f9452019-08-30 15:04:21 -0700138 @GuardedBy("mLockUser")
Keun young Parkf3523cd2019-04-08 10:09:17 -0700139 private final ArrayList<Integer> mBackgroundUsersRestartedHere = new ArrayList<>();
140
Felipe Leme58412202020-01-09 13:45:33 -0800141 private final UserHalService mHal;
142
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700143 // HandlerThread and Handler used when notifying app listeners (mAppLifecycleListeners).
Keun young Parkb241d022020-04-20 20:31:34 -0700144 private final HandlerThread mHandlerThread = CarServiceUtils.getHandlerThread(
145 getClass().getSimpleName());
146 private final Handler mHandler = new Handler(mHandlerThread.getLooper());
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700147
Felipe Leme5528ff72020-02-10 19:05:14 -0800148 /**
Antonio Kantekc8114752020-03-05 21:37:39 -0800149 * List of listeners to be notified on new user activities events.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700150 * This collection should be accessed and manipulated by mHandlerThread only.
Antonio Kantekc8114752020-03-05 21:37:39 -0800151 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700152 private final List<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>();
Antonio Kantekc8114752020-03-05 21:37:39 -0800153
154 /**
Felipe Leme5528ff72020-02-10 19:05:14 -0800155 * List of lifecycle listeners by uid.
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700156 * This collection should be accessed and manipulated by mHandlerThread only.
Felipe Leme5528ff72020-02-10 19:05:14 -0800157 */
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700158 private final SparseArray<IResultReceiver> mAppLifecycleListeners = new SparseArray<>();
Felipe Leme5528ff72020-02-10 19:05:14 -0800159
Mayank Garg7a114c82020-04-08 21:25:06 -0700160 /**
161 * User Id for the user switch in process, if any.
162 */
163 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700164 private int mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg7a114c82020-04-08 21:25:06 -0700165 /**
166 * Request Id for the user switch in process, if any.
167 */
168 @GuardedBy("mLockUser")
felipealf7368962020-04-16 12:55:19 -0700169 private int mRequestIdForUserSwitchInProcess;
Felipe Lemee3cab982020-03-12 11:39:29 -0700170 private final int mHalTimeoutMs = CarProperties.user_hal_timeout().orElse(5_000);
171
Eric Jeongc91f9452019-08-30 15:04:21 -0700172 private final CopyOnWriteArrayList<PassengerCallback> mPassengerCallbacks =
173 new CopyOnWriteArrayList<>();
174
felipeal61ce3732020-04-03 11:01:00 -0700175 @Nullable
176 @GuardedBy("mLockUser")
177 private UserInfo mInitialUser;
178
Mayank Garg71661ea2020-04-29 01:25:03 -0700179 private UserMetrics mUserMetrics;
felipeale8c5dce2020-04-15 11:27:06 -0700180
Eric Jeongc91f9452019-08-30 15:04:21 -0700181 /** Interface for callbaks related to passenger activities. */
182 public interface PassengerCallback {
183 /** Called when passenger is started at a certain zone. */
184 void onPassengerStarted(@UserIdInt int passengerId, int zoneId);
185 /** Called when passenger is stopped. */
186 void onPassengerStopped(@UserIdInt int passengerId);
187 }
188
189 /** Interface for delegating zone-related implementation to CarOccupantZoneService. */
190 public interface ZoneUserBindingHelper {
191 /** Gets occupant zones corresponding to the occupant type. */
192 @NonNull
193 List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType);
194 /** Assigns the user to the occupant zone. */
195 boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId);
196 /** Makes the occupant zone unoccupied. */
197 boolean unassignUserFromOccupantZone(@UserIdInt int userId);
198 /** Returns whether there is a passenger display. */
199 boolean isPassengerDisplayAvailable();
200 }
201
202 private final Object mLockHelper = new Object();
203 @GuardedBy("mLockHelper")
204 private ZoneUserBindingHelper mZoneUserBindingHelper;
205
Felipe Leme58412202020-01-09 13:45:33 -0800206 public CarUserService(@NonNull Context context, @NonNull UserHalService hal,
Mayank Garg71661ea2020-04-29 01:25:03 -0700207 @NonNull CarUserManagerHelper carUserManagerHelper, @NonNull UserManager userManager,
208 @NonNull IActivityManager am, int maxRunningUsers) {
209 this(context, hal, carUserManagerHelper, userManager, am, maxRunningUsers,
210 new UserMetrics());
211 }
212
213 @VisibleForTesting
214 CarUserService(@NonNull Context context, @NonNull UserHalService hal,
215 @NonNull CarUserManagerHelper carUserManagerHelper, @NonNull UserManager userManager,
216 @NonNull IActivityManager am, int maxRunningUsers, UserMetrics userMetrics) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700217 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
218 Log.d(TAG_USER, "constructed");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700219 }
220 mContext = context;
Felipe Leme58412202020-01-09 13:45:33 -0800221 mHal = hal;
Eric Jeong3a793b02019-09-30 16:12:53 -0700222 mCarUserManagerHelper = carUserManagerHelper;
Keun young Parkf3523cd2019-04-08 10:09:17 -0700223 mAm = am;
224 mMaxRunningUsers = maxRunningUsers;
Anthony Hugh9932a252019-06-12 16:19:56 -0700225 mUserManager = userManager;
Eric Jeongc91f9452019-08-30 15:04:21 -0700226 mLastPassengerId = UserHandle.USER_NULL;
227 mEnablePassengerSupport = context.getResources().getBoolean(R.bool.enablePassengerSupport);
Mayank Garg71661ea2020-04-29 01:25:03 -0700228 mUserMetrics = userMetrics;
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700229 }
230
231 @Override
232 public void init() {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700233 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
234 Log.d(TAG_USER, "init");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700235 }
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700236 }
237
238 @Override
239 public void release() {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700240 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
241 Log.d(TAG_USER, "release");
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700242 }
Ying Zhengd3cb98e2018-05-11 11:42:48 -0700243 }
244
245 @Override
Eric Jeong1545f3b2019-09-16 13:56:52 -0700246 public void dump(@NonNull PrintWriter writer) {
felipeal2d0483c2019-11-02 14:07:22 -0700247 checkAtLeastOnePermission("dump()", android.Manifest.permission.DUMP);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700248 writer.println("*CarUserService*");
Felipe Leme5528ff72020-02-10 19:05:14 -0800249 String indent = " ";
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700250 handleDumpListeners(writer, indent);
Eric Jeongc91f9452019-08-30 15:04:21 -0700251 synchronized (mLockUser) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700252 writer.println("User0Unlocked: " + mUser0Unlocked);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700253 writer.println("BackgroundUsersToRestart: " + mBackgroundUsersToRestart);
254 writer.println("BackgroundUsersRestarted: " + mBackgroundUsersRestartedHere);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700255 }
256 writer.println("MaxRunningUsers: " + mMaxRunningUsers);
257 List<UserInfo> allDrivers = getAllDrivers();
258 int driversSize = allDrivers.size();
259 writer.println("NumberOfDrivers: " + driversSize);
260 for (int i = 0; i < driversSize; i++) {
261 int driverId = allDrivers.get(i).id;
262 writer.print(indent + "#" + i + ": id=" + driverId);
263 List<UserInfo> passengers = getPassengers(driverId);
264 int passengersSize = passengers.size();
265 writer.print(" NumberPassengers: " + passengersSize);
266 if (passengersSize > 0) {
267 writer.print(" [");
268 for (int j = 0; j < passengersSize; j++) {
269 writer.print(passengers.get(j).id);
270 if (j < passengersSize - 1) {
271 writer.print(" ");
felipeal2d0483c2019-11-02 14:07:22 -0700272 }
felipeal2d0483c2019-11-02 14:07:22 -0700273 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700274 writer.print("]");
felipeal2d0483c2019-11-02 14:07:22 -0700275 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700276 writer.println();
277 }
278 writer.printf("EnablePassengerSupport: %s\n", mEnablePassengerSupport);
279 writer.printf("User HAL timeout: %dms\n", mHalTimeoutMs);
280 writer.printf("Initial user: %s\n", mInitialUser);
281 writer.println("Relevant overlayable properties");
282 Resources res = mContext.getResources();
283 writer.printf("%sowner_name=%s\n", indent,
284 res.getString(com.android.internal.R.string.owner_name));
285 writer.printf("%sdefault_guest_name=%s\n", indent,
286 res.getString(R.string.default_guest_name));
felipealf7368962020-04-16 12:55:19 -0700287 writer.printf("User switch in process=%d\n", mUserIdForUserSwitchInProcess);
Mayank Garg7a114c82020-04-08 21:25:06 -0700288 writer.printf("Request Id for the user switch in process=%d\n ",
289 mRequestIdForUserSwitchInProcess);
felipeale8c5dce2020-04-15 11:27:06 -0700290
291 dumpUserMetrics(writer);
292 }
293
294 /**
295 * Dumps user metrics.
296 */
297 public void dumpUserMetrics(@NonNull PrintWriter writer) {
298 mUserMetrics.dump(writer);
299 }
300
301 /**
302 * Dumps first user unlocking time.
303 */
304 public void dumpFirstUserUnlockDuration(PrintWriter writer) {
305 mUserMetrics.dumpFirstUserUnlockDuration(writer);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700306 }
307
308 private void handleDumpListeners(@NonNull PrintWriter writer, String indent) {
309 CountDownLatch latch = new CountDownLatch(1);
310 mHandler.post(() -> {
311 handleDumpUserLifecycleListeners(writer);
312 handleDumpAppLifecycleListeners(writer, indent);
313 latch.countDown();
314 });
315 int timeout = 5;
316 try {
317 if (!latch.await(timeout, TimeUnit.SECONDS)) {
318 writer.printf("Handler thread didn't respond in %ds when dumping listeners\n",
319 timeout);
320 }
321 } catch (InterruptedException e) {
322 Thread.currentThread().interrupt();
323 writer.println("Interrupted waiting for handler thread to dump app and user listeners");
324 }
325 }
326
327 private void handleDumpUserLifecycleListeners(@NonNull PrintWriter writer) {
328 if (mUserLifecycleListeners.isEmpty()) {
329 writer.println("No user lifecycle listeners");
330 return;
331 }
332 writer.printf("%d user lifecycle listeners\n", mUserLifecycleListeners.size());
333 for (UserLifecycleListener listener : mUserLifecycleListeners) {
334 writer.printf("Listener %s\n", listener);
335 }
336 }
337
338 private void handleDumpAppLifecycleListeners(@NonNull PrintWriter writer, String indent) {
339 int numberListeners = mAppLifecycleListeners.size();
340 if (numberListeners == 0) {
341 writer.println("No lifecycle listeners");
342 return;
343 }
344 writer.printf("%d lifecycle listeners\n", numberListeners);
345 for (int i = 0; i < numberListeners; i++) {
346 int uid = mAppLifecycleListeners.keyAt(i);
347 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
348 writer.printf("%suid: %d Listener %s\n", indent, uid, listener);
Keun-young Parkd462a912019-02-11 08:53:42 -0800349 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700350 }
351
352 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800353 * Creates a driver who is a regular user and is allowed to login to the driving occupant zone.
354 *
355 * @param name The name of the driver to be created.
356 * @param admin Whether the created driver will be an admin.
357 * @return {@link UserInfo} object of the created driver, or {@code null} if the driver could
358 * not be created.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700359 */
360 @Override
361 @Nullable
362 public UserInfo createDriver(@NonNull String name, boolean admin) {
363 checkManageUsersPermission("createDriver");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000364 Objects.requireNonNull(name, "name cannot be null");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700365 if (admin) {
366 return createNewAdminUser(name);
367 }
Eric Jeong3a793b02019-09-30 16:12:53 -0700368 return mCarUserManagerHelper.createNewNonAdminUser(name);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700369 }
370
371 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800372 * Creates a passenger who is a profile of the given driver.
373 *
374 * @param name The name of the passenger to be created.
375 * @param driverId User id of the driver under whom a passenger is created.
376 * @return {@link UserInfo} object of the created passenger, or {@code null} if the passenger
377 * could not be created.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700378 */
379 @Override
380 @Nullable
381 public UserInfo createPassenger(@NonNull String name, @UserIdInt int driverId) {
382 checkManageUsersPermission("createPassenger");
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +0000383 Objects.requireNonNull(name, "name cannot be null");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700384 UserInfo driver = mUserManager.getUserInfo(driverId);
385 if (driver == null) {
386 Log.w(TAG_USER, "the driver is invalid");
387 return null;
388 }
389 if (driver.isGuest()) {
390 Log.w(TAG_USER, "a guest driver cannot create a passenger");
391 return null;
392 }
Bookatz42fb1a62019-10-30 11:45:01 -0700393 UserInfo user = mUserManager.createProfileForUser(name,
394 UserManager.USER_TYPE_PROFILE_MANAGED, /* flags */ 0, driverId);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700395 if (user == null) {
396 // Couldn't create user, most likely because there are too many.
397 Log.w(TAG_USER, "can't create a profile for user" + driverId);
398 return null;
399 }
400 // Passenger user should be a non-admin user.
Eric Jeong3a793b02019-09-30 16:12:53 -0700401 mCarUserManagerHelper.setDefaultNonAdminRestrictions(user, /* enable= */ true);
Anthony Hugh6fed1e92019-10-22 16:22:03 -0700402 assignDefaultIcon(user);
Eric Jeong1545f3b2019-09-16 13:56:52 -0700403 return user;
404 }
405
406 /**
407 * @see CarUserManager.switchDriver
408 */
409 @Override
410 public boolean switchDriver(@UserIdInt int driverId) {
411 checkManageUsersPermission("switchDriver");
412 if (driverId == UserHandle.USER_SYSTEM && UserManager.isHeadlessSystemUserMode()) {
413 // System user doesn't associate with real person, can not be switched to.
414 Log.w(TAG_USER, "switching to system user in headless system user mode is not allowed");
415 return false;
416 }
417 int userSwitchable = mUserManager.getUserSwitchability();
418 if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) {
419 Log.w(TAG_USER, "current process is not allowed to switch user");
420 return false;
421 }
Anthony Hughfbb67762019-10-15 12:54:54 -0700422 if (driverId == ActivityManager.getCurrentUser()) {
Eric Jeong1545f3b2019-09-16 13:56:52 -0700423 // The current user is already the given user.
424 return true;
425 }
426 try {
427 return mAm.switchUser(driverId);
428 } catch (RemoteException e) {
429 // ignore
430 Log.w(TAG_USER, "error while switching user", e);
431 }
432 return false;
433 }
434
435 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800436 * Returns all drivers who can occupy the driving zone. Guest users are included in the list.
437 *
438 * @return the list of {@link UserInfo} who can be a driver on the device.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700439 */
440 @Override
441 @NonNull
442 public List<UserInfo> getAllDrivers() {
felipeal2d0483c2019-11-02 14:07:22 -0700443 checkManageUsersOrDumpPermission("getAllDrivers");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700444 return getUsers((user) -> !isSystemUser(user.id) && user.isEnabled()
445 && !user.isManagedProfile() && !user.isEphemeral());
Eric Jeong1545f3b2019-09-16 13:56:52 -0700446 }
447
448 /**
Eric Jeonge7916fc2019-12-20 14:03:34 -0800449 * Returns all passengers under the given driver.
450 *
451 * @param driverId User id of a driver.
452 * @return the list of {@link UserInfo} who is a passenger under the given driver.
Eric Jeong1545f3b2019-09-16 13:56:52 -0700453 */
454 @Override
455 @NonNull
456 public List<UserInfo> getPassengers(@UserIdInt int driverId) {
felipeal2d0483c2019-11-02 14:07:22 -0700457 checkManageUsersOrDumpPermission("getPassengers");
Eric Jeong1545f3b2019-09-16 13:56:52 -0700458 return getUsers((user) -> {
459 return !isSystemUser(user.id) && user.isEnabled() && user.isManagedProfile()
460 && user.profileGroupId == driverId;
461 });
462 }
463
464 /**
465 * @see CarUserManager.startPassenger
466 */
467 @Override
468 public boolean startPassenger(@UserIdInt int passengerId, int zoneId) {
469 checkManageUsersPermission("startPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700470 synchronized (mLockUser) {
471 try {
472 if (!mAm.startUserInBackgroundWithListener(passengerId, null)) {
473 Log.w(TAG_USER, "could not start passenger");
474 return false;
475 }
476 } catch (RemoteException e) {
477 // ignore
478 Log.w(TAG_USER, "error while starting passenger", e);
479 return false;
480 }
481 if (!assignUserToOccupantZone(passengerId, zoneId)) {
482 Log.w(TAG_USER, "could not assign passenger to zone");
483 return false;
484 }
485 mLastPassengerId = passengerId;
486 }
487 for (PassengerCallback callback : mPassengerCallbacks) {
488 callback.onPassengerStarted(passengerId, zoneId);
489 }
490 return true;
Eric Jeong1545f3b2019-09-16 13:56:52 -0700491 }
492
493 /**
494 * @see CarUserManager.stopPassenger
495 */
496 @Override
497 public boolean stopPassenger(@UserIdInt int passengerId) {
498 checkManageUsersPermission("stopPassenger");
Eric Jeongc91f9452019-08-30 15:04:21 -0700499 return stopPassengerInternal(passengerId, true);
500 }
501
502 private boolean stopPassengerInternal(@UserIdInt int passengerId, boolean checkCurrentDriver) {
503 synchronized (mLockUser) {
504 UserInfo passenger = mUserManager.getUserInfo(passengerId);
505 if (passenger == null) {
506 Log.w(TAG_USER, "passenger " + passengerId + " doesn't exist");
507 return false;
508 }
509 if (mLastPassengerId != passengerId) {
510 Log.w(TAG_USER, "passenger " + passengerId + " hasn't been started");
511 return true;
512 }
513 if (checkCurrentDriver) {
514 int currentUser = ActivityManager.getCurrentUser();
515 if (passenger.profileGroupId != currentUser) {
516 Log.w(TAG_USER, "passenger " + passengerId
517 + " is not a profile of the current user");
518 return false;
519 }
520 }
521 // Passenger is a profile, so cannot be stopped through activity manager.
522 // Instead, activities started by the passenger are stopped and the passenger is
523 // unassigned from the zone.
524 stopAllTasks(passengerId);
525 if (!unassignUserFromOccupantZone(passengerId)) {
526 Log.w(TAG_USER, "could not unassign user from occupant zone");
527 return false;
528 }
529 mLastPassengerId = UserHandle.USER_NULL;
530 }
531 for (PassengerCallback callback : mPassengerCallbacks) {
532 callback.onPassengerStopped(passengerId);
533 }
534 return true;
535 }
536
537 private void stopAllTasks(@UserIdInt int userId) {
538 try {
539 for (StackInfo info : mAm.getAllStackInfos()) {
540 for (int i = 0; i < info.taskIds.length; i++) {
541 if (info.taskUserIds[i] == userId) {
542 int taskId = info.taskIds[i];
543 if (!mAm.removeTask(taskId)) {
544 Log.w(TAG_USER, "could not remove task " + taskId);
545 }
546 }
547 }
548 }
549 } catch (RemoteException e) {
550 Log.e(TAG_USER, "could not get stack info", e);
551 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700552 }
553
Felipe Leme5528ff72020-02-10 19:05:14 -0800554 @Override
555 public void setLifecycleListenerForUid(IResultReceiver listener) {
556 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700557 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800558 checkInteractAcrossUsersPermission("setLifecycleListenerForUid" + uid);
559
560 try {
561 listener.asBinder().linkToDeath(() -> onListenerDeath(uid), 0);
562 } catch (RemoteException e) {
563 Log.wtf(TAG_USER, "Cannot listen to death of " + uid);
564 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700565 mHandler.post(() -> mAppLifecycleListeners.append(uid, listener));
Felipe Leme5528ff72020-02-10 19:05:14 -0800566 }
567
568 private void onListenerDeath(int uid) {
569 Log.i(TAG_USER, "Removing listeners for uid " + uid + " on binder death");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700570 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800571 }
572
573 @Override
574 public void resetLifecycleListenerForUid() {
575 int uid = Binder.getCallingUid();
felipeal312416a2020-04-14 12:28:24 -0700576 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_RESET_LIFECYCLE_LISTENER, uid);
Felipe Leme5528ff72020-02-10 19:05:14 -0800577 checkInteractAcrossUsersPermission("resetLifecycleListenerForUid-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700578 mHandler.post(() -> mAppLifecycleListeners.remove(uid));
Felipe Leme5528ff72020-02-10 19:05:14 -0800579 }
580
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800581 @Override
582 public void getInitialUserInfo(int requestType, int timeoutMs,
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800583 @NonNull IResultReceiver receiver) {
felipeal312416a2020-04-14 12:28:24 -0700584 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ, requestType,
585 timeoutMs);
Felipe Lemee2600fc2020-02-26 11:06:04 -0800586 Objects.requireNonNull(receiver, "receiver cannot be null");
felipeal0ec1ff02020-03-27 17:18:28 -0700587 checkManageUsersPermission("getInitialInfo");
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800588 UsersInfo usersInfo = getUsersInfo();
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800589 mHal.getInitialUserInfo(requestType, timeoutMs, usersInfo, (status, resp) -> {
Mayank Garg0e239142020-04-14 19:16:31 -0700590 Bundle resultData = null;
591 if (resp != null) {
felipeal312416a2020-04-14 12:28:24 -0700592 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP,
593 status, resp.action, resp.userToSwitchOrCreate.userId,
594 resp.userToSwitchOrCreate.flags, resp.userNameToCreate);
Mayank Garg0e239142020-04-14 19:16:31 -0700595 switch (resp.action) {
596 case InitialUserInfoResponseAction.SWITCH:
597 resultData = new Bundle();
598 resultData.putInt(BUNDLE_INITIAL_INFO_ACTION, resp.action);
599 resultData.putInt(BUNDLE_USER_ID, resp.userToSwitchOrCreate.userId);
600 break;
601 case InitialUserInfoResponseAction.CREATE:
602 resultData = new Bundle();
603 resultData.putInt(BUNDLE_INITIAL_INFO_ACTION, resp.action);
604 resultData.putInt(BUNDLE_USER_FLAGS, resp.userToSwitchOrCreate.flags);
605 resultData.putString(BUNDLE_USER_NAME, resp.userNameToCreate);
606 break;
607 case InitialUserInfoResponseAction.DEFAULT:
608 resultData = new Bundle();
609 resultData.putInt(BUNDLE_INITIAL_INFO_ACTION, resp.action);
610 break;
611 default:
612 // That's ok, it will be the same as DEFAULT...
613 Log.w(TAG_USER, "invalid response action on " + resp);
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800614 }
felipeal312416a2020-04-14 12:28:24 -0700615 } else {
616 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_RESP, status);
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800617 }
Mayank Garg0e239142020-04-14 19:16:31 -0700618 sendResult(receiver, status, resultData);
Felipe Lemec6e3c2a2020-02-19 16:53:57 -0800619 });
620 }
621
Felipe Lemee3cab982020-03-12 11:39:29 -0700622 /**
felipeal61ce3732020-04-03 11:01:00 -0700623 * Gets the initial foreground user after the device boots or resumes from suspension.
624 *
625 * <p>When the OEM supports the User HAL, the initial user won't be available until the HAL
626 * returns the initial value to {@code CarService} - if HAL takes too long or times out, this
627 * method returns {@code null}.
628 *
629 * <p>If the HAL eventually times out, {@code CarService} will fallback to its default behavior
630 * (like switching to the last active user), and this method will return the result of such
631 * operation.
632 *
633 * <p>Notice that if {@code CarService} crashes, subsequent calls to this method will return
634 * {@code null}.
635 *
636 * @hide
637 */
638 @Nullable
639 public UserInfo getInitialUser() {
640 checkInteractAcrossUsersPermission("getInitialUser");
641 synchronized (mLockUser) {
642 return mInitialUser;
643 }
644 }
645
646 // TODO(b/150413515): temporary method called by ICarImpl.setInitialUser(int userId), as for
647 // some reason passing the whole UserInfo through a raw binder transaction is not working.
648 /**
649 * Sets the initial foreground user after the device boots or resumes from suspension.
650 */
651 public void setInitialUser(@UserIdInt int userId) {
652 UserInfo initialUser = userId == UserHandle.USER_NULL ? null
653 : mUserManager.getUserInfo(userId);
654 setInitialUser(initialUser);
655 }
656
657 /**
658 * Sets the initial foreground user after the device boots or resumes from suspension.
659 */
660 public void setInitialUser(@Nullable UserInfo user) {
felipeal312416a2020-04-14 12:28:24 -0700661 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SET_INITIAL_USER,
662 user == null ? UserHandle.USER_NULL : user.id);
felipeal61ce3732020-04-03 11:01:00 -0700663 synchronized (mLockUser) {
664 mInitialUser = user;
665 }
666 if (user == null) {
667 // This mean InitialUserSetter failed and could not fallback, so the initial user was
668 // not switched (and most likely is SYSTEM_USER).
669 // TODO(b/153104378): should we set it to ActivityManager.getCurrentUser() instead?
670 Log.wtf(TAG_USER, "Initial user set to null");
671 }
672 }
673
674 /**
Felipe Lemee3cab982020-03-12 11:39:29 -0700675 * Calls the User HAL to get the initial user info.
676 *
677 * @param requestType type as defined by {@code InitialUserInfoRequestType}.
678 * @param callback callback to receive the results.
679 */
680 public void getInitialUserInfo(int requestType,
681 HalCallback<InitialUserInfoResponse> callback) {
felipeal312416a2020-04-14 12:28:24 -0700682 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_INITIAL_USER_INFO_REQ, requestType,
683 mHalTimeoutMs);
Felipe Lemee3cab982020-03-12 11:39:29 -0700684 Objects.requireNonNull(callback, "callback cannot be null");
felipeal0ec1ff02020-03-27 17:18:28 -0700685 checkManageUsersPermission("getInitialUserInfo");
Felipe Lemee3cab982020-03-12 11:39:29 -0700686 UsersInfo usersInfo = getUsersInfo();
687 mHal.getInitialUserInfo(requestType, mHalTimeoutMs, usersInfo, callback);
688 }
689
690 /**
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700691 * Calls the {@link UserHalService} and {@link IActivityManager} for user switch.
692 *
693 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700694 * When everything works well, the workflow is:
695 * <ol>
696 * <li> {@link UserHalService} is called for HAL user switch with ANDROID_SWITCH request
697 * type, current user id, target user id, and a callback.
698 * <li> HAL called back with SUCCESS.
699 * <li> {@link IActivityManager} is called for Android user switch.
700 * <li> Receiver would receive {@code STATUS_SUCCESSFUL}.
701 * <li> Once user is unlocked, {@link UserHalService} is again called with ANDROID_POST_SWITCH
702 * request type, current user id, and target user id. In this case, the current and target
703 * user IDs would be same.
704 * <ol/>
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700705 *
706 * <p>
Mayank Gargb08f6772020-05-01 18:06:48 -0700707 * Corner cases:
708 * <ul>
709 * <li> If target user is already the current user, no user switch is performed and receiver
710 * would receive {@code STATUS_ALREADY_REQUESTED_USER} right away.
711 * <li> If HAL user switch call fails, no Android user switch. Receiver would receive
712 * {@code STATUS_HAL_INTERNAL_FAILURE}.
713 * <li> If HAL user switch call is successful, but android user switch call fails,
714 * {@link UserHalService} is again called with request type POST_SWITCH, current user id, and
715 * target user id, but in this case the current and target user IDs would be different.
716 * <li> If another user switch request for the same target user is received while previous
717 * request is in process, receiver would receive
718 * {@code STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO} for the new request right away.
719 * <li> If a user switch request is received while another user switch request for different
720 * target user is in process, the previous request would be abandoned and new request will be
721 * processed. No POST_SWITCH would be sent for the previous request.
722 * <ul/>
Mayank Garg59f22192020-03-27 00:51:45 -0700723 *
Mayank Garge19c2922020-03-30 18:05:53 -0700724 * @param targetUserId - target user Id
Mayank Garg59f22192020-03-27 00:51:45 -0700725 * @param timeoutMs - timeout for HAL to wait
726 * @param receiver - receiver for the results
727 */
Mayank Garge19c2922020-03-30 18:05:53 -0700728 @Override
729 public void switchUser(@UserIdInt int targetUserId, int timeoutMs,
felipeale5bf0322020-04-16 15:10:57 -0700730 @NonNull AndroidFuture<UserSwitchResult> receiver) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700731 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_REQ, targetUserId, timeoutMs);
Mayank Garg59f22192020-03-27 00:51:45 -0700732 checkManageUsersPermission("switchUser");
Mayank Garge19c2922020-03-30 18:05:53 -0700733 Objects.requireNonNull(receiver);
734 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
felipealf7368962020-04-16 12:55:19 -0700735 Preconditions.checkArgument(targetUser != null, "Target user doesn't exist");
Mayank Garg7a114c82020-04-08 21:25:06 -0700736
felipealf7368962020-04-16 12:55:19 -0700737 int currentUser = ActivityManager.getCurrentUser();
738 if (currentUser == targetUserId) {
Mayank Garg0e239142020-04-14 19:16:31 -0700739 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
740 Log.d(TAG_USER, "Current user is same as requested target user: " + targetUserId);
741 }
felipeale5bf0322020-04-16 15:10:57 -0700742 int resultStatus = UserSwitchResult.STATUS_ALREADY_REQUESTED_USER;
743 sendResult(receiver, resultStatus);
Mayank Garg0e239142020-04-14 19:16:31 -0700744 return;
745 }
746
Mayank Garg7a114c82020-04-08 21:25:06 -0700747 synchronized (mLockUser) {
felipealf7368962020-04-16 12:55:19 -0700748 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
749 Log.d(TAG_USER, "switchUser(" + targetUserId + "): currentuser=" + currentUser
750 + ", mUserIdForUserSwitchInProcess=" + mUserIdForUserSwitchInProcess);
751 }
752
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700753 // If there is another request for the same target user, return another request in
754 // process, else {@link mUserIdForUserSwitchInProcess} is updated and {@link
755 // mRequestIdForUserSwitchInProcess} is reset. It is possible that there may be another
756 // user switch request in process for different target user, but that request is now
757 // ignored.
felipealf7368962020-04-16 12:55:19 -0700758 if (mUserIdForUserSwitchInProcess == targetUserId) {
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700759 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
760 Log.d(TAG_USER,
761 "Another user switch request in process for the requested target user: "
762 + targetUserId);
763 }
764
765 int resultStatus = UserSwitchResult.STATUS_TARGET_USER_ALREADY_BEING_SWITCHED_TO;
felipeale5bf0322020-04-16 15:10:57 -0700766 sendResult(receiver, resultStatus);
Mayank Garg7a114c82020-04-08 21:25:06 -0700767 return;
768 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700769 else {
770 mUserIdForUserSwitchInProcess = targetUserId;
771 mRequestIdForUserSwitchInProcess = 0;
772 }
Mayank Garg7a114c82020-04-08 21:25:06 -0700773 }
774
Mayank Garg59f22192020-03-27 00:51:45 -0700775 UsersInfo usersInfo = getUsersInfo();
Mayank Garg7a114c82020-04-08 21:25:06 -0700776 android.hardware.automotive.vehicle.V2_0.UserInfo halTargetUser =
Mayank Garg59f22192020-03-27 00:51:45 -0700777 new android.hardware.automotive.vehicle.V2_0.UserInfo();
Mayank Garg7a114c82020-04-08 21:25:06 -0700778 halTargetUser.userId = targetUser.id;
779 halTargetUser.flags = UserHalHelper.convertFlags(targetUser);
780 mHal.switchUser(halTargetUser, timeoutMs, usersInfo, (status, resp) -> {
felipealf7368962020-04-16 12:55:19 -0700781 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
782 Log.d(TAG, "switch response: status="
783 + UserHalHelper.halCallbackStatusToString(status) + ", resp=" + resp);
784 }
785
felipeale5bf0322020-04-16 15:10:57 -0700786 int resultStatus = UserSwitchResult.STATUS_HAL_INTERNAL_FAILURE;
felipealf7368962020-04-16 12:55:19 -0700787
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700788 synchronized (mLockUser) {
789 if (status != HalCallback.STATUS_OK) {
790 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, status);
791 Log.w(TAG, "invalid callback status ("
792 + UserHalHelper.halCallbackStatusToString(status) + ") for response "
793 + resp);
794 sendResult(receiver, resultStatus);
795 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
796 return;
797 }
felipealf7368962020-04-16 12:55:19 -0700798
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700799 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_SWITCH_USER_RESP, status, resp.status,
800 resp.errorMessage);
801
802 if (mUserIdForUserSwitchInProcess != targetUserId) {
803 // Another user switch request received while HAL responded. No need to process
804 // this request further
805 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
806 Log.d(TAG_USER, "Another user switch received while HAL responsed. Request "
807 + "abondoned for : " + targetUserId + ". Current user in process: "
808 + mUserIdForUserSwitchInProcess);
felipealf7368962020-04-16 12:55:19 -0700809 }
Mayank Garg1f20dcd2020-04-22 17:46:01 -0700810 resultStatus =
811 UserSwitchResult.STATUS_TARGET_USER_ABANDONED_DUE_TO_A_NEW_REQUEST;
812 sendResult(receiver, resultStatus);
813 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
814 return;
815 }
816
817 switch (resp.status) {
818 case SwitchUserStatus.SUCCESS:
819 boolean switched;
820 try {
821 switched = mAm.switchUser(targetUserId);
822 if (switched) {
823 resultStatus = UserSwitchResult.STATUS_SUCCESSFUL;
824 mRequestIdForUserSwitchInProcess = resp.requestId;
825 } else {
826 resultStatus = UserSwitchResult.STATUS_ANDROID_FAILURE;
827 postSwitchHalResponse(resp.requestId, targetUserId);
828 }
829 } catch (RemoteException e) {
830 // ignore
831 Log.w(TAG_USER,
832 "error while switching user " + targetUser.toFullString(), e);
833 }
834 break;
835 case SwitchUserStatus.FAILURE:
836 // HAL failed to switch user
837 resultStatus = UserSwitchResult.STATUS_HAL_FAILURE;
838 break;
839 }
840
841 if (mRequestIdForUserSwitchInProcess == 0) {
842 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
843 }
Mayank Garg59f22192020-03-27 00:51:45 -0700844 }
felipeale5bf0322020-04-16 15:10:57 -0700845 sendResult(receiver, resultStatus, resp.errorMessage);
Mayank Garg59f22192020-03-27 00:51:45 -0700846 });
847 }
848
felipeal5e3ede42020-04-23 18:04:07 -0700849 @Override
850 public GetUserIdentificationAssociationResponse getUserIdentificationAssociation(int[] types) {
851 Preconditions.checkArgument(!ArrayUtils.isEmpty(types), "must have at least one type");
852 checkManageUsersPermission("getUserIdentificationAssociation");
853
854 int uid = getCallingUid();
855 int userId = UserHandle.getUserId(uid);
856 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_REQ, uid, userId);
857
858 UserIdentificationGetRequest request = new UserIdentificationGetRequest();
859 request.userInfo.userId = userId;
860 request.userInfo.flags = getHalUserInfoFlags(userId);
861
862 request.numberAssociationTypes = types.length;
863 for (int i = 0; i < types.length; i++) {
864 request.associationTypes.add(types[i]);
865 }
866
867 UserIdentificationResponse halResponse = mHal.getUserAssociation(request);
868 if (halResponse == null) {
869 Log.w(TAG, "getUserIdentificationAssociation(): HAL returned null for "
870 + Arrays.toString(types));
871 return null;
872 }
873
874 int[] values = new int[halResponse.associations.size()];
875 for (int i = 0; i < values.length; i++) {
876 values[i] = halResponse.associations.get(i).value;
877 }
878 EventLog.writeEvent(EventLogTags.CAR_USER_MGR_GET_USER_AUTH_RESP, values.length);
879
880 return new GetUserIdentificationAssociationResponse(halResponse.errorMessage, values);
881 }
882
883 /**
884 * Gets the User HAL flags for the given user.
885 *
886 * @throws IllegalArgumentException if the user does not exist.
887 */
888 private int getHalUserInfoFlags(@UserIdInt int userId) {
889 UserInfo user = mUserManager.getUserInfo(userId);
890 Preconditions.checkArgument(user != null, "no user for id %d", userId);
891 return UserHalHelper.convertFlags(user);
892 }
893
Mayank Garg0e239142020-04-14 19:16:31 -0700894 private void sendResult(@NonNull IResultReceiver receiver, int resultCode,
895 @Nullable Bundle resultData) {
896 try {
897 receiver.send(resultCode, resultData);
898 } catch (RemoteException e) {
899 // ignore
900 Log.w(TAG_USER, "error while sending results", e);
901 }
902 }
903
felipeale5bf0322020-04-16 15:10:57 -0700904 private void sendResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
905 @UserSwitchResult.Status int status) {
906 sendResult(receiver, status, /* errorMessage= */ null);
907 }
908
909 private void sendResult(@NonNull AndroidFuture<UserSwitchResult> receiver,
910 @UserSwitchResult.Status int status, @Nullable String errorMessage) {
911 receiver.complete(new UserSwitchResult(status, errorMessage));
912 }
913
Mayank Garg7a114c82020-04-08 21:25:06 -0700914 private void postSwitchHalResponse(int requestId, @UserIdInt int targetUserId) {
915 UserInfo targetUser = mUserManager.getUserInfo(targetUserId);
916 UsersInfo usersInfo = getUsersInfo();
917 android.hardware.automotive.vehicle.V2_0.UserInfo halTargetUser =
918 new android.hardware.automotive.vehicle.V2_0.UserInfo();
919 halTargetUser.userId = targetUser.id;
920 halTargetUser.flags = UserHalHelper.convertFlags(targetUser);
felipeal312416a2020-04-14 12:28:24 -0700921 EventLog.writeEvent(EventLogTags.CAR_USER_SVC_POST_SWITCH_USER_REQ, requestId,
922 targetUserId, usersInfo.currentUser.userId);
Mayank Garg7a114c82020-04-08 21:25:06 -0700923 mHal.postSwitchResponse(requestId, halTargetUser, usersInfo);
924 }
925
Mayank Garg59f22192020-03-27 00:51:45 -0700926 /**
Felipe Lemee3cab982020-03-12 11:39:29 -0700927 * Checks if the User HAL is supported.
928 */
929 public boolean isUserHalSupported() {
930 return mHal.isSupported();
931 }
932
Felipe Lemeabbf2da2020-02-24 18:25:29 -0800933 // TODO(b/144120654): use helper to generate UsersInfo
934 private UsersInfo getUsersInfo() {
935 UserInfo currentUser;
936 try {
937 currentUser = mAm.getCurrentUser();
938 } catch (RemoteException e) {
939 // shouldn't happen
940 throw new IllegalStateException("Could not get current user: ", e);
941 }
942 List<UserInfo> existingUsers = mUserManager.getUsers();
943 int size = existingUsers.size();
944
945 UsersInfo usersInfo = new UsersInfo();
946 usersInfo.numberUsers = size;
947 usersInfo.currentUser.userId = currentUser.id;
948 usersInfo.currentUser.flags = UserHalHelper.convertFlags(currentUser);
949
950 for (int i = 0; i < size; i++) {
951 UserInfo androidUser = existingUsers.get(i);
952 android.hardware.automotive.vehicle.V2_0.UserInfo halUser =
953 new android.hardware.automotive.vehicle.V2_0.UserInfo();
954 halUser.userId = androidUser.id;
955 halUser.flags = UserHalHelper.convertFlags(androidUser);
956 usersInfo.existingUsers.add(halUser);
957 }
958
959 return usersInfo;
960 }
961
Eric Jeong1545f3b2019-09-16 13:56:52 -0700962 /** Returns whether the given user is a system user. */
963 private static boolean isSystemUser(@UserIdInt int userId) {
964 return userId == UserHandle.USER_SYSTEM;
965 }
966
Keun young Park13a7a822019-04-04 15:53:08 -0700967 private void updateDefaultUserRestriction() {
968 // We want to set restrictions on system and guest users only once. These are persisted
969 // onto disk, so it's sufficient to do it once + we minimize the number of disk writes.
970 if (Settings.Global.getInt(mContext.getContentResolver(),
Eric Jeong1545f3b2019-09-16 13:56:52 -0700971 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, /* default= */ 0) != 0) {
972 return;
Keun young Park13a7a822019-04-04 15:53:08 -0700973 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700974 // Only apply the system user restrictions if the system user is headless.
975 if (UserManager.isHeadlessSystemUserMode()) {
976 setSystemUserRestrictions();
977 }
Eric Jeong1545f3b2019-09-16 13:56:52 -0700978 Settings.Global.putInt(mContext.getContentResolver(),
979 CarSettings.Global.DEFAULT_USER_RESTRICTIONS_SET, 1);
Keun young Park13a7a822019-04-04 15:53:08 -0700980 }
981
Eric Jeong1545f3b2019-09-16 13:56:52 -0700982 private boolean isPersistentUser(@UserIdInt int userId) {
Anthony Hugh9932a252019-06-12 16:19:56 -0700983 return !mUserManager.getUserInfo(userId).isEphemeral();
984 }
985
Antonio Kantekc8114752020-03-05 21:37:39 -0800986 /**
Antonio Kantekc8114752020-03-05 21:37:39 -0800987 * Adds a new {@link UserLifecycleListener} to listen to user activity events.
988 */
989 public void addUserLifecycleListener(@NonNull UserLifecycleListener listener) {
990 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700991 mHandler.post(() -> mUserLifecycleListeners.add(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -0800992 }
993
994 /**
995 * Removes previously added {@link UserLifecycleListener}.
996 */
997 public void removeUserLifecycleListener(@NonNull UserLifecycleListener listener) {
998 Objects.requireNonNull(listener, "listener cannot be null");
Antonio Kantek7236a5b2020-04-06 19:53:55 -0700999 mHandler.post(() -> mUserLifecycleListeners.remove(listener));
Antonio Kantekc8114752020-03-05 21:37:39 -08001000 }
1001
Eric Jeongc91f9452019-08-30 15:04:21 -07001002 /** Adds callback to listen to passenger activity events. */
1003 public void addPassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001004 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001005 mPassengerCallbacks.add(callback);
1006 }
1007
1008 /** Removes previously added callback to listen passenger events. */
1009 public void removePassengerCallback(@NonNull PassengerCallback callback) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001010 Objects.requireNonNull(callback, "callback cannot be null");
Eric Jeongc91f9452019-08-30 15:04:21 -07001011 mPassengerCallbacks.remove(callback);
1012 }
1013
1014 /** Sets the implementation of ZoneUserBindingHelper. */
1015 public void setZoneUserBindingHelper(@NonNull ZoneUserBindingHelper helper) {
1016 synchronized (mLockHelper) {
1017 mZoneUserBindingHelper = helper;
1018 }
1019 }
1020
felipeal98900c82020-04-09 09:05:02 -07001021 private void onUserUnlocked(@UserIdInt int userId) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001022 ArrayList<Runnable> tasks = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001023 synchronized (mLockUser) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001024 sendPostSwitchToHalLocked(userId);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001025 if (userId == UserHandle.USER_SYSTEM) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001026 if (!mUser0Unlocked) { // user 0, unlocked, do this only once
1027 updateDefaultUserRestriction();
1028 tasks = new ArrayList<>(mUser0UnlockTasks);
1029 mUser0UnlockTasks.clear();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001030 mUser0Unlocked = true;
Keun young Parkf3523cd2019-04-08 10:09:17 -07001031 }
1032 } else { // none user0
Eric Jeong1545f3b2019-09-16 13:56:52 -07001033 Integer user = userId;
1034 if (isPersistentUser(userId)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001035 // current foreground user should stay in top priority.
Anthony Hughfbb67762019-10-15 12:54:54 -07001036 if (userId == ActivityManager.getCurrentUser()) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001037 mBackgroundUsersToRestart.remove(user);
1038 mBackgroundUsersToRestart.add(0, user);
1039 }
1040 // -1 for user 0
1041 if (mBackgroundUsersToRestart.size() > (mMaxRunningUsers - 1)) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001042 int userToDrop = mBackgroundUsersToRestart.get(
Keun young Parkf3523cd2019-04-08 10:09:17 -07001043 mBackgroundUsersToRestart.size() - 1);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001044 Log.i(TAG_USER, "New user unlocked:" + userId
Keun young Parkf3523cd2019-04-08 10:09:17 -07001045 + ", dropping least recently user from restart list:" + userToDrop);
1046 // Drop the least recently used user.
1047 mBackgroundUsersToRestart.remove(mBackgroundUsersToRestart.size() - 1);
1048 }
1049 }
Keun-young Parkd462a912019-02-11 08:53:42 -08001050 }
1051 }
1052 if (tasks != null && tasks.size() > 0) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001053 Log.d(TAG_USER, "User0 unlocked, run queued tasks:" + tasks.size());
Keun-young Parkd462a912019-02-11 08:53:42 -08001054 for (Runnable r : tasks) {
1055 r.run();
1056 }
1057 }
1058 }
1059
1060 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001061 * Starts all background users that were active in system.
1062 *
Keun young Parkfb656372019-03-12 18:37:55 -07001063 * @return list of background users started successfully.
1064 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001065 @NonNull
Keun young Parkfb656372019-03-12 18:37:55 -07001066 public ArrayList<Integer> startAllBackgroundUsers() {
1067 ArrayList<Integer> users;
Eric Jeongc91f9452019-08-30 15:04:21 -07001068 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001069 users = new ArrayList<>(mBackgroundUsersToRestart);
1070 mBackgroundUsersRestartedHere.clear();
1071 mBackgroundUsersRestartedHere.addAll(mBackgroundUsersToRestart);
Keun young Parkfb656372019-03-12 18:37:55 -07001072 }
1073 ArrayList<Integer> startedUsers = new ArrayList<>();
1074 for (Integer user : users) {
Anthony Hughfbb67762019-10-15 12:54:54 -07001075 if (user == ActivityManager.getCurrentUser()) {
Keun young Parkfb656372019-03-12 18:37:55 -07001076 continue;
1077 }
1078 try {
1079 if (mAm.startUserInBackground(user)) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001080 if (mUserManager.isUserUnlockingOrUnlocked(user)) {
1081 // already unlocked / unlocking. No need to unlock.
Keun young Parkfb656372019-03-12 18:37:55 -07001082 startedUsers.add(user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001083 } else if (mAm.unlockUser(user, null, null, null)) {
1084 startedUsers.add(user);
1085 } else { // started but cannot unlock
Eric Jeong1545f3b2019-09-16 13:56:52 -07001086 Log.w(TAG_USER, "Background user started but cannot be unlocked:" + user);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001087 if (mUserManager.isUserRunning(user)) {
1088 // add to started list so that it can be stopped later.
1089 startedUsers.add(user);
1090 }
Keun young Parkfb656372019-03-12 18:37:55 -07001091 }
1092 }
1093 } catch (RemoteException e) {
1094 // ignore
Eric Jeong1545f3b2019-09-16 13:56:52 -07001095 Log.w(TAG_USER, "error while starting user in background", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001096 }
1097 }
Keun young Parkf3523cd2019-04-08 10:09:17 -07001098 // Keep only users that were re-started in mBackgroundUsersRestartedHere
Eric Jeongc91f9452019-08-30 15:04:21 -07001099 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001100 ArrayList<Integer> usersToRemove = new ArrayList<>();
1101 for (Integer user : mBackgroundUsersToRestart) {
1102 if (!startedUsers.contains(user)) {
1103 usersToRemove.add(user);
1104 }
1105 }
1106 mBackgroundUsersRestartedHere.removeAll(usersToRemove);
1107 }
Keun young Parkfb656372019-03-12 18:37:55 -07001108 return startedUsers;
1109 }
1110
1111 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001112 * Stops all background users that were active in system.
1113 *
1114 * @return whether stopping succeeds.
Keun young Parkfb656372019-03-12 18:37:55 -07001115 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001116 public boolean stopBackgroundUser(@UserIdInt int userId) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001117 if (userId == UserHandle.USER_SYSTEM) {
1118 return false;
1119 }
Anthony Hughfbb67762019-10-15 12:54:54 -07001120 if (userId == ActivityManager.getCurrentUser()) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001121 Log.i(TAG_USER, "stopBackgroundUser, already a FG user:" + userId);
Keun young Parkfb656372019-03-12 18:37:55 -07001122 return false;
1123 }
1124 try {
Keun young Parked9e6282019-09-19 17:38:26 -07001125 int r = mAm.stopUserWithDelayedLocking(userId, true, null);
Keun young Parkf3523cd2019-04-08 10:09:17 -07001126 if (r == ActivityManager.USER_OP_SUCCESS) {
Eric Jeongc91f9452019-08-30 15:04:21 -07001127 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001128 Integer user = userId;
1129 mBackgroundUsersRestartedHere.remove(user);
1130 }
1131 } else if (r == ActivityManager.USER_OP_IS_CURRENT) {
1132 return false;
1133 } else {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001134 Log.i(TAG_USER, "stopBackgroundUser failed, user:" + userId + " err:" + r);
Keun young Parkfb656372019-03-12 18:37:55 -07001135 return false;
1136 }
1137 } catch (RemoteException e) {
1138 // ignore
Eric Jeong1545f3b2019-09-16 13:56:52 -07001139 Log.w(TAG_USER, "error while stopping user", e);
Keun young Parkfb656372019-03-12 18:37:55 -07001140 }
1141 return true;
1142 }
1143
1144 /**
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001145 * Notifies all registered {@link UserLifecycleListener} with the event passed as argument.
Pavel Maltsev17e81832019-04-04 14:38:41 -07001146 */
felipeale8c5dce2020-04-15 11:27:06 -07001147 public void onUserLifecycleEvent(@UserLifecycleEventType int eventType, long timestampMs,
1148 @UserIdInt int fromUserId, @UserIdInt int toUserId) {
1149 int userId = toUserId;
felipeal98900c82020-04-09 09:05:02 -07001150
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001151 // Handle special cases first...
felipeal98900c82020-04-09 09:05:02 -07001152 if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_SWITCHING) {
1153 onUserSwitching(userId);
1154 } else if (eventType == CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
1155 onUserUnlocked(userId);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001156 }
1157
felipeale8c5dce2020-04-15 11:27:06 -07001158 // ...then notify listeners.
Yan Zhue7921522020-04-16 15:59:25 -07001159 UserLifecycleEvent event = new UserLifecycleEvent(eventType, fromUserId, userId);
felipeale8c5dce2020-04-15 11:27:06 -07001160
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001161 mHandler.post(() -> {
1162 handleNotifyServiceUserLifecycleListeners(event);
1163 handleNotifyAppUserLifecycleListeners(event);
1164 });
felipeale8c5dce2020-04-15 11:27:06 -07001165
1166 // Finally, update metrics.
1167 mUserMetrics.onEvent(eventType, timestampMs, fromUserId, toUserId);
1168 }
1169
1170 /**
1171 * Sets the first user unlocking metrics.
1172 */
1173 public void onFirstUserUnlocked(@UserIdInt int userId, long timestampMs, long duration,
1174 int halResponseTime) {
1175 mUserMetrics.logFirstUnlockedUser(userId, timestampMs, duration, halResponseTime);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001176 }
1177
Mayank Garg7a114c82020-04-08 21:25:06 -07001178 private void sendPostSwitchToHalLocked(@UserIdInt int userId) {
felipealf7368962020-04-16 12:55:19 -07001179 if (mUserIdForUserSwitchInProcess == UserHandle.USER_NULL
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001180 || mUserIdForUserSwitchInProcess != userId
1181 || mRequestIdForUserSwitchInProcess == 0) {
Mayank Garg7a114c82020-04-08 21:25:06 -07001182 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1183 Log.d(TAG_USER, "No user switch request Id. No android post switch sent.");
1184 }
1185 return;
1186 }
felipealf7368962020-04-16 12:55:19 -07001187 postSwitchHalResponse(mRequestIdForUserSwitchInProcess, mUserIdForUserSwitchInProcess);
1188 mUserIdForUserSwitchInProcess = UserHandle.USER_NULL;
Mayank Garg1f20dcd2020-04-22 17:46:01 -07001189 mRequestIdForUserSwitchInProcess = 0;
Mayank Garg7a114c82020-04-08 21:25:06 -07001190 }
1191
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001192 private void handleNotifyAppUserLifecycleListeners(UserLifecycleEvent event) {
1193 int listenersSize = mAppLifecycleListeners.size();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001194 if (listenersSize == 0) {
felipeal2a84d512020-04-06 18:52:15 -07001195 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1196 Log.d(TAG_USER, "No app listener to be notified of " + event);
1197 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001198 return;
1199 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001200 // Must use a different TimingsTraceLog because it's another thread
1201 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1202 Log.d(TAG_USER, "Notifying " + listenersSize + " app listeners of " + event);
1203 }
felipeal2a84d512020-04-06 18:52:15 -07001204 int userId = event.getUserId();
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001205 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
1206 t.traceBegin("notify-app-listeners-user-" + userId + "-event-" + event.getEventType());
1207 for (int i = 0; i < listenersSize; i++) {
1208 int uid = mAppLifecycleListeners.keyAt(i);
1209 IResultReceiver listener = mAppLifecycleListeners.valueAt(i);
1210 Bundle data = new Bundle();
1211 data.putInt(CarUserManager.BUNDLE_PARAM_ACTION, event.getEventType());
Yan Zhue7921522020-04-16 15:59:25 -07001212
1213 int fromUid = event.getPreviousUserId();
1214 if (fromUid != UserHandle.USER_NULL) {
1215 data.putInt(CarUserManager.BUNDLE_PARAM_PREVIOUS_USER_ID, fromUid);
1216 }
1217
felipeal2a84d512020-04-06 18:52:15 -07001218 if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001219 Log.d(TAG_USER, "Notifying listener for uid " + uid);
felipeal2a84d512020-04-06 18:52:15 -07001220 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001221 try {
felipeal2a84d512020-04-06 18:52:15 -07001222 t.traceBegin("notify-app-listener-" + uid);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001223 listener.send(userId, data);
1224 } catch (RemoteException e) {
1225 Log.e(TAG_USER, "Error calling lifecycle listener", e);
1226 } finally {
1227 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001228 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001229 }
1230 t.traceEnd(); // notify-app-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001231 }
1232
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001233 private void handleNotifyServiceUserLifecycleListeners(UserLifecycleEvent event) {
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001234 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
1235 if (mUserLifecycleListeners.isEmpty()) {
felipeal2a84d512020-04-06 18:52:15 -07001236 Log.w(TAG_USER, "Not notifying internal UserLifecycleListeners");
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001237 return;
felipeal2a84d512020-04-06 18:52:15 -07001238 } else if (Log.isLoggable(TAG_USER, Log.DEBUG)) {
1239 Log.d(TAG_USER, "Notifying " + mUserLifecycleListeners.size() + " service listeners of "
1240 + event);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001241 }
felipeal2a84d512020-04-06 18:52:15 -07001242
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001243 t.traceBegin("notify-listeners-user-" + event.getUserId() + "-event-"
1244 + event.getEventType());
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001245 for (UserLifecycleListener listener : mUserLifecycleListeners) {
felipeal2a84d512020-04-06 18:52:15 -07001246 String listenerName = FunctionalUtils.getLambdaName(listener);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001247 try {
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001248 t.traceBegin("notify-listener-" + listenerName);
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001249 listener.onEvent(event);
1250 } catch (RuntimeException e) {
1251 Log.e(TAG_USER,
felipeal2a84d512020-04-06 18:52:15 -07001252 "Exception raised when invoking onEvent for " + listenerName, e);
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001253 } finally {
1254 t.traceEnd();
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001255 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001256 }
Antonio Kantek7236a5b2020-04-06 19:53:55 -07001257 t.traceEnd(); // notify-listeners-user-USERID-event-EVENT_TYPE
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001258 }
1259
felipeal98900c82020-04-09 09:05:02 -07001260 private void onUserSwitching(@UserIdInt int userId) {
Felipe Leme5528ff72020-02-10 19:05:14 -08001261 Log.i(TAG_USER, "onSwitchUser() callback for user " + userId);
1262 TimingsTraceLog t = new TimingsTraceLog(TAG_USER, Trace.TRACE_TAG_SYSTEM_SERVER);
felipeal98900c82020-04-09 09:05:02 -07001263 t.traceBegin("onUserSwitching-" + userId);
Felipe Leme5528ff72020-02-10 19:05:14 -08001264
Felipe Lemef45ee502019-12-19 10:00:14 -08001265 if (!isSystemUser(userId)) {
Eric Jeong3a793b02019-09-30 16:12:53 -07001266 mCarUserManagerHelper.setLastActiveUser(userId);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001267 }
Eric Jeongc91f9452019-08-30 15:04:21 -07001268 if (mLastPassengerId != UserHandle.USER_NULL) {
1269 stopPassengerInternal(mLastPassengerId, false);
1270 }
1271 if (mEnablePassengerSupport && isPassengerDisplayAvailable()) {
1272 setupPassengerUser();
1273 startFirstPassenger(userId);
1274 }
felipeal98900c82020-04-09 09:05:02 -07001275 t.traceEnd();
Pavel Maltsev17e81832019-04-04 14:38:41 -07001276 }
1277
1278 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001279 * 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 -08001280 * run inside this call.
Eric Jeong1545f3b2019-09-16 13:56:52 -07001281 *
Keun-young Parkd462a912019-02-11 08:53:42 -08001282 * @param r Runnable to run.
1283 */
Eric Jeong1545f3b2019-09-16 13:56:52 -07001284 public void runOnUser0Unlock(@NonNull Runnable r) {
Daulet Zhanguzin4ded6782020-01-03 15:47:10 +00001285 Objects.requireNonNull(r, "runnable cannot be null");
Keun-young Parkd462a912019-02-11 08:53:42 -08001286 boolean runNow = false;
Eric Jeongc91f9452019-08-30 15:04:21 -07001287 synchronized (mLockUser) {
Keun-young Parkd462a912019-02-11 08:53:42 -08001288 if (mUser0Unlocked) {
1289 runNow = true;
1290 } else {
1291 mUser0UnlockTasks.add(r);
1292 }
1293 }
1294 if (runNow) {
1295 r.run();
1296 }
1297 }
1298
Keun young Parkf3523cd2019-04-08 10:09:17 -07001299 @VisibleForTesting
Eric Jeong1545f3b2019-09-16 13:56:52 -07001300 @NonNull
1301 ArrayList<Integer> getBackgroundUsersToRestart() {
1302 ArrayList<Integer> backgroundUsersToRestart = null;
Eric Jeongc91f9452019-08-30 15:04:21 -07001303 synchronized (mLockUser) {
Keun young Parkf3523cd2019-04-08 10:09:17 -07001304 backgroundUsersToRestart = new ArrayList<>(mBackgroundUsersToRestart);
1305 }
1306 return backgroundUsersToRestart;
1307 }
1308
Ying Zheng1ab32b62018-06-26 12:47:26 -07001309 private void setSystemUserRestrictions() {
Ying Zheng1ab32b62018-06-26 12:47:26 -07001310 // Disable Location service for system user.
1311 LocationManager locationManager =
1312 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Anthony Hugh04ee04f2019-12-17 16:11:33 -08001313 locationManager.setLocationEnabledForUser(
1314 /* enabled= */ false, UserHandle.of(UserHandle.USER_SYSTEM));
Ying Zheng1ab32b62018-06-26 12:47:26 -07001315 }
Eric Jeong1545f3b2019-09-16 13:56:52 -07001316
1317 /**
1318 * Creates a new user on the system, the created user would be granted admin role.
1319 *
1320 * @param name Name to be given to the newly created user.
Eric Jeong3a793b02019-09-30 16:12:53 -07001321 * @return newly created admin user, {@code null} if it fails to create a user.
Eric Jeong1545f3b2019-09-16 13:56:52 -07001322 */
1323 @Nullable
1324 private UserInfo createNewAdminUser(String name) {
1325 if (!(mUserManager.isAdminUser() || mUserManager.isSystemUser())) {
1326 // Only admins or system user can create other privileged users.
1327 Log.e(TAG_USER, "Only admin users and system user can create other admins.");
1328 return null;
1329 }
1330
1331 UserInfo user = mUserManager.createUser(name, UserInfo.FLAG_ADMIN);
1332 if (user == null) {
1333 // Couldn't create user, most likely because there are too many.
1334 Log.w(TAG_USER, "can't create admin user.");
1335 return null;
1336 }
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001337 assignDefaultIcon(user);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001338
1339 return user;
1340 }
1341
Anthony Hugh6fed1e92019-10-22 16:22:03 -07001342 /**
1343 * Assigns a default icon to a user according to the user's id.
1344 *
1345 * @param userInfo User whose avatar is set to default icon.
1346 * @return Bitmap of the user icon.
1347 */
1348 private Bitmap assignDefaultIcon(UserInfo userInfo) {
1349 int idForIcon = userInfo.isGuest() ? UserHandle.USER_NULL : userInfo.id;
1350 Bitmap bitmap = UserIcons.convertToBitmap(
1351 UserIcons.getDefaultUserIcon(mContext.getResources(), idForIcon, false));
1352 mUserManager.setUserIcon(userInfo.id, bitmap);
1353 return bitmap;
1354 }
1355
Eric Jeong1545f3b2019-09-16 13:56:52 -07001356 private interface UserFilter {
1357 boolean isEligibleUser(UserInfo user);
1358 }
1359
1360 /** Returns all users who are matched by the given filter. */
1361 private List<UserInfo> getUsers(UserFilter filter) {
1362 List<UserInfo> users = mUserManager.getUsers(/* excludeDying= */ true);
1363
1364 for (Iterator<UserInfo> iterator = users.iterator(); iterator.hasNext(); ) {
1365 UserInfo user = iterator.next();
1366 if (!filter.isEligibleUser(user)) {
1367 iterator.remove();
1368 }
1369 }
1370 return users;
1371 }
1372
1373 /**
Eric Jeong1545f3b2019-09-16 13:56:52 -07001374 * Enforces that apps which have the
1375 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
1376 * can make certain calls to the CarUserManager.
1377 *
1378 * @param message used as message if SecurityException is thrown.
1379 * @throws SecurityException if the caller is not system or root.
1380 */
1381 private static void checkManageUsersPermission(String message) {
felipeal2d0483c2019-11-02 14:07:22 -07001382 checkAtLeastOnePermission(message, android.Manifest.permission.MANAGE_USERS);
1383 }
1384
1385 private static void checkManageUsersOrDumpPermission(String message) {
1386 checkAtLeastOnePermission(message,
1387 android.Manifest.permission.MANAGE_USERS,
1388 android.Manifest.permission.DUMP);
1389 }
1390
Felipe Leme5528ff72020-02-10 19:05:14 -08001391 private void checkInteractAcrossUsersPermission(String message) {
1392 checkAtLeastOnePermission(message, android.Manifest.permission.INTERACT_ACROSS_USERS,
1393 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
1394 }
1395
felipeal2d0483c2019-11-02 14:07:22 -07001396 private static void checkAtLeastOnePermission(String message, String...permissions) {
Eric Jeong1545f3b2019-09-16 13:56:52 -07001397 int callingUid = Binder.getCallingUid();
felipeal2d0483c2019-11-02 14:07:22 -07001398 if (!hasAtLeastOnePermissionGranted(callingUid, permissions)) {
1399 throw new SecurityException("You need one of " + Arrays.toString(permissions)
Felipe Leme5528ff72020-02-10 19:05:14 -08001400 + " to: " + message);
Eric Jeong1545f3b2019-09-16 13:56:52 -07001401 }
1402 }
1403
felipeal2d0483c2019-11-02 14:07:22 -07001404 private static boolean hasAtLeastOnePermissionGranted(int uid, String... permissions) {
1405 for (String permission : permissions) {
1406 if (ActivityManager.checkComponentPermission(permission, uid, /* owningUid = */-1,
1407 /* exported = */ true)
1408 == android.content.pm.PackageManager.PERMISSION_GRANTED) {
1409 return true;
1410 }
1411 }
1412 return false;
Eric Jeong1545f3b2019-09-16 13:56:52 -07001413 }
Eric Jeongc91f9452019-08-30 15:04:21 -07001414
1415 private int getNumberOfManagedProfiles(@UserIdInt int userId) {
1416 List<UserInfo> users = mUserManager.getUsers(/* excludeDying= */true);
1417 // Count all users that are managed profiles of the given user.
1418 int managedProfilesCount = 0;
1419 for (UserInfo user : users) {
1420 if (user.isManagedProfile() && user.profileGroupId == userId) {
1421 managedProfilesCount++;
1422 }
1423 }
1424 return managedProfilesCount;
1425 }
1426
1427 /**
1428 * Starts the first passenger of the given driver and assigns the passenger to the front
1429 * passenger zone.
1430 *
1431 * @param driverId User id of the driver.
1432 * @return whether it succeeds.
1433 */
1434 private boolean startFirstPassenger(@UserIdInt int driverId) {
1435 int zoneId = getAvailablePassengerZone();
1436 if (zoneId == OccupantZoneInfo.INVALID_ZONE_ID) {
1437 Log.w(TAG_USER, "passenger occupant zone is not found");
1438 return false;
1439 }
1440 List<UserInfo> passengers = getPassengers(driverId);
1441 if (passengers.size() < 1) {
1442 Log.w(TAG_USER, "passenger is not found");
1443 return false;
1444 }
1445 // Only one passenger is supported. If there are two or more passengers, the first passenger
1446 // is chosen.
1447 int passengerId = passengers.get(0).id;
1448 if (!startPassenger(passengerId, zoneId)) {
1449 Log.w(TAG_USER, "cannot start passenger " + passengerId);
1450 return false;
1451 }
1452 return true;
1453 }
1454
1455 private int getAvailablePassengerZone() {
1456 int[] occupantTypes = new int[] {CarOccupantZoneManager.OCCUPANT_TYPE_FRONT_PASSENGER,
1457 CarOccupantZoneManager.OCCUPANT_TYPE_REAR_PASSENGER};
1458 for (int occupantType : occupantTypes) {
1459 int zoneId = getZoneId(occupantType);
1460 if (zoneId != OccupantZoneInfo.INVALID_ZONE_ID) {
1461 return zoneId;
1462 }
1463 }
1464 return OccupantZoneInfo.INVALID_ZONE_ID;
1465 }
1466
1467 /**
1468 * Creates a new passenger user when there is no passenger user.
1469 */
1470 private void setupPassengerUser() {
1471 int currentUser = ActivityManager.getCurrentUser();
1472 int profileCount = getNumberOfManagedProfiles(currentUser);
1473 if (profileCount > 0) {
1474 Log.w(TAG_USER, "max profile of user" + currentUser
1475 + " is exceeded: current profile count is " + profileCount);
1476 return;
1477 }
1478 // TODO(b/140311342): Use resource string for the default passenger name.
1479 UserInfo passenger = createPassenger("Passenger", currentUser);
1480 if (passenger == null) {
1481 // Couldn't create user, most likely because there are too many.
1482 Log.w(TAG_USER, "cannot create a passenger user");
1483 return;
1484 }
1485 }
1486
1487 @NonNull
1488 private List<OccupantZoneInfo> getOccupantZones(@OccupantTypeEnum int occupantType) {
1489 ZoneUserBindingHelper helper = null;
1490 synchronized (mLockHelper) {
1491 if (mZoneUserBindingHelper == null) {
1492 Log.w(TAG_USER, "implementation is not delegated");
1493 return new ArrayList<OccupantZoneInfo>();
1494 }
1495 helper = mZoneUserBindingHelper;
1496 }
1497 return helper.getOccupantZones(occupantType);
1498 }
1499
1500 private boolean assignUserToOccupantZone(@UserIdInt int userId, int zoneId) {
1501 ZoneUserBindingHelper helper = null;
1502 synchronized (mLockHelper) {
1503 if (mZoneUserBindingHelper == null) {
1504 Log.w(TAG_USER, "implementation is not delegated");
1505 return false;
1506 }
1507 helper = mZoneUserBindingHelper;
1508 }
1509 return helper.assignUserToOccupantZone(userId, zoneId);
1510 }
1511
1512 private boolean unassignUserFromOccupantZone(@UserIdInt int userId) {
1513 ZoneUserBindingHelper helper = null;
1514 synchronized (mLockHelper) {
1515 if (mZoneUserBindingHelper == null) {
1516 Log.w(TAG_USER, "implementation is not delegated");
1517 return false;
1518 }
1519 helper = mZoneUserBindingHelper;
1520 }
1521 return helper.unassignUserFromOccupantZone(userId);
1522 }
1523
1524 private boolean isPassengerDisplayAvailable() {
1525 ZoneUserBindingHelper helper = null;
1526 synchronized (mLockHelper) {
1527 if (mZoneUserBindingHelper == null) {
1528 Log.w(TAG_USER, "implementation is not delegated");
1529 return false;
1530 }
1531 helper = mZoneUserBindingHelper;
1532 }
1533 return helper.isPassengerDisplayAvailable();
1534 }
1535
1536 /**
1537 * Gets the zone id of the given occupant type. If there are two or more zones, the first found
1538 * zone is returned.
1539 *
1540 * @param occupantType The type of an occupant.
1541 * @return The zone id of the given occupant type. {@link OccupantZoneInfo.INVALID_ZONE_ID},
1542 * if not found.
1543 */
1544 private int getZoneId(@OccupantTypeEnum int occupantType) {
1545 List<OccupantZoneInfo> zoneInfos = getOccupantZones(occupantType);
1546 return (zoneInfos.size() > 0) ? zoneInfos.get(0).zoneId : OccupantZoneInfo.INVALID_ZONE_ID;
1547 }
Antonio Kantek4cf199d2020-03-27 15:56:13 -07001548}