blob: 5e58cd9389ec053765c194527bf02618f0d30795 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080032import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.os.Environment;
34import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080035import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080037import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010038import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070039import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Fyodor Kupolov262f9952015-03-23 18:55:11 -070053import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Fyodor Kupolov262f9952015-03-23 18:55:11 -070077import libcore.io.IoUtils;
78
Amith Yamasani258848d2012-08-10 17:06:33 -070079public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani2a003292012-08-14 18:25:45 -070081 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082
Amith Yamasani16389312012-10-17 21:20:14 -070083 private static final boolean DBG = false;
84
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070089 private static final String ATTR_CREATION_TIME = "created";
90 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070091 private static final String ATTR_SALT = "salt";
92 private static final String ATTR_PIN_HASH = "pinHash";
93 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
94 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070095 private static final String ATTR_SERIAL_NO = "serialNumber";
96 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070097 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070098 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070099 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100100 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530101 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800104 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String TAG_ENTRY = "entry";
106 private static final String TAG_VALUE = "value";
107 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
112 private static final String ATTR_TYPE_STRING = "s";
113 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700114 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700115 private static final String ATTR_TYPE_BUNDLE = "B";
116 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700117
Amith Yamasani0b285492011-04-14 17:35:23 -0700118 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700120 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100121 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800123 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700124 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800125
Amith Yamasani634cf312012-10-04 17:34:21 -0700126 private static final int MIN_USER_ID = 10;
127
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700128 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700129
Amith Yamasani920ace02012-09-20 22:15:37 -0700130 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
131
Amith Yamasani655d0e22013-06-12 14:19:10 -0700132 // Number of attempts before jumping to the next BACKOFF_TIMES slot
133 private static final int BACKOFF_INC_INTERVAL = 5;
134
Amith Yamasani95ab7842014-08-11 17:09:26 -0700135 // Maximum number of managed profiles permitted is 1. This cannot be increased
136 // without first making sure that the rest of the framework is prepared for it.
137 private static final int MAX_MANAGED_PROFILES = 1;
138
Amith Yamasani655d0e22013-06-12 14:19:10 -0700139 // Amount of time to force the user to wait before entering the PIN again, after failing
140 // BACKOFF_INC_INTERVAL times.
141 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
142
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800143 static final int WRITE_USER_MSG = 1;
144 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145
Dianne Hackborn4428e172012-08-24 17:43:05 -0700146 private final Context mContext;
147 private final PackageManagerService mPm;
148 private final Object mInstallLock;
149 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151 private final Handler mHandler;
152
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private final File mUsersDir;
154 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700155 private final File mBaseUserPath;
156
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800157 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800158 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800160
Amith Yamasani655d0e22013-06-12 14:19:10 -0700161 class RestrictionsPinState {
162 long salt;
163 String pinHash;
164 int failedAttempts;
165 long lastAttemptTime;
166 }
167
168 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
169 new SparseArray<RestrictionsPinState>();
170
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171 /**
172 * Set of user IDs being actively removed. Removed IDs linger in this set
173 * for several seconds to work around a VFS caching issue.
174 */
175 // @GuardedBy("mPackagesLock")
176 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Amith Yamasani0b285492011-04-14 17:35:23 -0700178 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700179 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700180 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700181
Jason Monk62062992014-05-06 09:55:28 -0400182 private IAppOpsService mAppOpsService;
183
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 public static UserManagerService getInstance() {
187 synchronized (UserManagerService.class) {
188 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
192 /**
193 * Available for testing purposes.
194 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700195 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Called by package manager to create the service. This is closely
201 * associated with the package manager, and the given lock is the
202 * package manager's own lock.
203 */
204 UserManagerService(Context context, PackageManagerService pm,
205 Object installLock, Object packagesLock) {
206 this(context, pm, installLock, packagesLock,
207 Environment.getDataDirectory(),
208 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700209 }
210
Dianne Hackborn4428e172012-08-24 17:43:05 -0700211 /**
212 * Available for testing purposes.
213 */
214 private UserManagerService(Context context, PackageManagerService pm,
215 Object installLock, Object packagesLock,
216 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 mContext = context;
218 mPm = pm;
219 mInstallLock = installLock;
220 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 synchronized (mInstallLock) {
223 synchronized (mPackagesLock) {
224 mUsersDir = new File(dataDir, USER_INFO_DIR);
225 mUsersDir.mkdirs();
226 // Make zeroth user directory, for services to migrate their files to that location
227 File userZeroDir = new File(mUsersDir, "0");
228 userZeroDir.mkdirs();
229 mBaseUserPath = baseUserPath;
230 FileUtils.setPermissions(mUsersDir.toString(),
231 FileUtils.S_IRWXU|FileUtils.S_IRWXG
232 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
233 -1, -1);
234 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800235 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700236 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700237 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700238 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
239 for (int i = 0; i < mUsers.size(); i++) {
240 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700241 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 partials.add(ui);
243 }
244 }
245 for (int i = 0; i < partials.size(); i++) {
246 UserInfo ui = partials.get(i);
247 Slog.w(LOG_TAG, "Removing partially created user #" + i
248 + " (name=" + ui.name + ")");
249 removeUserStateLocked(ui.id);
250 }
251 sInstance = this;
252 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700253 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700254 }
255
256 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700257 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400258 mAppOpsService = IAppOpsService.Stub.asInterface(
259 ServiceManager.getService(Context.APP_OPS_SERVICE));
260 for (int i = 0; i < mUserIds.length; ++i) {
261 try {
262 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
263 } catch (RemoteException e) {
264 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
265 }
266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
268
269 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700270 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700271 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700272 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700273 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
274 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700275 UserInfo ui = mUsers.valueAt(i);
276 if (ui.partial) {
277 continue;
278 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800279 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700280 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700281 }
Amith Yamasani13593602012-03-22 16:16:17 -0700282 }
283 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700284 }
Amith Yamasani13593602012-03-22 16:16:17 -0700285 }
286
Amith Yamasani258848d2012-08-10 17:06:33 -0700287 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100288 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800289 if (userId != UserHandle.getCallingUserId()) {
290 checkManageUsersPermission("getting profiles related to user " + userId);
291 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700292 final long ident = Binder.clearCallingIdentity();
293 try {
294 synchronized (mPackagesLock) {
295 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100296 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700297 } finally {
298 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000299 }
300 }
301
Amith Yamasanibe465322014-04-24 13:45:17 -0700302 /** Assume permissions already checked and caller's identity cleared */
303 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700304 UserInfo user = getUserInfoLocked(userId);
305 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700306 if (user == null) {
307 // Probably a dying user
308 return users;
309 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 for (int i = 0; i < mUsers.size(); i++) {
311 UserInfo profile = mUsers.valueAt(i);
312 if (!isProfileOf(user, profile)) {
313 continue;
314 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100315 if (enabledOnly && !profile.isEnabled()) {
316 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700317 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700318 if (mRemovingUserIds.get(profile.id)) {
319 continue;
320 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700321 users.add(profile);
322 }
323 return users;
324 }
325
Jessica Hummelbe81c802014-04-22 15:49:22 +0100326 @Override
327 public UserInfo getProfileParent(int userHandle) {
328 checkManageUsersPermission("get the profile parent");
329 synchronized (mPackagesLock) {
330 UserInfo profile = getUserInfoLocked(userHandle);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -0800331 if (profile == null) {
332 return null;
333 }
Jessica Hummelbe81c802014-04-22 15:49:22 +0100334 int parentUserId = profile.profileGroupId;
335 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
336 return null;
337 } else {
338 return getUserInfoLocked(parentUserId);
339 }
340 }
341 }
342
Kenny Guy2a764942014-04-02 13:29:20 +0100343 private boolean isProfileOf(UserInfo user, UserInfo profile) {
344 return user.id == profile.id ||
345 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
346 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000347 }
348
349 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100350 public void setUserEnabled(int userId) {
351 checkManageUsersPermission("enable user");
352 synchronized (mPackagesLock) {
353 UserInfo info = getUserInfoLocked(userId);
354 if (info != null && !info.isEnabled()) {
355 info.flags ^= UserInfo.FLAG_DISABLED;
356 writeUserLocked(info);
357 }
358 }
359 }
360
361 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700363 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700364 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700365 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700366 }
367 }
368
Amith Yamasani71e6c692013-03-24 17:39:28 -0700369 @Override
370 public boolean isRestricted() {
371 synchronized (mPackagesLock) {
372 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
373 }
374 }
375
Amith Yamasani195263742012-08-21 15:40:12 -0700376 /*
377 * Should be locked on mUsers before calling this.
378 */
379 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700380 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700381 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800382 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700383 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
384 return null;
385 }
386 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700387 }
388
Amith Yamasani13593602012-03-22 16:16:17 -0700389 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700390 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700391 return ArrayUtils.contains(mUserIds, userId);
392 }
393 }
394
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700396 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700397 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700398 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700399 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700400 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700401 if (info == null || info.partial) {
402 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
403 return;
404 }
Amith Yamasani13593602012-03-22 16:16:17 -0700405 if (name != null && !name.equals(info.name)) {
406 info.name = name;
407 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700408 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700409 }
410 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700411 if (changed) {
412 sendUserInfoChangedBroadcast(userId);
413 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700414 }
415
Amith Yamasani258848d2012-08-10 17:06:33 -0700416 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700417 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700418 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400419 long ident = Binder.clearCallingIdentity();
420 try {
421 synchronized (mPackagesLock) {
422 UserInfo info = mUsers.get(userId);
423 if (info == null || info.partial) {
424 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
425 return;
426 }
427 writeBitmapLocked(info, bitmap);
428 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700429 }
Jason Monk9a944532014-07-08 09:31:21 -0400430 sendUserInfoChangedBroadcast(userId);
431 } finally {
432 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700433 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700434 }
435
436 private void sendUserInfoChangedBroadcast(int userId) {
437 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
438 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
439 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700440 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700441 }
442
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100444 public ParcelFileDescriptor getUserIcon(int userId) {
445 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700446 synchronized (mPackagesLock) {
447 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700448 if (info == null || info.partial) {
449 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
450 return null;
451 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100452 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
453 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
454 || callingGroupId != info.profileGroupId) {
455 checkManageUsersPermission("get the icon of a user who is not related");
456 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (info.iconPath == null) {
458 return null;
459 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100460 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700461 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100462
463 try {
464 return ParcelFileDescriptor.open(
465 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
466 } catch (FileNotFoundException e) {
467 Log.e(LOG_TAG, "Couldn't find icon file", e);
468 }
469 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700470 }
471
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700472 public void makeInitialized(int userId) {
473 checkManageUsersPermission("makeInitialized");
474 synchronized (mPackagesLock) {
475 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700476 if (info == null || info.partial) {
477 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
478 }
479 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700480 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800481 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700482 }
483 }
484 }
485
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700486 /**
487 * If default guest restrictions haven't been initialized yet, add the basic
488 * restrictions.
489 */
490 private void initDefaultGuestRestrictions() {
491 if (mGuestRestrictions.isEmpty()) {
492 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800493 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700494 }
495 }
496
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800497 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530498 public Bundle getDefaultGuestRestrictions() {
499 checkManageUsersPermission("getDefaultGuestRestrictions");
500 synchronized (mPackagesLock) {
501 return new Bundle(mGuestRestrictions);
502 }
503 }
504
505 @Override
506 public void setDefaultGuestRestrictions(Bundle restrictions) {
507 checkManageUsersPermission("setDefaultGuestRestrictions");
508 synchronized (mPackagesLock) {
509 mGuestRestrictions.clear();
510 mGuestRestrictions.putAll(restrictions);
511 writeUserListLocked();
512 }
513 }
514
515 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700516 public boolean hasUserRestriction(String restrictionKey, int userId) {
517 synchronized (mPackagesLock) {
518 Bundle restrictions = mUserRestrictions.get(userId);
519 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
520 }
521 }
522
523 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800524 public Bundle getUserRestrictions(int userId) {
525 // checkManageUsersPermission("getUserRestrictions");
526
527 synchronized (mPackagesLock) {
528 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700529 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800530 }
531 }
532
533 @Override
534 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700535 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700536 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800537
538 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700539 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800540 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400541 long token = Binder.clearCallingIdentity();
542 try {
543 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
544 } catch (RemoteException e) {
545 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
546 } finally {
547 Binder.restoreCallingIdentity(token);
548 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800549 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800550 }
551 }
552
Amith Yamasani258848d2012-08-10 17:06:33 -0700553 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700554 * Check if we've hit the limit of how many users can be created.
555 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700556 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700557 int aliveUserCount = 0;
558 final int totalUserCount = mUsers.size();
559 // Skip over users being removed
560 for (int i = 0; i < totalUserCount; i++) {
561 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700562 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700563 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700564 aliveUserCount++;
565 }
566 }
567 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700568 }
569
570 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700571 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700572 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700573 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700574 *
575 * @param message used as message if SecurityException is thrown
576 * @throws SecurityException if the caller is not system or root
577 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700578 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700580 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400581 && ActivityManager.checkComponentPermission(
582 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700583 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
584 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
585 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400586 }
587
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700588 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 try {
590 File dir = new File(mUsersDir, Integer.toString(info.id));
591 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100592 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700593 if (!dir.exists()) {
594 dir.mkdir();
595 FileUtils.setPermissions(
596 dir.getPath(),
597 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
598 -1, -1);
599 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700600 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100601 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
602 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700603 info.iconPath = file.getAbsolutePath();
604 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700605 try {
606 os.close();
607 } catch (IOException ioe) {
608 // What the ... !
609 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100610 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700611 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700612 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700613 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700614 }
615
Amith Yamasani0b285492011-04-14 17:35:23 -0700616 /**
617 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
618 * cache it elsewhere.
619 * @return the array of user ids.
620 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700621 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700622 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700623 return mUserIds;
624 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700625 }
626
Dianne Hackborn4428e172012-08-24 17:43:05 -0700627 int[] getUserIdsLPr() {
628 return mUserIds;
629 }
630
Amith Yamasani13593602012-03-22 16:16:17 -0700631 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700633 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700634 return;
635 }
636 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700637 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700638 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700639 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 XmlPullParser parser = Xml.newPullParser();
641 parser.setInput(fis, null);
642 int type;
643 while ((type = parser.next()) != XmlPullParser.START_TAG
644 && type != XmlPullParser.END_DOCUMENT) {
645 ;
646 }
647
648 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700649 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700650 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700651 return;
652 }
653
Amith Yamasani2a003292012-08-14 18:25:45 -0700654 mNextSerialNumber = -1;
655 if (parser.getName().equals(TAG_USERS)) {
656 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
657 if (lastSerialNumber != null) {
658 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
659 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700660 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
661 if (versionNumber != null) {
662 mUserVersion = Integer.parseInt(versionNumber);
663 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700664 }
665
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700666 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530667 if (type == XmlPullParser.START_TAG) {
668 final String name = parser.getName();
669 if (name.equals(TAG_USER)) {
670 String id = parser.getAttributeValue(null, ATTR_ID);
671 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700672
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530673 if (user != null) {
674 mUsers.put(user.id, user);
675 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
676 mNextSerialNumber = user.id + 1;
677 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700678 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530679 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800680 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
681 && type != XmlPullParser.END_TAG) {
682 if (type == XmlPullParser.START_TAG) {
683 if (parser.getName().equals(TAG_RESTRICTIONS)) {
684 readRestrictionsLocked(parser, mGuestRestrictions);
685 }
686 break;
687 }
688 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700689 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700690 }
691 }
Amith Yamasani13593602012-03-22 16:16:17 -0700692 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700693 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700694 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700695 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700697 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800698 } finally {
699 if (fis != null) {
700 try {
701 fis.close();
702 } catch (IOException e) {
703 }
704 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700705 }
706 }
707
Amith Yamasani6f34b412012-10-22 18:19:27 -0700708 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800709 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700710 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700711 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700712 int userVersion = mUserVersion;
713 if (userVersion < 1) {
714 // Assign a proper name for the owner, if not initialized correctly before
715 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
716 if ("Primary".equals(user.name)) {
717 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800718 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700719 }
720 userVersion = 1;
721 }
722
Amith Yamasanibc9625052012-11-15 14:39:18 -0800723 if (userVersion < 2) {
724 // Owner should be marked as initialized
725 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
726 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
727 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800728 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800729 }
730 userVersion = 2;
731 }
732
Amith Yamasani350962c2013-08-06 11:18:53 -0700733
Amith Yamasani5e486f52013-08-07 11:06:44 -0700734 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700735 userVersion = 4;
736 }
737
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700738 if (userVersion < 5) {
739 initDefaultGuestRestrictions();
740 userVersion = 5;
741 }
742
Amith Yamasani6f34b412012-10-22 18:19:27 -0700743 if (userVersion < USER_VERSION) {
744 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
745 + USER_VERSION);
746 } else {
747 mUserVersion = userVersion;
748 writeUserListLocked();
749 }
750 }
751
Amith Yamasani13593602012-03-22 16:16:17 -0700752 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700753 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800754 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700755 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700756 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700758 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400759 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800760
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500761 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800762 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
763
Amith Yamasani13593602012-03-22 16:16:17 -0700764 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700765 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766
Amith Yamasani13593602012-03-22 16:16:17 -0700767 writeUserListLocked();
768 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700769 }
770
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800771 private void scheduleWriteUserLocked(UserInfo userInfo) {
772 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
773 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
774 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
775 }
776 }
777
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700778 /*
779 * Writes the user file in this format:
780 *
781 * <user flags="20039023" id="0">
782 * <name>Primary</name>
783 * </user>
784 */
Amith Yamasani13593602012-03-22 16:16:17 -0700785 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700786 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700787 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700789 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 final BufferedOutputStream bos = new BufferedOutputStream(fos);
791
792 // XmlSerializer serializer = XmlUtils.serializerInstance();
793 final XmlSerializer serializer = new FastXmlSerializer();
794 serializer.setOutput(bos, "utf-8");
795 serializer.startDocument(null, true);
796 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
797
798 serializer.startTag(null, TAG_USER);
799 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700800 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700801 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700802 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
803 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
804 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700805 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
806 if (pinState != null) {
807 if (pinState.salt != 0) {
808 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
809 }
810 if (pinState.pinHash != null) {
811 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
812 }
813 if (pinState.failedAttempts != 0) {
814 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
815 Integer.toString(pinState.failedAttempts));
816 serializer.attribute(null, ATTR_LAST_RETRY_MS,
817 Long.toString(pinState.lastAttemptTime));
818 }
819 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700820 if (userInfo.iconPath != null) {
821 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
822 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700823 if (userInfo.partial) {
824 serializer.attribute(null, ATTR_PARTIAL, "true");
825 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700826 if (userInfo.guestToRemove) {
827 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
828 }
Kenny Guy2a764942014-04-02 13:29:20 +0100829 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
830 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
831 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833
834 serializer.startTag(null, TAG_NAME);
835 serializer.text(userInfo.name);
836 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800837 Bundle restrictions = mUserRestrictions.get(userInfo.id);
838 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530839 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800840 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 serializer.endTag(null, TAG_USER);
842
843 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700844 userFile.finishWrite(fos);
845 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700846 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700847 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700848 }
849 }
850
851 /*
852 * Writes the user list file in this format:
853 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700854 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700855 * <user id="0"></user>
856 * <user id="2"></user>
857 * </users>
858 */
Amith Yamasani13593602012-03-22 16:16:17 -0700859 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700860 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700861 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700862 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700863 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700864 final BufferedOutputStream bos = new BufferedOutputStream(fos);
865
866 // XmlSerializer serializer = XmlUtils.serializerInstance();
867 final XmlSerializer serializer = new FastXmlSerializer();
868 serializer.setOutput(bos, "utf-8");
869 serializer.startDocument(null, true);
870 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
871
872 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700873 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700874 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700875
Adam Lesinskieddeb492014-09-08 17:50:03 -0700876 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530877 writeRestrictionsLocked(serializer, mGuestRestrictions);
878 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879 for (int i = 0; i < mUsers.size(); i++) {
880 UserInfo user = mUsers.valueAt(i);
881 serializer.startTag(null, TAG_USER);
882 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
883 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700884 }
885
886 serializer.endTag(null, TAG_USERS);
887
888 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700889 userListFile.finishWrite(fos);
890 } catch (Exception e) {
891 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700892 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700893 }
894 }
895
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530896 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
897 throws IOException {
898 serializer.startTag(null, TAG_RESTRICTIONS);
899 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
900 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
901 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
902 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
903 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
904 writeBoolean(serializer, restrictions,
905 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
906 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
907 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
908 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
909 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
910 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
911 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
912 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
913 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
914 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
915 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700922 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
923 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530929 serializer.endTag(null, TAG_RESTRICTIONS);
930 }
931
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800932 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700933 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700934 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700935 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700936 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700937 long creationTime = 0L;
938 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700939 long salt = 0L;
940 String pinHash = null;
941 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100942 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700943 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700945 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800946 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947
948 FileInputStream fis = null;
949 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700950 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700951 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700953 XmlPullParser parser = Xml.newPullParser();
954 parser.setInput(fis, null);
955 int type;
956 while ((type = parser.next()) != XmlPullParser.START_TAG
957 && type != XmlPullParser.END_DOCUMENT) {
958 ;
959 }
960
961 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 return null;
964 }
965
966 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700967 int storedId = readIntAttribute(parser, ATTR_ID, -1);
968 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700969 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 return null;
971 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700972 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
973 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700974 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700975 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
976 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700977 salt = readLongAttribute(parser, ATTR_SALT, 0L);
978 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
979 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
980 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100981 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
982 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700983 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
984 if ("true".equals(valueString)) {
985 partial = true;
986 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700987 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
988 if ("true".equals(valueString)) {
989 guestToRemove = true;
990 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800992 int outerDepth = parser.getDepth();
993 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
994 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
995 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
996 continue;
997 }
998 String tag = parser.getName();
999 if (TAG_NAME.equals(tag)) {
1000 type = parser.next();
1001 if (type == XmlPullParser.TEXT) {
1002 name = parser.getText();
1003 }
1004 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301005 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 }
1007 }
1008 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001009
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001010 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001011 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001012 userInfo.creationTime = creationTime;
1013 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001014 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001015 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001016 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001017 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -07001018 if (salt != 0L) {
1019 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1020 if (pinState == null) {
1021 pinState = new RestrictionsPinState();
1022 mRestrictionsPinStates.put(id, pinState);
1023 }
1024 pinState.salt = salt;
1025 pinState.pinHash = pinHash;
1026 pinState.failedAttempts = failedAttempts;
1027 pinState.lastAttemptTime = lastAttemptTime;
1028 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001029 return userInfo;
1030
1031 } catch (IOException ioe) {
1032 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001033 } finally {
1034 if (fis != null) {
1035 try {
1036 fis.close();
1037 } catch (IOException e) {
1038 }
1039 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001040 }
1041 return null;
1042 }
1043
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301044 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1045 throws IOException {
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1047 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1048 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1049 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1050 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1051 readBoolean(parser, restrictions,
1052 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1059 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1060 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1061 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1062 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1065 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1066 readBoolean(parser, restrictions,
1067 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1068 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1069 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001070 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1071 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001072 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001073 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1074 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001075 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001076 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301077 }
1078
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001079 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1080 String restrictionKey) {
1081 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001082 if (value != null) {
1083 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1084 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001085 }
1086
1087 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1088 throws IOException {
1089 if (restrictions.containsKey(restrictionKey)) {
1090 xml.attribute(null, restrictionKey,
1091 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1092 }
1093 }
1094
Amith Yamasani920ace02012-09-20 22:15:37 -07001095 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1096 String valueString = parser.getAttributeValue(null, attr);
1097 if (valueString == null) return defaultValue;
1098 try {
1099 return Integer.parseInt(valueString);
1100 } catch (NumberFormatException nfe) {
1101 return defaultValue;
1102 }
1103 }
1104
1105 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1106 String valueString = parser.getAttributeValue(null, attr);
1107 if (valueString == null) return defaultValue;
1108 try {
1109 return Long.parseLong(valueString);
1110 } catch (NumberFormatException nfe) {
1111 return defaultValue;
1112 }
1113 }
1114
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001115 private boolean isPackageInstalled(String pkg, int userId) {
1116 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1117 PackageManager.GET_UNINSTALLED_PACKAGES,
1118 userId);
1119 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1120 return false;
1121 }
1122 return true;
1123 }
1124
Amith Yamasanib82add22013-07-09 11:24:44 -07001125 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001126 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001127 * Does not do any permissions checking.
1128 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001129 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001130 synchronized (mPackagesLock) {
1131 File dir = Environment.getUserSystemDirectory(userId);
1132 String[] files = dir.list();
1133 if (files == null) return;
1134 for (String fileName : files) {
1135 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1136 File resFile = new File(dir, fileName);
1137 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001138 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001139 }
1140 }
1141 }
1142 }
1143 }
1144
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001145 /**
1146 * Removes the app restrictions file for a specific package and user id, if it exists.
1147 */
1148 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1149 synchronized (mPackagesLock) {
1150 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001151 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001152 if (resFile.exists()) {
1153 resFile.delete();
1154 }
1155 }
1156 }
1157
Kenny Guya52dc3e2014-02-11 15:33:14 +00001158 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001159 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001160 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001161 if (userId != UserHandle.USER_OWNER) {
1162 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001163 return null;
1164 }
Kenny Guy2a764942014-04-02 13:29:20 +01001165 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001166 }
1167
Amith Yamasani258848d2012-08-10 17:06:33 -07001168 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001169 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001170 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001171 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001172 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001173
Jessica Hummelbe81c802014-04-22 15:49:22 +01001174 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001175 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1176 UserManager.DISALLOW_ADD_USER, false)) {
1177 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1178 return null;
1179 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001180 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001181 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001182 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001183 try {
1184 synchronized (mInstallLock) {
1185 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001186 UserInfo parent = null;
1187 if (parentId != UserHandle.USER_NULL) {
1188 parent = getUserInfoLocked(parentId);
1189 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001190 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001191 // If we're not adding a guest user and the limit has been reached,
1192 // cannot add a user.
1193 if (!isGuest && isUserLimitReachedLocked()) {
1194 return null;
1195 }
1196 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001197 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001198 return null;
1199 }
1200 // Limit number of managed profiles that can be created
1201 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1202 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1203 >= MAX_MANAGED_PROFILES) {
1204 return null;
1205 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001206 int userId = getNextAvailableIdLocked();
1207 userInfo = new UserInfo(userId, name, null, flags);
1208 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1209 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001210 long now = System.currentTimeMillis();
1211 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001212 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001213 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001214 mUsers.put(userId, userInfo);
1215 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001216 if (parent != null) {
1217 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1218 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001219 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001220 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001221 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001222 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001223 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001224 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001225 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001226 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001227 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001228 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001229 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001230 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001231 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001232 if (userInfo != null) {
1233 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1234 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1235 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1236 android.Manifest.permission.MANAGE_USERS);
1237 }
1238 } finally {
1239 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001240 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001241 return userInfo;
1242 }
1243
Amith Yamasani95ab7842014-08-11 17:09:26 -07001244 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1245 int count = 0;
1246 for (int i = mUsers.size() - 1; i >= 0; i--) {
1247 UserInfo user = mUsers.valueAt(i);
1248 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1249 if ((user.flags & flags) != 0) {
1250 count++;
1251 }
1252 }
1253 }
1254 return count;
1255 }
1256
Amith Yamasani0b285492011-04-14 17:35:23 -07001257 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001258 * Find the current guest user. If the Guest user is partial,
1259 * then do not include it in the results as it is about to die.
1260 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1261 * the special handling of Guests being removed.
1262 */
1263 private UserInfo findCurrentGuestUserLocked() {
1264 final int size = mUsers.size();
1265 for (int i = 0; i < size; i++) {
1266 final UserInfo user = mUsers.valueAt(i);
1267 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1268 return user;
1269 }
1270 }
1271 return null;
1272 }
1273
1274 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001275 * Mark this guest user for deletion to allow us to create another guest
1276 * and switch to that user before actually removing this guest.
1277 * @param userHandle the userid of the current guest
1278 * @return whether the user could be marked for deletion
1279 */
1280 public boolean markGuestForDeletion(int userHandle) {
1281 checkManageUsersPermission("Only the system can remove users");
1282 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1283 UserManager.DISALLOW_REMOVE_USER, false)) {
1284 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1285 return false;
1286 }
1287
1288 long ident = Binder.clearCallingIdentity();
1289 try {
1290 final UserInfo user;
1291 synchronized (mPackagesLock) {
1292 user = mUsers.get(userHandle);
1293 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1294 return false;
1295 }
1296 if (!user.isGuest()) {
1297 return false;
1298 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001299 // We set this to a guest user that is to be removed. This is a temporary state
1300 // where we are allowed to add new Guest users, even if this one is still not
1301 // removed. This user will still show up in getUserInfo() calls.
1302 // If we don't get around to removing this Guest user, it will be purged on next
1303 // startup.
1304 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001305 // Mark it as disabled, so that it isn't returned any more when
1306 // profiles are queried.
1307 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001308 writeUserLocked(user);
1309 }
1310 } finally {
1311 Binder.restoreCallingIdentity(ident);
1312 }
1313 return true;
1314 }
1315
1316 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001317 * Removes a user and all data directories created for that user. This method should be called
1318 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001319 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001320 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001321 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001322 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001323 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1324 UserManager.DISALLOW_REMOVE_USER, false)) {
1325 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1326 return false;
1327 }
1328
Kenny Guyee58b4f2014-05-23 15:19:53 +01001329 long ident = Binder.clearCallingIdentity();
1330 try {
1331 final UserInfo user;
1332 synchronized (mPackagesLock) {
1333 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001334 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001335 return false;
1336 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001337
1338 // We remember deleted user IDs to prevent them from being
1339 // reused during the current boot; they can still be reused
1340 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001341 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001342
Kenny Guyee58b4f2014-05-23 15:19:53 +01001343 try {
1344 mAppOpsService.removeUser(userHandle);
1345 } catch (RemoteException e) {
1346 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1347 }
1348 // Set this to a partially created user, so that the user will be purged
1349 // on next startup, in case the runtime stops now before stopping and
1350 // removing the user completely.
1351 user.partial = true;
1352 // Mark it as disabled, so that it isn't returned any more when
1353 // profiles are queried.
1354 user.flags |= UserInfo.FLAG_DISABLED;
1355 writeUserLocked(user);
1356 }
1357
1358 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1359 && user.isManagedProfile()) {
1360 // Send broadcast to notify system that the user removed was a
1361 // managed user.
1362 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1363 }
1364
1365 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1366 int res;
1367 try {
1368 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1369 new IStopUserCallback.Stub() {
1370 @Override
1371 public void userStopped(int userId) {
1372 finishRemoveUser(userId);
1373 }
1374 @Override
1375 public void userStopAborted(int userId) {
1376 }
1377 });
1378 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001379 return false;
1380 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001381 return res == ActivityManager.USER_OP_SUCCESS;
1382 } finally {
1383 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001384 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001385 }
1386
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001387 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001388 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001389 // Let other services shutdown any activity and clean up their state before completely
1390 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001391 long ident = Binder.clearCallingIdentity();
1392 try {
1393 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1394 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001395 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1396 android.Manifest.permission.MANAGE_USERS,
1397
1398 new BroadcastReceiver() {
1399 @Override
1400 public void onReceive(Context context, Intent intent) {
1401 if (DBG) {
1402 Slog.i(LOG_TAG,
1403 "USER_REMOVED broadcast sent, cleaning up user data "
1404 + userHandle);
1405 }
1406 new Thread() {
1407 public void run() {
1408 synchronized (mInstallLock) {
1409 synchronized (mPackagesLock) {
1410 removeUserStateLocked(userHandle);
1411 }
1412 }
1413 }
1414 }.start();
1415 }
1416 },
1417
1418 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001419 } finally {
1420 Binder.restoreCallingIdentity(ident);
1421 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001422 }
1423
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001424 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001425 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001426 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001427
1428 // Remove this user from the list
1429 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001430
Amith Yamasani655d0e22013-06-12 14:19:10 -07001431 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001432 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001433 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001434 userFile.delete();
1435 // Update the user list
1436 writeUserListLocked();
1437 updateUserIdsLocked();
1438 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1439 }
1440
Amith Yamasani61f57372012-08-31 12:12:28 -07001441 private void removeDirectoryRecursive(File parent) {
1442 if (parent.isDirectory()) {
1443 String[] files = parent.list();
1444 for (String filename : files) {
1445 File child = new File(parent, filename);
1446 removeDirectoryRecursive(child);
1447 }
1448 }
1449 parent.delete();
1450 }
1451
Kenny Guyf8d3a232014-05-15 16:09:52 +01001452 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001453 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001454 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1455 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001456 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1457 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001458 }
1459
Amith Yamasani2a003292012-08-14 18:25:45 -07001460 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001461 public Bundle getApplicationRestrictions(String packageName) {
1462 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1463 }
1464
1465 @Override
1466 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001467 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001468 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001469 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001470 }
1471 synchronized (mPackagesLock) {
1472 // Read the restrictions from XML
1473 return readApplicationRestrictionsLocked(packageName, userId);
1474 }
1475 }
1476
1477 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001478 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001479 int userId) {
1480 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001481 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001482 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001483 }
1484 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001485 if (restrictions == null || restrictions.isEmpty()) {
1486 cleanAppRestrictionsForPackage(packageName, userId);
1487 } else {
1488 // Write the restrictions to XML
1489 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1490 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001491 }
Robin Lee66e5d962014-04-09 16:44:21 +01001492
Kenny Guyd21b2182014-07-17 16:38:55 +01001493 if (isPackageInstalled(packageName, userId)) {
1494 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1495 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1496 changeIntent.setPackage(packageName);
1497 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1498 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1499 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001500 }
1501
Amith Yamasani655d0e22013-06-12 14:19:10 -07001502 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001503 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001504 checkManageUsersPermission("Only system can modify the restrictions pin");
1505 int userId = UserHandle.getCallingUserId();
1506 synchronized (mPackagesLock) {
1507 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1508 if (pinState == null) {
1509 pinState = new RestrictionsPinState();
1510 }
1511 if (newPin == null) {
1512 pinState.salt = 0;
1513 pinState.pinHash = null;
1514 } else {
1515 try {
1516 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1517 } catch (NoSuchAlgorithmException e) {
1518 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1519 }
1520 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1521 pinState.failedAttempts = 0;
1522 }
1523 mRestrictionsPinStates.put(userId, pinState);
1524 writeUserLocked(mUsers.get(userId));
1525 }
1526 return true;
1527 }
1528
1529 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001530 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001531 checkManageUsersPermission("Only system can verify the restrictions pin");
1532 int userId = UserHandle.getCallingUserId();
1533 synchronized (mPackagesLock) {
1534 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1535 // If there's no pin set, return error code
1536 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1537 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1538 } else if (pin == null) {
1539 // If just checking if user can be prompted, return remaining time
1540 int waitTime = getRemainingTimeForPinAttempt(pinState);
1541 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1542 return waitTime;
1543 } else {
1544 int waitTime = getRemainingTimeForPinAttempt(pinState);
1545 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1546 if (waitTime > 0) {
1547 return waitTime;
1548 }
1549 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1550 pinState.failedAttempts = 0;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001551 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001552 return UserManager.PIN_VERIFICATION_SUCCESS;
1553 } else {
1554 pinState.failedAttempts++;
1555 pinState.lastAttemptTime = System.currentTimeMillis();
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001556 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001557 return waitTime;
1558 }
1559 }
1560 }
1561 }
1562
1563 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1564 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1565 BACKOFF_TIMES.length - 1);
1566 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1567 BACKOFF_TIMES[backoffIndex] : 0;
1568 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1569 0);
1570 }
1571
1572 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001573 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001574 int userId = UserHandle.getCallingUserId();
1575 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001576 return hasRestrictionsPinLocked(userId);
1577 }
1578 }
1579
1580 private boolean hasRestrictionsPinLocked(int userId) {
1581 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1582 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1583 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001584 }
1585 return true;
1586 }
1587
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001588 @Override
1589 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001590 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001591 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001592 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001593 }
1594
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001595 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001596 synchronized (mPackagesLock) {
1597 // Remove all user restrictions
1598 setUserRestrictions(new Bundle(), userHandle);
1599 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001600 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001601 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001602 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001603 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001604 if (unhideApps) {
1605 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001606 }
1607 }
1608
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001609 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001610 mHandler.post(new Runnable() {
1611 @Override
1612 public void run() {
1613 List<ApplicationInfo> apps =
1614 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1615 userHandle).getList();
1616 final long ident = Binder.clearCallingIdentity();
1617 try {
1618 for (ApplicationInfo appInfo : apps) {
1619 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001620 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1621 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001622 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001623 userHandle);
1624 }
1625 }
1626 } finally {
1627 Binder.restoreCallingIdentity(ident);
1628 }
1629 }
1630 });
1631 }
1632
Amith Yamasani655d0e22013-06-12 14:19:10 -07001633 /*
1634 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1635 * Not the most secure, but it is at least a second level of protection. First level is that
1636 * the file is in a location only readable by the system process.
1637 * @param password the password.
1638 * @param salt the randomly generated salt
1639 * @return the hash of the pattern in a String.
1640 */
1641 private String passwordToHash(String password, long salt) {
1642 if (password == null) {
1643 return null;
1644 }
1645 String algo = null;
1646 String hashed = salt + password;
1647 try {
1648 byte[] saltedPassword = (password + salt).getBytes();
1649 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1650 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1651 hashed = toHex(sha1) + toHex(md5);
1652 } catch (NoSuchAlgorithmException e) {
1653 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1654 }
1655 return hashed;
1656 }
1657
1658 private static String toHex(byte[] ary) {
1659 final String hex = "0123456789ABCDEF";
1660 String ret = "";
1661 for (int i = 0; i < ary.length; i++) {
1662 ret += hex.charAt((ary[i] >> 4) & 0xf);
1663 ret += hex.charAt(ary[i] & 0xf);
1664 }
1665 return ret;
1666 }
1667
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001669 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001670 try {
1671 return mContext.getPackageManager().getApplicationInfo(packageName,
1672 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1673 } catch (NameNotFoundException nnfe) {
1674 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001675 } finally {
1676 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001677 }
1678 }
1679
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001680 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001681 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001682 AtomicFile restrictionsFile =
1683 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1684 packageToRestrictionsFileName(packageName)));
1685 return readApplicationRestrictionsLocked(restrictionsFile);
1686 }
1687
1688 @VisibleForTesting
1689 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001690 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001691 final ArrayList<String> values = new ArrayList<>();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001692
1693 FileInputStream fis = null;
1694 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 fis = restrictionsFile.openRead();
1696 XmlPullParser parser = Xml.newPullParser();
1697 parser.setInput(fis, null);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001698 XmlUtils.nextElement(parser);
1699 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001700 Slog.e(LOG_TAG, "Unable to read restrictions file "
1701 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001702 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001703 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001704 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1705 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001706 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001707 } catch (IOException|XmlPullParserException e) {
1708 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001709 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001710 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001711 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001712 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 }
1714
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001715 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1716 XmlPullParser parser) throws XmlPullParserException, IOException {
1717 int type = parser.getEventType();
1718 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1719 String key = parser.getAttributeValue(null, ATTR_KEY);
1720 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1721 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1722 if (multiple != null) {
1723 values.clear();
1724 int count = Integer.parseInt(multiple);
1725 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1726 if (type == XmlPullParser.START_TAG
1727 && parser.getName().equals(TAG_VALUE)) {
1728 values.add(parser.nextText().trim());
1729 count--;
1730 }
1731 }
1732 String [] valueStrings = new String[values.size()];
1733 values.toArray(valueStrings);
1734 restrictions.putStringArray(key, valueStrings);
1735 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1736 restrictions.putBundle(key, readBundleEntry(parser, values));
1737 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1738 final int outerDepth = parser.getDepth();
1739 ArrayList<Bundle> bundleList = new ArrayList<>();
1740 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1741 Bundle childBundle = readBundleEntry(parser, values);
1742 bundleList.add(childBundle);
1743 }
1744 restrictions.putParcelableArray(key,
1745 bundleList.toArray(new Bundle[bundleList.size()]));
1746 } else {
1747 String value = parser.nextText().trim();
1748 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1749 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1750 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1751 restrictions.putInt(key, Integer.parseInt(value));
1752 } else {
1753 restrictions.putString(key, value);
1754 }
1755 }
1756 }
1757 }
1758
1759 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1760 throws IOException, XmlPullParserException {
1761 Bundle childBundle = new Bundle();
1762 final int outerDepth = parser.getDepth();
1763 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1764 readEntry(childBundle, values, parser);
1765 }
1766 return childBundle;
1767 }
1768
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001769 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001770 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001771 AtomicFile restrictionsFile = new AtomicFile(
1772 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001773 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001774 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1775 }
1776
1777 @VisibleForTesting
1778 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1779 AtomicFile restrictionsFile) {
1780 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001781 try {
1782 fos = restrictionsFile.startWrite();
1783 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1784
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001785 final XmlSerializer serializer = new FastXmlSerializer();
1786 serializer.setOutput(bos, "utf-8");
1787 serializer.startDocument(null, true);
1788 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1789
1790 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001791 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001792 serializer.endTag(null, TAG_RESTRICTIONS);
1793
1794 serializer.endDocument();
1795 restrictionsFile.finishWrite(fos);
1796 } catch (Exception e) {
1797 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001798 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1799 }
1800 }
1801
1802 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1803 throws IOException {
1804 for (String key : restrictions.keySet()) {
1805 Object value = restrictions.get(key);
1806 serializer.startTag(null, TAG_ENTRY);
1807 serializer.attribute(null, ATTR_KEY, key);
1808
1809 if (value instanceof Boolean) {
1810 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1811 serializer.text(value.toString());
1812 } else if (value instanceof Integer) {
1813 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1814 serializer.text(value.toString());
1815 } else if (value == null || value instanceof String) {
1816 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1817 serializer.text(value != null ? (String) value : "");
1818 } else if (value instanceof Bundle) {
1819 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1820 writeBundle((Bundle) value, serializer);
1821 } else if (value instanceof Parcelable[]) {
1822 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1823 Parcelable[] array = (Parcelable[]) value;
1824 for (Parcelable parcelable : array) {
1825 if (!(parcelable instanceof Bundle)) {
1826 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1827 }
1828 serializer.startTag(null, TAG_ENTRY);
1829 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1830 writeBundle((Bundle) parcelable, serializer);
1831 serializer.endTag(null, TAG_ENTRY);
1832 }
1833 } else {
1834 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1835 String[] values = (String[]) value;
1836 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1837 for (String choice : values) {
1838 serializer.startTag(null, TAG_VALUE);
1839 serializer.text(choice != null ? choice : "");
1840 serializer.endTag(null, TAG_VALUE);
1841 }
1842 }
1843 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001844 }
1845 }
1846
1847 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001848 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001849 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001850 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001851 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001852 }
1853 }
1854
1855 @Override
1856 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001857 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001858 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001859 UserInfo info = getUserInfoLocked(userId);
1860 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001861 }
1862 // Not found
1863 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001864 }
1865 }
1866
Amith Yamasani0b285492011-04-14 17:35:23 -07001867 /**
1868 * Caches the list of user ids in an array, adjusting the array size when necessary.
1869 */
Amith Yamasani13593602012-03-22 16:16:17 -07001870 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001871 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001872 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001873 if (!mUsers.valueAt(i).partial) {
1874 num++;
1875 }
1876 }
Amith Yamasani16389312012-10-17 21:20:14 -07001877 final int[] newUsers = new int[num];
1878 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001879 for (int i = 0; i < mUsers.size(); i++) {
1880 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001881 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001882 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001883 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001884 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001885 }
1886
1887 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001888 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001889 * @param userId the user that was just foregrounded
1890 */
1891 public void userForeground(int userId) {
1892 synchronized (mPackagesLock) {
1893 UserInfo user = mUsers.get(userId);
1894 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001895 if (user == null || user.partial) {
1896 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1897 return;
1898 }
1899 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001900 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001901 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001902 }
1903 }
1904 }
1905
1906 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001907 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001908 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1909 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001910 * @return
1911 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001912 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001913 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001914 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001915 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001916 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001917 break;
1918 }
1919 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001920 }
Amith Yamasani195263742012-08-21 15:40:12 -07001921 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001923 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001924
Amith Yamasanifc95e702013-09-26 13:20:17 -07001925 private String packageToRestrictionsFileName(String packageName) {
1926 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1927 }
1928
1929 private String restrictionsFileNameToPackage(String fileName) {
1930 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1931 (int) (fileName.length() - XML_SUFFIX.length()));
1932 }
1933
Amith Yamasani920ace02012-09-20 22:15:37 -07001934 @Override
1935 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1936 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1937 != PackageManager.PERMISSION_GRANTED) {
1938 pw.println("Permission Denial: can't dump UserManager from from pid="
1939 + Binder.getCallingPid()
1940 + ", uid=" + Binder.getCallingUid()
1941 + " without permission "
1942 + android.Manifest.permission.DUMP);
1943 return;
1944 }
1945
1946 long now = System.currentTimeMillis();
1947 StringBuilder sb = new StringBuilder();
1948 synchronized (mPackagesLock) {
1949 pw.println("Users:");
1950 for (int i = 0; i < mUsers.size(); i++) {
1951 UserInfo user = mUsers.valueAt(i);
1952 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001953 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001954 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001955 if (user.partial) pw.print(" <partial>");
1956 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001957 pw.print(" Created: ");
1958 if (user.creationTime == 0) {
1959 pw.println("<unknown>");
1960 } else {
1961 sb.setLength(0);
1962 TimeUtils.formatDuration(now - user.creationTime, sb);
1963 sb.append(" ago");
1964 pw.println(sb);
1965 }
1966 pw.print(" Last logged in: ");
1967 if (user.lastLoggedInTime == 0) {
1968 pw.println("<unknown>");
1969 } else {
1970 sb.setLength(0);
1971 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1972 sb.append(" ago");
1973 pw.println(sb);
1974 }
1975 }
1976 }
1977 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001978
1979 final class MainHandler extends Handler {
1980
1981 @Override
1982 public void handleMessage(Message msg) {
1983 switch (msg.what) {
1984 case WRITE_USER_MSG:
1985 removeMessages(WRITE_USER_MSG, msg.obj);
1986 synchronized (mPackagesLock) {
1987 int userId = ((UserInfo) msg.obj).id;
1988 UserInfo userInfo = mUsers.get(userId);
1989 if (userInfo != null) {
1990 writeUserLocked(userInfo);
1991 }
1992 }
1993 }
1994 }
1995 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001996}