blob: e79a20618139c2f3fa1fa64f48f5918374eb244f [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) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700330 return getProfileParentLocked(userHandle);
331 }
332 }
333
334 private UserInfo getProfileParentLocked(int userHandle) {
335 UserInfo profile = getUserInfoLocked(userHandle);
336 if (profile == null) {
337 return null;
338 }
339 int parentUserId = profile.profileGroupId;
340 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
341 return null;
342 } else {
343 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100344 }
345 }
346
Kenny Guy2a764942014-04-02 13:29:20 +0100347 private boolean isProfileOf(UserInfo user, UserInfo profile) {
348 return user.id == profile.id ||
349 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
350 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000351 }
352
353 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100354 public void setUserEnabled(int userId) {
355 checkManageUsersPermission("enable user");
356 synchronized (mPackagesLock) {
357 UserInfo info = getUserInfoLocked(userId);
358 if (info != null && !info.isEnabled()) {
359 info.flags ^= UserInfo.FLAG_DISABLED;
360 writeUserLocked(info);
361 }
362 }
363 }
364
365 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700366 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700367 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700368 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700369 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700370 }
371 }
372
Amith Yamasani71e6c692013-03-24 17:39:28 -0700373 @Override
374 public boolean isRestricted() {
375 synchronized (mPackagesLock) {
376 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
377 }
378 }
379
Amith Yamasani195263742012-08-21 15:40:12 -0700380 /*
381 * Should be locked on mUsers before calling this.
382 */
383 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700384 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700385 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800386 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700387 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
388 return null;
389 }
390 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700391 }
392
Amith Yamasani13593602012-03-22 16:16:17 -0700393 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700394 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700395 return ArrayUtils.contains(mUserIds, userId);
396 }
397 }
398
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700400 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700401 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700402 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700403 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700404 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700405 if (info == null || info.partial) {
406 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
407 return;
408 }
Amith Yamasani13593602012-03-22 16:16:17 -0700409 if (name != null && !name.equals(info.name)) {
410 info.name = name;
411 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700412 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700413 }
414 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700415 if (changed) {
416 sendUserInfoChangedBroadcast(userId);
417 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700418 }
419
Amith Yamasani258848d2012-08-10 17:06:33 -0700420 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700421 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700422 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400423 long ident = Binder.clearCallingIdentity();
424 try {
425 synchronized (mPackagesLock) {
426 UserInfo info = mUsers.get(userId);
427 if (info == null || info.partial) {
428 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
429 return;
430 }
431 writeBitmapLocked(info, bitmap);
432 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700433 }
Jason Monk9a944532014-07-08 09:31:21 -0400434 sendUserInfoChangedBroadcast(userId);
435 } finally {
436 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700437 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700438 }
439
440 private void sendUserInfoChangedBroadcast(int userId) {
441 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
442 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
443 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700444 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700445 }
446
Amith Yamasani258848d2012-08-10 17:06:33 -0700447 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100448 public ParcelFileDescriptor getUserIcon(int userId) {
449 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700450 synchronized (mPackagesLock) {
451 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 if (info == null || info.partial) {
453 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
454 return null;
455 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100456 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
457 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
458 || callingGroupId != info.profileGroupId) {
459 checkManageUsersPermission("get the icon of a user who is not related");
460 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700461 if (info.iconPath == null) {
462 return null;
463 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100464 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700465 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100466
467 try {
468 return ParcelFileDescriptor.open(
469 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
470 } catch (FileNotFoundException e) {
471 Log.e(LOG_TAG, "Couldn't find icon file", e);
472 }
473 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700474 }
475
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700476 public void makeInitialized(int userId) {
477 checkManageUsersPermission("makeInitialized");
478 synchronized (mPackagesLock) {
479 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700480 if (info == null || info.partial) {
481 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
482 }
483 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700484 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800485 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700486 }
487 }
488 }
489
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700490 /**
491 * If default guest restrictions haven't been initialized yet, add the basic
492 * restrictions.
493 */
494 private void initDefaultGuestRestrictions() {
495 if (mGuestRestrictions.isEmpty()) {
496 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800497 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700498 }
499 }
500
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800501 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530502 public Bundle getDefaultGuestRestrictions() {
503 checkManageUsersPermission("getDefaultGuestRestrictions");
504 synchronized (mPackagesLock) {
505 return new Bundle(mGuestRestrictions);
506 }
507 }
508
509 @Override
510 public void setDefaultGuestRestrictions(Bundle restrictions) {
511 checkManageUsersPermission("setDefaultGuestRestrictions");
512 synchronized (mPackagesLock) {
513 mGuestRestrictions.clear();
514 mGuestRestrictions.putAll(restrictions);
515 writeUserListLocked();
516 }
517 }
518
519 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700520 public boolean hasUserRestriction(String restrictionKey, int userId) {
521 synchronized (mPackagesLock) {
522 Bundle restrictions = mUserRestrictions.get(userId);
523 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
524 }
525 }
526
527 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800528 public Bundle getUserRestrictions(int userId) {
529 // checkManageUsersPermission("getUserRestrictions");
530
531 synchronized (mPackagesLock) {
532 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700533 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800534 }
535 }
536
537 @Override
538 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700539 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700540 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800541
542 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700543 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800544 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400545 long token = Binder.clearCallingIdentity();
546 try {
547 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
548 } catch (RemoteException e) {
549 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
550 } finally {
551 Binder.restoreCallingIdentity(token);
552 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800553 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800554 }
555 }
556
Amith Yamasani258848d2012-08-10 17:06:33 -0700557 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700558 * Check if we've hit the limit of how many users can be created.
559 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700560 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700561 int aliveUserCount = 0;
562 final int totalUserCount = mUsers.size();
563 // Skip over users being removed
564 for (int i = 0; i < totalUserCount; i++) {
565 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700566 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700567 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700568 aliveUserCount++;
569 }
570 }
571 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700572 }
573
574 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700575 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700576 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700577 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700578 *
579 * @param message used as message if SecurityException is thrown
580 * @throws SecurityException if the caller is not system or root
581 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700582 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700583 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700584 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400585 && ActivityManager.checkComponentPermission(
586 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
588 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
589 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400590 }
591
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700592 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700593 try {
594 File dir = new File(mUsersDir, Integer.toString(info.id));
595 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100596 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 if (!dir.exists()) {
598 dir.mkdir();
599 FileUtils.setPermissions(
600 dir.getPath(),
601 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
602 -1, -1);
603 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700604 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100605 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
606 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700607 info.iconPath = file.getAbsolutePath();
608 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700609 try {
610 os.close();
611 } catch (IOException ioe) {
612 // What the ... !
613 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100614 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700615 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700616 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700617 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700618 }
619
Amith Yamasani0b285492011-04-14 17:35:23 -0700620 /**
621 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
622 * cache it elsewhere.
623 * @return the array of user ids.
624 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700625 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700626 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700627 return mUserIds;
628 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700629 }
630
Dianne Hackborn4428e172012-08-24 17:43:05 -0700631 int[] getUserIdsLPr() {
632 return mUserIds;
633 }
634
Amith Yamasani13593602012-03-22 16:16:17 -0700635 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700636 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700637 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700638 return;
639 }
640 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700641 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700642 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700643 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700644 XmlPullParser parser = Xml.newPullParser();
645 parser.setInput(fis, null);
646 int type;
647 while ((type = parser.next()) != XmlPullParser.START_TAG
648 && type != XmlPullParser.END_DOCUMENT) {
649 ;
650 }
651
652 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700653 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700654 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700655 return;
656 }
657
Amith Yamasani2a003292012-08-14 18:25:45 -0700658 mNextSerialNumber = -1;
659 if (parser.getName().equals(TAG_USERS)) {
660 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
661 if (lastSerialNumber != null) {
662 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
663 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700664 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
665 if (versionNumber != null) {
666 mUserVersion = Integer.parseInt(versionNumber);
667 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700668 }
669
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700670 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530671 if (type == XmlPullParser.START_TAG) {
672 final String name = parser.getName();
673 if (name.equals(TAG_USER)) {
674 String id = parser.getAttributeValue(null, ATTR_ID);
675 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700676
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530677 if (user != null) {
678 mUsers.put(user.id, user);
679 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
680 mNextSerialNumber = user.id + 1;
681 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700682 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530683 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800684 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
685 && type != XmlPullParser.END_TAG) {
686 if (type == XmlPullParser.START_TAG) {
687 if (parser.getName().equals(TAG_RESTRICTIONS)) {
688 readRestrictionsLocked(parser, mGuestRestrictions);
689 }
690 break;
691 }
692 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700693 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700694 }
695 }
Amith Yamasani13593602012-03-22 16:16:17 -0700696 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700697 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700699 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700700 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700701 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800702 } finally {
703 if (fis != null) {
704 try {
705 fis.close();
706 } catch (IOException e) {
707 }
708 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700709 }
710 }
711
Amith Yamasani6f34b412012-10-22 18:19:27 -0700712 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800713 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700714 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700715 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700716 int userVersion = mUserVersion;
717 if (userVersion < 1) {
718 // Assign a proper name for the owner, if not initialized correctly before
719 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
720 if ("Primary".equals(user.name)) {
721 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800722 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700723 }
724 userVersion = 1;
725 }
726
Amith Yamasanibc9625052012-11-15 14:39:18 -0800727 if (userVersion < 2) {
728 // Owner should be marked as initialized
729 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
730 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
731 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800732 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800733 }
734 userVersion = 2;
735 }
736
Amith Yamasani350962c2013-08-06 11:18:53 -0700737
Amith Yamasani5e486f52013-08-07 11:06:44 -0700738 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700739 userVersion = 4;
740 }
741
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700742 if (userVersion < 5) {
743 initDefaultGuestRestrictions();
744 userVersion = 5;
745 }
746
Amith Yamasani6f34b412012-10-22 18:19:27 -0700747 if (userVersion < USER_VERSION) {
748 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
749 + USER_VERSION);
750 } else {
751 mUserVersion = userVersion;
752 writeUserListLocked();
753 }
754 }
755
Amith Yamasani13593602012-03-22 16:16:17 -0700756 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800758 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700759 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700760 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700761 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700762 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400763 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800764
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500765 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800766 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
767
Amith Yamasani13593602012-03-22 16:16:17 -0700768 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700769 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700770
Amith Yamasani13593602012-03-22 16:16:17 -0700771 writeUserListLocked();
772 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 }
774
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800775 private void scheduleWriteUserLocked(UserInfo userInfo) {
776 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
777 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
778 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
779 }
780 }
781
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700782 /*
783 * Writes the user file in this format:
784 *
785 * <user flags="20039023" id="0">
786 * <name>Primary</name>
787 * </user>
788 */
Amith Yamasani13593602012-03-22 16:16:17 -0700789 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700790 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700791 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700792 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700793 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700794 final BufferedOutputStream bos = new BufferedOutputStream(fos);
795
796 // XmlSerializer serializer = XmlUtils.serializerInstance();
797 final XmlSerializer serializer = new FastXmlSerializer();
798 serializer.setOutput(bos, "utf-8");
799 serializer.startDocument(null, true);
800 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
801
802 serializer.startTag(null, TAG_USER);
803 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700804 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700805 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700806 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
807 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
808 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700809 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
810 if (pinState != null) {
811 if (pinState.salt != 0) {
812 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
813 }
814 if (pinState.pinHash != null) {
815 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
816 }
817 if (pinState.failedAttempts != 0) {
818 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
819 Integer.toString(pinState.failedAttempts));
820 serializer.attribute(null, ATTR_LAST_RETRY_MS,
821 Long.toString(pinState.lastAttemptTime));
822 }
823 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700824 if (userInfo.iconPath != null) {
825 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
826 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700827 if (userInfo.partial) {
828 serializer.attribute(null, ATTR_PARTIAL, "true");
829 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700830 if (userInfo.guestToRemove) {
831 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
832 }
Kenny Guy2a764942014-04-02 13:29:20 +0100833 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
834 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
835 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000836 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837
838 serializer.startTag(null, TAG_NAME);
839 serializer.text(userInfo.name);
840 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800841 Bundle restrictions = mUserRestrictions.get(userInfo.id);
842 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530843 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800844 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700845 serializer.endTag(null, TAG_USER);
846
847 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700848 userFile.finishWrite(fos);
849 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700850 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700851 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852 }
853 }
854
855 /*
856 * Writes the user list file in this format:
857 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700858 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700859 * <user id="0"></user>
860 * <user id="2"></user>
861 * </users>
862 */
Amith Yamasani13593602012-03-22 16:16:17 -0700863 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700864 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700865 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700866 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700867 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700868 final BufferedOutputStream bos = new BufferedOutputStream(fos);
869
870 // XmlSerializer serializer = XmlUtils.serializerInstance();
871 final XmlSerializer serializer = new FastXmlSerializer();
872 serializer.setOutput(bos, "utf-8");
873 serializer.startDocument(null, true);
874 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
875
876 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700877 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700878 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879
Adam Lesinskieddeb492014-09-08 17:50:03 -0700880 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530881 writeRestrictionsLocked(serializer, mGuestRestrictions);
882 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700883 for (int i = 0; i < mUsers.size(); i++) {
884 UserInfo user = mUsers.valueAt(i);
885 serializer.startTag(null, TAG_USER);
886 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
887 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700888 }
889
890 serializer.endTag(null, TAG_USERS);
891
892 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700893 userListFile.finishWrite(fos);
894 } catch (Exception e) {
895 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700896 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700897 }
898 }
899
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530900 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
901 throws IOException {
902 serializer.startTag(null, TAG_RESTRICTIONS);
903 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
904 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
905 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
906 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
907 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
908 writeBoolean(serializer, restrictions,
909 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
910 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
911 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
912 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
913 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
914 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
915 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
919 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
922 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
923 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700929 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
930 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000931 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000932 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530933 serializer.endTag(null, TAG_RESTRICTIONS);
934 }
935
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800936 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700937 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700938 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700940 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700941 long creationTime = 0L;
942 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700943 long salt = 0L;
944 String pinHash = null;
945 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100946 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700947 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700948 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700949 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800950 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700951
952 FileInputStream fis = null;
953 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700954 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700955 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700956 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 XmlPullParser parser = Xml.newPullParser();
958 parser.setInput(fis, null);
959 int type;
960 while ((type = parser.next()) != XmlPullParser.START_TAG
961 && type != XmlPullParser.END_DOCUMENT) {
962 ;
963 }
964
965 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700966 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 return null;
968 }
969
970 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700971 int storedId = readIntAttribute(parser, ATTR_ID, -1);
972 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700973 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700974 return null;
975 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700976 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
977 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700978 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700979 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
980 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700981 salt = readLongAttribute(parser, ATTR_SALT, 0L);
982 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
983 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
984 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100985 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
986 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700987 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
988 if ("true".equals(valueString)) {
989 partial = true;
990 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700991 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
992 if ("true".equals(valueString)) {
993 guestToRemove = true;
994 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800996 int outerDepth = parser.getDepth();
997 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
998 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
999 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1000 continue;
1001 }
1002 String tag = parser.getName();
1003 if (TAG_NAME.equals(tag)) {
1004 type = parser.next();
1005 if (type == XmlPullParser.TEXT) {
1006 name = parser.getText();
1007 }
1008 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301009 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001010 }
1011 }
1012 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001013
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001014 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001015 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001016 userInfo.creationTime = creationTime;
1017 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001018 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001019 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001020 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001021 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -07001022 if (salt != 0L) {
1023 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1024 if (pinState == null) {
1025 pinState = new RestrictionsPinState();
1026 mRestrictionsPinStates.put(id, pinState);
1027 }
1028 pinState.salt = salt;
1029 pinState.pinHash = pinHash;
1030 pinState.failedAttempts = failedAttempts;
1031 pinState.lastAttemptTime = lastAttemptTime;
1032 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 return userInfo;
1034
1035 } catch (IOException ioe) {
1036 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001037 } finally {
1038 if (fis != null) {
1039 try {
1040 fis.close();
1041 } catch (IOException e) {
1042 }
1043 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001044 }
1045 return null;
1046 }
1047
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301048 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1049 throws IOException {
1050 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1051 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1055 readBoolean(parser, restrictions,
1056 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1059 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1060 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1061 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1065 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1066 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1068 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1069 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1070 readBoolean(parser, restrictions,
1071 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1072 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1073 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001074 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1075 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001076 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001077 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1078 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001079 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001080 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301081 }
1082
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001083 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1084 String restrictionKey) {
1085 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001086 if (value != null) {
1087 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1088 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001089 }
1090
1091 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1092 throws IOException {
1093 if (restrictions.containsKey(restrictionKey)) {
1094 xml.attribute(null, restrictionKey,
1095 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1096 }
1097 }
1098
Amith Yamasani920ace02012-09-20 22:15:37 -07001099 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1100 String valueString = parser.getAttributeValue(null, attr);
1101 if (valueString == null) return defaultValue;
1102 try {
1103 return Integer.parseInt(valueString);
1104 } catch (NumberFormatException nfe) {
1105 return defaultValue;
1106 }
1107 }
1108
1109 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1110 String valueString = parser.getAttributeValue(null, attr);
1111 if (valueString == null) return defaultValue;
1112 try {
1113 return Long.parseLong(valueString);
1114 } catch (NumberFormatException nfe) {
1115 return defaultValue;
1116 }
1117 }
1118
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001119 private boolean isPackageInstalled(String pkg, int userId) {
1120 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1121 PackageManager.GET_UNINSTALLED_PACKAGES,
1122 userId);
1123 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1124 return false;
1125 }
1126 return true;
1127 }
1128
Amith Yamasanib82add22013-07-09 11:24:44 -07001129 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001130 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001131 * Does not do any permissions checking.
1132 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001133 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001134 synchronized (mPackagesLock) {
1135 File dir = Environment.getUserSystemDirectory(userId);
1136 String[] files = dir.list();
1137 if (files == null) return;
1138 for (String fileName : files) {
1139 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1140 File resFile = new File(dir, fileName);
1141 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001142 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001143 }
1144 }
1145 }
1146 }
1147 }
1148
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001149 /**
1150 * Removes the app restrictions file for a specific package and user id, if it exists.
1151 */
1152 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1153 synchronized (mPackagesLock) {
1154 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001155 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001156 if (resFile.exists()) {
1157 resFile.delete();
1158 }
1159 }
1160 }
1161
Kenny Guya52dc3e2014-02-11 15:33:14 +00001162 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001163 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001164 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001165 if (userId != UserHandle.USER_OWNER) {
1166 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001167 return null;
1168 }
Kenny Guy2a764942014-04-02 13:29:20 +01001169 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001170 }
1171
Amith Yamasani258848d2012-08-10 17:06:33 -07001172 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001173 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001174 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001175 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001176 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001177
Jessica Hummelbe81c802014-04-22 15:49:22 +01001178 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001179 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1180 UserManager.DISALLOW_ADD_USER, false)) {
1181 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1182 return null;
1183 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001184 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001185 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001186 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001187 try {
1188 synchronized (mInstallLock) {
1189 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001190 UserInfo parent = null;
1191 if (parentId != UserHandle.USER_NULL) {
1192 parent = getUserInfoLocked(parentId);
1193 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001194 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001195 // If we're not adding a guest user and the limit has been reached,
1196 // cannot add a user.
1197 if (!isGuest && isUserLimitReachedLocked()) {
1198 return null;
1199 }
1200 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001201 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001202 return null;
1203 }
1204 // Limit number of managed profiles that can be created
1205 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1206 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1207 >= MAX_MANAGED_PROFILES) {
1208 return null;
1209 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001210 int userId = getNextAvailableIdLocked();
1211 userInfo = new UserInfo(userId, name, null, flags);
1212 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1213 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001214 long now = System.currentTimeMillis();
1215 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001216 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001217 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001218 mUsers.put(userId, userInfo);
1219 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001220 if (parent != null) {
1221 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1222 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001223 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001224 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001225 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001226 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001227 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001228 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001229 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001230 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001231 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001232 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001233 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001234 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001235 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001236 if (userInfo != null) {
1237 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1238 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1239 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1240 android.Manifest.permission.MANAGE_USERS);
1241 }
1242 } finally {
1243 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001244 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001245 return userInfo;
1246 }
1247
Amith Yamasani95ab7842014-08-11 17:09:26 -07001248 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1249 int count = 0;
1250 for (int i = mUsers.size() - 1; i >= 0; i--) {
1251 UserInfo user = mUsers.valueAt(i);
1252 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1253 if ((user.flags & flags) != 0) {
1254 count++;
1255 }
1256 }
1257 }
1258 return count;
1259 }
1260
Amith Yamasani0b285492011-04-14 17:35:23 -07001261 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001262 * Find the current guest user. If the Guest user is partial,
1263 * then do not include it in the results as it is about to die.
1264 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1265 * the special handling of Guests being removed.
1266 */
1267 private UserInfo findCurrentGuestUserLocked() {
1268 final int size = mUsers.size();
1269 for (int i = 0; i < size; i++) {
1270 final UserInfo user = mUsers.valueAt(i);
1271 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1272 return user;
1273 }
1274 }
1275 return null;
1276 }
1277
1278 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001279 * Mark this guest user for deletion to allow us to create another guest
1280 * and switch to that user before actually removing this guest.
1281 * @param userHandle the userid of the current guest
1282 * @return whether the user could be marked for deletion
1283 */
1284 public boolean markGuestForDeletion(int userHandle) {
1285 checkManageUsersPermission("Only the system can remove users");
1286 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1287 UserManager.DISALLOW_REMOVE_USER, false)) {
1288 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1289 return false;
1290 }
1291
1292 long ident = Binder.clearCallingIdentity();
1293 try {
1294 final UserInfo user;
1295 synchronized (mPackagesLock) {
1296 user = mUsers.get(userHandle);
1297 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1298 return false;
1299 }
1300 if (!user.isGuest()) {
1301 return false;
1302 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001303 // We set this to a guest user that is to be removed. This is a temporary state
1304 // where we are allowed to add new Guest users, even if this one is still not
1305 // removed. This user will still show up in getUserInfo() calls.
1306 // If we don't get around to removing this Guest user, it will be purged on next
1307 // startup.
1308 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001309 // Mark it as disabled, so that it isn't returned any more when
1310 // profiles are queried.
1311 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001312 writeUserLocked(user);
1313 }
1314 } finally {
1315 Binder.restoreCallingIdentity(ident);
1316 }
1317 return true;
1318 }
1319
1320 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001321 * Removes a user and all data directories created for that user. This method should be called
1322 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001323 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001324 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001325 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001326 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001327 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1328 UserManager.DISALLOW_REMOVE_USER, false)) {
1329 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1330 return false;
1331 }
1332
Kenny Guyee58b4f2014-05-23 15:19:53 +01001333 long ident = Binder.clearCallingIdentity();
1334 try {
1335 final UserInfo user;
1336 synchronized (mPackagesLock) {
1337 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001338 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001339 return false;
1340 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001341
1342 // We remember deleted user IDs to prevent them from being
1343 // reused during the current boot; they can still be reused
1344 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001345 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001346
Kenny Guyee58b4f2014-05-23 15:19:53 +01001347 try {
1348 mAppOpsService.removeUser(userHandle);
1349 } catch (RemoteException e) {
1350 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1351 }
1352 // Set this to a partially created user, so that the user will be purged
1353 // on next startup, in case the runtime stops now before stopping and
1354 // removing the user completely.
1355 user.partial = true;
1356 // Mark it as disabled, so that it isn't returned any more when
1357 // profiles are queried.
1358 user.flags |= UserInfo.FLAG_DISABLED;
1359 writeUserLocked(user);
1360 }
1361
1362 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1363 && user.isManagedProfile()) {
1364 // Send broadcast to notify system that the user removed was a
1365 // managed user.
1366 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1367 }
1368
1369 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1370 int res;
1371 try {
1372 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1373 new IStopUserCallback.Stub() {
1374 @Override
1375 public void userStopped(int userId) {
1376 finishRemoveUser(userId);
1377 }
1378 @Override
1379 public void userStopAborted(int userId) {
1380 }
1381 });
1382 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001383 return false;
1384 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001385 return res == ActivityManager.USER_OP_SUCCESS;
1386 } finally {
1387 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001388 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001389 }
1390
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001391 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001392 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001393 // Let other services shutdown any activity and clean up their state before completely
1394 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001395 long ident = Binder.clearCallingIdentity();
1396 try {
1397 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1398 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001399 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1400 android.Manifest.permission.MANAGE_USERS,
1401
1402 new BroadcastReceiver() {
1403 @Override
1404 public void onReceive(Context context, Intent intent) {
1405 if (DBG) {
1406 Slog.i(LOG_TAG,
1407 "USER_REMOVED broadcast sent, cleaning up user data "
1408 + userHandle);
1409 }
1410 new Thread() {
1411 public void run() {
1412 synchronized (mInstallLock) {
1413 synchronized (mPackagesLock) {
1414 removeUserStateLocked(userHandle);
1415 }
1416 }
1417 }
1418 }.start();
1419 }
1420 },
1421
1422 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001423 } finally {
1424 Binder.restoreCallingIdentity(ident);
1425 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001426 }
1427
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001428 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001429 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001430 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001431
1432 // Remove this user from the list
1433 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001434
Amith Yamasani655d0e22013-06-12 14:19:10 -07001435 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001436 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001437 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001438 userFile.delete();
1439 // Update the user list
1440 writeUserListLocked();
1441 updateUserIdsLocked();
1442 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1443 }
1444
Amith Yamasani61f57372012-08-31 12:12:28 -07001445 private void removeDirectoryRecursive(File parent) {
1446 if (parent.isDirectory()) {
1447 String[] files = parent.list();
1448 for (String filename : files) {
1449 File child = new File(parent, filename);
1450 removeDirectoryRecursive(child);
1451 }
1452 }
1453 parent.delete();
1454 }
1455
Kenny Guyf8d3a232014-05-15 16:09:52 +01001456 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001457 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001458 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1459 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001460 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1461 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001462 }
1463
Amith Yamasani2a003292012-08-14 18:25:45 -07001464 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001465 public Bundle getApplicationRestrictions(String packageName) {
1466 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1467 }
1468
1469 @Override
1470 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001471 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001472 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001473 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001474 }
1475 synchronized (mPackagesLock) {
1476 // Read the restrictions from XML
1477 return readApplicationRestrictionsLocked(packageName, userId);
1478 }
1479 }
1480
1481 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001482 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001483 int userId) {
1484 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001485 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001486 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001487 }
1488 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001489 if (restrictions == null || restrictions.isEmpty()) {
1490 cleanAppRestrictionsForPackage(packageName, userId);
1491 } else {
1492 // Write the restrictions to XML
1493 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1494 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001495 }
Robin Lee66e5d962014-04-09 16:44:21 +01001496
Kenny Guyd21b2182014-07-17 16:38:55 +01001497 if (isPackageInstalled(packageName, userId)) {
1498 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1499 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1500 changeIntent.setPackage(packageName);
1501 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1502 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1503 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001504 }
1505
Amith Yamasani655d0e22013-06-12 14:19:10 -07001506 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001507 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001508 checkManageUsersPermission("Only system can modify the restrictions pin");
1509 int userId = UserHandle.getCallingUserId();
1510 synchronized (mPackagesLock) {
1511 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1512 if (pinState == null) {
1513 pinState = new RestrictionsPinState();
1514 }
1515 if (newPin == null) {
1516 pinState.salt = 0;
1517 pinState.pinHash = null;
1518 } else {
1519 try {
1520 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1521 } catch (NoSuchAlgorithmException e) {
1522 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1523 }
1524 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1525 pinState.failedAttempts = 0;
1526 }
1527 mRestrictionsPinStates.put(userId, pinState);
1528 writeUserLocked(mUsers.get(userId));
1529 }
1530 return true;
1531 }
1532
1533 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001534 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001535 checkManageUsersPermission("Only system can verify the restrictions pin");
1536 int userId = UserHandle.getCallingUserId();
1537 synchronized (mPackagesLock) {
1538 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1539 // If there's no pin set, return error code
1540 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1541 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1542 } else if (pin == null) {
1543 // If just checking if user can be prompted, return remaining time
1544 int waitTime = getRemainingTimeForPinAttempt(pinState);
1545 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1546 return waitTime;
1547 } else {
1548 int waitTime = getRemainingTimeForPinAttempt(pinState);
1549 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1550 if (waitTime > 0) {
1551 return waitTime;
1552 }
1553 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1554 pinState.failedAttempts = 0;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001555 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001556 return UserManager.PIN_VERIFICATION_SUCCESS;
1557 } else {
1558 pinState.failedAttempts++;
1559 pinState.lastAttemptTime = System.currentTimeMillis();
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001560 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001561 return waitTime;
1562 }
1563 }
1564 }
1565 }
1566
1567 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1568 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1569 BACKOFF_TIMES.length - 1);
1570 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1571 BACKOFF_TIMES[backoffIndex] : 0;
1572 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1573 0);
1574 }
1575
1576 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001577 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001578 int userId = UserHandle.getCallingUserId();
1579 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001580 return hasRestrictionsPinLocked(userId);
1581 }
1582 }
1583
1584 private boolean hasRestrictionsPinLocked(int userId) {
1585 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1586 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1587 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001588 }
1589 return true;
1590 }
1591
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001592 @Override
1593 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001594 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001595 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001596 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001597 }
1598
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001599 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001600 synchronized (mPackagesLock) {
1601 // Remove all user restrictions
1602 setUserRestrictions(new Bundle(), userHandle);
1603 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001604 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001605 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001606 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001607 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001608 if (unhideApps) {
1609 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001610 }
1611 }
1612
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001613 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001614 mHandler.post(new Runnable() {
1615 @Override
1616 public void run() {
1617 List<ApplicationInfo> apps =
1618 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1619 userHandle).getList();
1620 final long ident = Binder.clearCallingIdentity();
1621 try {
1622 for (ApplicationInfo appInfo : apps) {
1623 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001624 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1625 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001626 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001627 userHandle);
1628 }
1629 }
1630 } finally {
1631 Binder.restoreCallingIdentity(ident);
1632 }
1633 }
1634 });
1635 }
1636
Amith Yamasani655d0e22013-06-12 14:19:10 -07001637 /*
1638 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1639 * Not the most secure, but it is at least a second level of protection. First level is that
1640 * the file is in a location only readable by the system process.
1641 * @param password the password.
1642 * @param salt the randomly generated salt
1643 * @return the hash of the pattern in a String.
1644 */
1645 private String passwordToHash(String password, long salt) {
1646 if (password == null) {
1647 return null;
1648 }
1649 String algo = null;
1650 String hashed = salt + password;
1651 try {
1652 byte[] saltedPassword = (password + salt).getBytes();
1653 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1654 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1655 hashed = toHex(sha1) + toHex(md5);
1656 } catch (NoSuchAlgorithmException e) {
1657 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1658 }
1659 return hashed;
1660 }
1661
1662 private static String toHex(byte[] ary) {
1663 final String hex = "0123456789ABCDEF";
1664 String ret = "";
1665 for (int i = 0; i < ary.length; i++) {
1666 ret += hex.charAt((ary[i] >> 4) & 0xf);
1667 ret += hex.charAt(ary[i] & 0xf);
1668 }
1669 return ret;
1670 }
1671
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001672 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001673 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001674 try {
1675 return mContext.getPackageManager().getApplicationInfo(packageName,
1676 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1677 } catch (NameNotFoundException nnfe) {
1678 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001679 } finally {
1680 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001681 }
1682 }
1683
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001684 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001685 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001686 AtomicFile restrictionsFile =
1687 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1688 packageToRestrictionsFileName(packageName)));
1689 return readApplicationRestrictionsLocked(restrictionsFile);
1690 }
1691
1692 @VisibleForTesting
1693 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001694 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001695 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001696 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001697 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001698 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001699
1700 FileInputStream fis = null;
1701 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001702 fis = restrictionsFile.openRead();
1703 XmlPullParser parser = Xml.newPullParser();
1704 parser.setInput(fis, null);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001705 XmlUtils.nextElement(parser);
1706 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 Slog.e(LOG_TAG, "Unable to read restrictions file "
1708 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001709 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001710 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001711 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1712 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001714 } catch (IOException|XmlPullParserException e) {
1715 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001716 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001717 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001718 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001719 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001720 }
1721
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001722 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1723 XmlPullParser parser) throws XmlPullParserException, IOException {
1724 int type = parser.getEventType();
1725 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1726 String key = parser.getAttributeValue(null, ATTR_KEY);
1727 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1728 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1729 if (multiple != null) {
1730 values.clear();
1731 int count = Integer.parseInt(multiple);
1732 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1733 if (type == XmlPullParser.START_TAG
1734 && parser.getName().equals(TAG_VALUE)) {
1735 values.add(parser.nextText().trim());
1736 count--;
1737 }
1738 }
1739 String [] valueStrings = new String[values.size()];
1740 values.toArray(valueStrings);
1741 restrictions.putStringArray(key, valueStrings);
1742 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1743 restrictions.putBundle(key, readBundleEntry(parser, values));
1744 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1745 final int outerDepth = parser.getDepth();
1746 ArrayList<Bundle> bundleList = new ArrayList<>();
1747 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1748 Bundle childBundle = readBundleEntry(parser, values);
1749 bundleList.add(childBundle);
1750 }
1751 restrictions.putParcelableArray(key,
1752 bundleList.toArray(new Bundle[bundleList.size()]));
1753 } else {
1754 String value = parser.nextText().trim();
1755 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1756 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1757 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1758 restrictions.putInt(key, Integer.parseInt(value));
1759 } else {
1760 restrictions.putString(key, value);
1761 }
1762 }
1763 }
1764 }
1765
1766 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1767 throws IOException, XmlPullParserException {
1768 Bundle childBundle = new Bundle();
1769 final int outerDepth = parser.getDepth();
1770 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1771 readEntry(childBundle, values, parser);
1772 }
1773 return childBundle;
1774 }
1775
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001776 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001777 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001778 AtomicFile restrictionsFile = new AtomicFile(
1779 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001780 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001781 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1782 }
1783
1784 @VisibleForTesting
1785 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1786 AtomicFile restrictionsFile) {
1787 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001788 try {
1789 fos = restrictionsFile.startWrite();
1790 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1791
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001792 final XmlSerializer serializer = new FastXmlSerializer();
1793 serializer.setOutput(bos, "utf-8");
1794 serializer.startDocument(null, true);
1795 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1796
1797 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001798 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001799 serializer.endTag(null, TAG_RESTRICTIONS);
1800
1801 serializer.endDocument();
1802 restrictionsFile.finishWrite(fos);
1803 } catch (Exception e) {
1804 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001805 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1806 }
1807 }
1808
1809 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1810 throws IOException {
1811 for (String key : restrictions.keySet()) {
1812 Object value = restrictions.get(key);
1813 serializer.startTag(null, TAG_ENTRY);
1814 serializer.attribute(null, ATTR_KEY, key);
1815
1816 if (value instanceof Boolean) {
1817 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1818 serializer.text(value.toString());
1819 } else if (value instanceof Integer) {
1820 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1821 serializer.text(value.toString());
1822 } else if (value == null || value instanceof String) {
1823 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1824 serializer.text(value != null ? (String) value : "");
1825 } else if (value instanceof Bundle) {
1826 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1827 writeBundle((Bundle) value, serializer);
1828 } else if (value instanceof Parcelable[]) {
1829 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1830 Parcelable[] array = (Parcelable[]) value;
1831 for (Parcelable parcelable : array) {
1832 if (!(parcelable instanceof Bundle)) {
1833 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1834 }
1835 serializer.startTag(null, TAG_ENTRY);
1836 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1837 writeBundle((Bundle) parcelable, serializer);
1838 serializer.endTag(null, TAG_ENTRY);
1839 }
1840 } else {
1841 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1842 String[] values = (String[]) value;
1843 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1844 for (String choice : values) {
1845 serializer.startTag(null, TAG_VALUE);
1846 serializer.text(choice != null ? choice : "");
1847 serializer.endTag(null, TAG_VALUE);
1848 }
1849 }
1850 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001851 }
1852 }
1853
1854 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001855 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001856 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001857 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001858 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001859 }
1860 }
1861
1862 @Override
1863 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001864 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001865 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001866 UserInfo info = getUserInfoLocked(userId);
1867 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001868 }
1869 // Not found
1870 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001871 }
1872 }
1873
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001874 @Override
1875 public long getUserCreationTime(int userHandle) {
1876 int callingUserId = UserHandle.getCallingUserId();
1877 UserInfo userInfo = null;
1878 synchronized (mPackagesLock) {
1879 if (callingUserId == userHandle) {
1880 userInfo = getUserInfoLocked(userHandle);
1881 } else {
1882 UserInfo parent = getProfileParentLocked(userHandle);
1883 if (parent != null && parent.id == callingUserId) {
1884 userInfo = getUserInfoLocked(userHandle);
1885 }
1886 }
1887 }
1888 if (userInfo == null) {
1889 throw new SecurityException("userHandle can only be the calling user or a managed "
1890 + "profile associated with this user");
1891 }
1892 return userInfo.creationTime;
1893 }
1894
Amith Yamasani0b285492011-04-14 17:35:23 -07001895 /**
1896 * Caches the list of user ids in an array, adjusting the array size when necessary.
1897 */
Amith Yamasani13593602012-03-22 16:16:17 -07001898 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001899 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001900 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001901 if (!mUsers.valueAt(i).partial) {
1902 num++;
1903 }
1904 }
Amith Yamasani16389312012-10-17 21:20:14 -07001905 final int[] newUsers = new int[num];
1906 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001907 for (int i = 0; i < mUsers.size(); i++) {
1908 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001909 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001910 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001911 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001912 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001913 }
1914
1915 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001916 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001917 * @param userId the user that was just foregrounded
1918 */
1919 public void userForeground(int userId) {
1920 synchronized (mPackagesLock) {
1921 UserInfo user = mUsers.get(userId);
1922 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001923 if (user == null || user.partial) {
1924 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1925 return;
1926 }
1927 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001928 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001929 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001930 }
1931 }
1932 }
1933
1934 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001935 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001936 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1937 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001938 * @return
1939 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001940 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001941 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001942 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001943 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001944 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001945 break;
1946 }
1947 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001948 }
Amith Yamasani195263742012-08-21 15:40:12 -07001949 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001950 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001951 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001952
Amith Yamasanifc95e702013-09-26 13:20:17 -07001953 private String packageToRestrictionsFileName(String packageName) {
1954 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1955 }
1956
1957 private String restrictionsFileNameToPackage(String fileName) {
1958 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1959 (int) (fileName.length() - XML_SUFFIX.length()));
1960 }
1961
Amith Yamasani920ace02012-09-20 22:15:37 -07001962 @Override
1963 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1964 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1965 != PackageManager.PERMISSION_GRANTED) {
1966 pw.println("Permission Denial: can't dump UserManager from from pid="
1967 + Binder.getCallingPid()
1968 + ", uid=" + Binder.getCallingUid()
1969 + " without permission "
1970 + android.Manifest.permission.DUMP);
1971 return;
1972 }
1973
1974 long now = System.currentTimeMillis();
1975 StringBuilder sb = new StringBuilder();
1976 synchronized (mPackagesLock) {
1977 pw.println("Users:");
1978 for (int i = 0; i < mUsers.size(); i++) {
1979 UserInfo user = mUsers.valueAt(i);
1980 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001981 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001982 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001983 if (user.partial) pw.print(" <partial>");
1984 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001985 pw.print(" Created: ");
1986 if (user.creationTime == 0) {
1987 pw.println("<unknown>");
1988 } else {
1989 sb.setLength(0);
1990 TimeUtils.formatDuration(now - user.creationTime, sb);
1991 sb.append(" ago");
1992 pw.println(sb);
1993 }
1994 pw.print(" Last logged in: ");
1995 if (user.lastLoggedInTime == 0) {
1996 pw.println("<unknown>");
1997 } else {
1998 sb.setLength(0);
1999 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2000 sb.append(" ago");
2001 pw.println(sb);
2002 }
2003 }
2004 }
2005 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002006
2007 final class MainHandler extends Handler {
2008
2009 @Override
2010 public void handleMessage(Message msg) {
2011 switch (msg.what) {
2012 case WRITE_USER_MSG:
2013 removeMessages(WRITE_USER_MSG, msg.obj);
2014 synchronized (mPackagesLock) {
2015 int userId = ((UserInfo) msg.obj).id;
2016 UserInfo userInfo = mUsers.get(userId);
2017 if (userInfo != null) {
2018 writeUserLocked(userInfo);
2019 }
2020 }
2021 }
2022 }
2023 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002024}