blob: 26ecb729ab2762fd6ecd45bb04508a2045689998 [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;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070040import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040041import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070042import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070043import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070044import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070045import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070046import android.util.Slog;
47import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080048import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070049import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.util.Xml;
51
Jason Monk62062992014-05-06 09:55:28 -040052import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import com.android.internal.util.ArrayUtils;
54import com.android.internal.util.FastXmlSerializer;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
59
Amith Yamasani4b2e9342011-03-31 12:38:53 -070060import java.io.BufferedOutputStream;
61import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070062import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070064import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileOutputStream;
66import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070067import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070068import java.security.MessageDigest;
69import java.security.NoSuchAlgorithmException;
70import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.util.ArrayList;
72import java.util.List;
73
Amith Yamasani258848d2012-08-10 17:06:33 -070074public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075
Amith Yamasani2a003292012-08-14 18:25:45 -070076 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani16389312012-10-17 21:20:14 -070078 private static final boolean DBG = false;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070084 private static final String ATTR_CREATION_TIME = "created";
85 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070086 private static final String ATTR_SALT = "salt";
87 private static final String ATTR_PIN_HASH = "pinHash";
88 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
89 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070090 private static final String ATTR_SERIAL_NO = "serialNumber";
91 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070092 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070093 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010095 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053096 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080099 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800100 private static final String TAG_ENTRY = "entry";
101 private static final String TAG_VALUE = "value";
102 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700103 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800104 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700106 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
107 private static final String ATTR_TYPE_STRING = "s";
108 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700109 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100114 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700121 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani655d0e22013-06-12 14:19:10 -0700125 // Number of attempts before jumping to the next BACKOFF_TIMES slot
126 private static final int BACKOFF_INC_INTERVAL = 5;
127
Amith Yamasani95ab7842014-08-11 17:09:26 -0700128 // Maximum number of managed profiles permitted is 1. This cannot be increased
129 // without first making sure that the rest of the framework is prepared for it.
130 private static final int MAX_MANAGED_PROFILES = 1;
131
Amith Yamasani655d0e22013-06-12 14:19:10 -0700132 // Amount of time to force the user to wait before entering the PIN again, after failing
133 // BACKOFF_INC_INTERVAL times.
134 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
135
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800136 static final int WRITE_USER_MSG = 1;
137 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530138
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final Context mContext;
140 private final PackageManagerService mPm;
141 private final Object mInstallLock;
142 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800144 private final Handler mHandler;
145
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private final File mUsersDir;
147 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700148 private final File mBaseUserPath;
149
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800150 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800151 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530152 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800153
Amith Yamasani655d0e22013-06-12 14:19:10 -0700154 class RestrictionsPinState {
155 long salt;
156 String pinHash;
157 int failedAttempts;
158 long lastAttemptTime;
159 }
160
161 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
162 new SparseArray<RestrictionsPinState>();
163
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800164 /**
165 * Set of user IDs being actively removed. Removed IDs linger in this set
166 * for several seconds to work around a VFS caching issue.
167 */
168 // @GuardedBy("mPackagesLock")
169 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700170
Amith Yamasani0b285492011-04-14 17:35:23 -0700171 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700172 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700173 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700174
Jason Monk62062992014-05-06 09:55:28 -0400175 private IAppOpsService mAppOpsService;
176
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700178
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 public static UserManagerService getInstance() {
180 synchronized (UserManagerService.class) {
181 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700182 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700183 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184
185 /**
186 * Available for testing purposes.
187 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700188 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700189 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 }
191
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 /**
193 * Called by package manager to create the service. This is closely
194 * associated with the package manager, and the given lock is the
195 * package manager's own lock.
196 */
197 UserManagerService(Context context, PackageManagerService pm,
198 Object installLock, Object packagesLock) {
199 this(context, pm, installLock, packagesLock,
200 Environment.getDataDirectory(),
201 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700202 }
203
Dianne Hackborn4428e172012-08-24 17:43:05 -0700204 /**
205 * Available for testing purposes.
206 */
207 private UserManagerService(Context context, PackageManagerService pm,
208 Object installLock, Object packagesLock,
209 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700210 mContext = context;
211 mPm = pm;
212 mInstallLock = installLock;
213 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800214 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700215 synchronized (mInstallLock) {
216 synchronized (mPackagesLock) {
217 mUsersDir = new File(dataDir, USER_INFO_DIR);
218 mUsersDir.mkdirs();
219 // Make zeroth user directory, for services to migrate their files to that location
220 File userZeroDir = new File(mUsersDir, "0");
221 userZeroDir.mkdirs();
222 mBaseUserPath = baseUserPath;
223 FileUtils.setPermissions(mUsersDir.toString(),
224 FileUtils.S_IRWXU|FileUtils.S_IRWXG
225 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
226 -1, -1);
227 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800228 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700230 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700231 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
232 for (int i = 0; i < mUsers.size(); i++) {
233 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700234 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700235 partials.add(ui);
236 }
237 }
238 for (int i = 0; i < partials.size(); i++) {
239 UserInfo ui = partials.get(i);
240 Slog.w(LOG_TAG, "Removing partially created user #" + i
241 + " (name=" + ui.name + ")");
242 removeUserStateLocked(ui.id);
243 }
244 sInstance = this;
245 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700246 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700247 }
248
249 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700250 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400251 mAppOpsService = IAppOpsService.Stub.asInterface(
252 ServiceManager.getService(Context.APP_OPS_SERVICE));
253 for (int i = 0; i < mUserIds.length; ++i) {
254 try {
255 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
256 } catch (RemoteException e) {
257 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
258 }
259 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 }
261
262 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700263 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700264 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700265 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700266 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
267 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 UserInfo ui = mUsers.valueAt(i);
269 if (ui.partial) {
270 continue;
271 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800272 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700274 }
Amith Yamasani13593602012-03-22 16:16:17 -0700275 }
276 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700277 }
Amith Yamasani13593602012-03-22 16:16:17 -0700278 }
279
Amith Yamasani258848d2012-08-10 17:06:33 -0700280 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100281 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800282 if (userId != UserHandle.getCallingUserId()) {
283 checkManageUsersPermission("getting profiles related to user " + userId);
284 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 final long ident = Binder.clearCallingIdentity();
286 try {
287 synchronized (mPackagesLock) {
288 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100289 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 } finally {
291 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000292 }
293 }
294
Amith Yamasanibe465322014-04-24 13:45:17 -0700295 /** Assume permissions already checked and caller's identity cleared */
296 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700297 UserInfo user = getUserInfoLocked(userId);
298 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700299 if (user == null) {
300 // Probably a dying user
301 return users;
302 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700303 for (int i = 0; i < mUsers.size(); i++) {
304 UserInfo profile = mUsers.valueAt(i);
305 if (!isProfileOf(user, profile)) {
306 continue;
307 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100308 if (enabledOnly && !profile.isEnabled()) {
309 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700311 if (mRemovingUserIds.get(profile.id)) {
312 continue;
313 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700314 users.add(profile);
315 }
316 return users;
317 }
318
Jessica Hummelbe81c802014-04-22 15:49:22 +0100319 @Override
320 public UserInfo getProfileParent(int userHandle) {
321 checkManageUsersPermission("get the profile parent");
322 synchronized (mPackagesLock) {
323 UserInfo profile = getUserInfoLocked(userHandle);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -0800324 if (profile == null) {
325 return null;
326 }
Jessica Hummelbe81c802014-04-22 15:49:22 +0100327 int parentUserId = profile.profileGroupId;
328 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
329 return null;
330 } else {
331 return getUserInfoLocked(parentUserId);
332 }
333 }
334 }
335
Kenny Guy2a764942014-04-02 13:29:20 +0100336 private boolean isProfileOf(UserInfo user, UserInfo profile) {
337 return user.id == profile.id ||
338 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
339 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000340 }
341
342 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100343 public void setUserEnabled(int userId) {
344 checkManageUsersPermission("enable user");
345 synchronized (mPackagesLock) {
346 UserInfo info = getUserInfoLocked(userId);
347 if (info != null && !info.isEnabled()) {
348 info.flags ^= UserInfo.FLAG_DISABLED;
349 writeUserLocked(info);
350 }
351 }
352 }
353
354 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700355 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700356 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700357 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700358 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700359 }
360 }
361
Amith Yamasani71e6c692013-03-24 17:39:28 -0700362 @Override
363 public boolean isRestricted() {
364 synchronized (mPackagesLock) {
365 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
366 }
367 }
368
Amith Yamasani195263742012-08-21 15:40:12 -0700369 /*
370 * Should be locked on mUsers before calling this.
371 */
372 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700373 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700374 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800375 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700376 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
377 return null;
378 }
379 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700380 }
381
Amith Yamasani13593602012-03-22 16:16:17 -0700382 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700383 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700384 return ArrayUtils.contains(mUserIds, userId);
385 }
386 }
387
Amith Yamasani258848d2012-08-10 17:06:33 -0700388 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700389 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700390 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700391 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700392 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700393 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 if (info == null || info.partial) {
395 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
396 return;
397 }
Amith Yamasani13593602012-03-22 16:16:17 -0700398 if (name != null && !name.equals(info.name)) {
399 info.name = name;
400 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700401 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700402 }
403 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700404 if (changed) {
405 sendUserInfoChangedBroadcast(userId);
406 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700407 }
408
Amith Yamasani258848d2012-08-10 17:06:33 -0700409 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700410 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700411 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400412 long ident = Binder.clearCallingIdentity();
413 try {
414 synchronized (mPackagesLock) {
415 UserInfo info = mUsers.get(userId);
416 if (info == null || info.partial) {
417 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
418 return;
419 }
420 writeBitmapLocked(info, bitmap);
421 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700422 }
Jason Monk9a944532014-07-08 09:31:21 -0400423 sendUserInfoChangedBroadcast(userId);
424 } finally {
425 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700426 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700427 }
428
429 private void sendUserInfoChangedBroadcast(int userId) {
430 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
431 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
432 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700433 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700434 }
435
Amith Yamasani258848d2012-08-10 17:06:33 -0700436 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100437 public ParcelFileDescriptor getUserIcon(int userId) {
438 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700439 synchronized (mPackagesLock) {
440 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 if (info == null || info.partial) {
442 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
443 return null;
444 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100445 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
446 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
447 || callingGroupId != info.profileGroupId) {
448 checkManageUsersPermission("get the icon of a user who is not related");
449 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 if (info.iconPath == null) {
451 return null;
452 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100453 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700454 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100455
456 try {
457 return ParcelFileDescriptor.open(
458 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
459 } catch (FileNotFoundException e) {
460 Log.e(LOG_TAG, "Couldn't find icon file", e);
461 }
462 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700463 }
464
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700465 public void makeInitialized(int userId) {
466 checkManageUsersPermission("makeInitialized");
467 synchronized (mPackagesLock) {
468 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700469 if (info == null || info.partial) {
470 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
471 }
472 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700473 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800474 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700475 }
476 }
477 }
478
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700479 /**
480 * If default guest restrictions haven't been initialized yet, add the basic
481 * restrictions.
482 */
483 private void initDefaultGuestRestrictions() {
484 if (mGuestRestrictions.isEmpty()) {
485 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800486 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700487 }
488 }
489
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800490 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530491 public Bundle getDefaultGuestRestrictions() {
492 checkManageUsersPermission("getDefaultGuestRestrictions");
493 synchronized (mPackagesLock) {
494 return new Bundle(mGuestRestrictions);
495 }
496 }
497
498 @Override
499 public void setDefaultGuestRestrictions(Bundle restrictions) {
500 checkManageUsersPermission("setDefaultGuestRestrictions");
501 synchronized (mPackagesLock) {
502 mGuestRestrictions.clear();
503 mGuestRestrictions.putAll(restrictions);
504 writeUserListLocked();
505 }
506 }
507
508 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700509 public boolean hasUserRestriction(String restrictionKey, int userId) {
510 synchronized (mPackagesLock) {
511 Bundle restrictions = mUserRestrictions.get(userId);
512 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
513 }
514 }
515
516 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800517 public Bundle getUserRestrictions(int userId) {
518 // checkManageUsersPermission("getUserRestrictions");
519
520 synchronized (mPackagesLock) {
521 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700522 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800523 }
524 }
525
526 @Override
527 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700528 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700529 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800530
531 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700532 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800533 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400534 long token = Binder.clearCallingIdentity();
535 try {
536 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
537 } catch (RemoteException e) {
538 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
539 } finally {
540 Binder.restoreCallingIdentity(token);
541 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800542 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800543 }
544 }
545
Amith Yamasani258848d2012-08-10 17:06:33 -0700546 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700547 * Check if we've hit the limit of how many users can be created.
548 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700549 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700550 int aliveUserCount = 0;
551 final int totalUserCount = mUsers.size();
552 // Skip over users being removed
553 for (int i = 0; i < totalUserCount; i++) {
554 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700555 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700556 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700557 aliveUserCount++;
558 }
559 }
560 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700561 }
562
563 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700564 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700565 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700566 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700567 *
568 * @param message used as message if SecurityException is thrown
569 * @throws SecurityException if the caller is not system or root
570 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700571 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700573 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400574 && ActivityManager.checkComponentPermission(
575 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700576 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
577 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
578 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400579 }
580
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700581 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700582 try {
583 File dir = new File(mUsersDir, Integer.toString(info.id));
584 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100585 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700586 if (!dir.exists()) {
587 dir.mkdir();
588 FileUtils.setPermissions(
589 dir.getPath(),
590 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
591 -1, -1);
592 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700593 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100594 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
595 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700596 info.iconPath = file.getAbsolutePath();
597 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700598 try {
599 os.close();
600 } catch (IOException ioe) {
601 // What the ... !
602 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100603 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700604 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700605 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700606 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700607 }
608
Amith Yamasani0b285492011-04-14 17:35:23 -0700609 /**
610 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
611 * cache it elsewhere.
612 * @return the array of user ids.
613 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700614 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700615 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700616 return mUserIds;
617 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700618 }
619
Dianne Hackborn4428e172012-08-24 17:43:05 -0700620 int[] getUserIdsLPr() {
621 return mUserIds;
622 }
623
Amith Yamasani13593602012-03-22 16:16:17 -0700624 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700625 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700626 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700627 return;
628 }
629 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700630 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700632 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700633 XmlPullParser parser = Xml.newPullParser();
634 parser.setInput(fis, null);
635 int type;
636 while ((type = parser.next()) != XmlPullParser.START_TAG
637 && type != XmlPullParser.END_DOCUMENT) {
638 ;
639 }
640
641 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700642 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700643 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700644 return;
645 }
646
Amith Yamasani2a003292012-08-14 18:25:45 -0700647 mNextSerialNumber = -1;
648 if (parser.getName().equals(TAG_USERS)) {
649 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
650 if (lastSerialNumber != null) {
651 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
652 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700653 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
654 if (versionNumber != null) {
655 mUserVersion = Integer.parseInt(versionNumber);
656 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700657 }
658
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700659 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530660 if (type == XmlPullParser.START_TAG) {
661 final String name = parser.getName();
662 if (name.equals(TAG_USER)) {
663 String id = parser.getAttributeValue(null, ATTR_ID);
664 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700665
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530666 if (user != null) {
667 mUsers.put(user.id, user);
668 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
669 mNextSerialNumber = user.id + 1;
670 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700671 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530672 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800673 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
674 && type != XmlPullParser.END_TAG) {
675 if (type == XmlPullParser.START_TAG) {
676 if (parser.getName().equals(TAG_RESTRICTIONS)) {
677 readRestrictionsLocked(parser, mGuestRestrictions);
678 }
679 break;
680 }
681 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700682 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700683 }
684 }
Amith Yamasani13593602012-03-22 16:16:17 -0700685 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700686 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700687 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700688 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700690 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800691 } finally {
692 if (fis != null) {
693 try {
694 fis.close();
695 } catch (IOException e) {
696 }
697 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 }
699 }
700
Amith Yamasani6f34b412012-10-22 18:19:27 -0700701 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800702 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700703 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700704 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700705 int userVersion = mUserVersion;
706 if (userVersion < 1) {
707 // Assign a proper name for the owner, if not initialized correctly before
708 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
709 if ("Primary".equals(user.name)) {
710 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800711 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700712 }
713 userVersion = 1;
714 }
715
Amith Yamasanibc9625052012-11-15 14:39:18 -0800716 if (userVersion < 2) {
717 // Owner should be marked as initialized
718 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
719 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
720 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800721 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800722 }
723 userVersion = 2;
724 }
725
Amith Yamasani350962c2013-08-06 11:18:53 -0700726
Amith Yamasani5e486f52013-08-07 11:06:44 -0700727 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700728 userVersion = 4;
729 }
730
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700731 if (userVersion < 5) {
732 initDefaultGuestRestrictions();
733 userVersion = 5;
734 }
735
Amith Yamasani6f34b412012-10-22 18:19:27 -0700736 if (userVersion < USER_VERSION) {
737 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
738 + USER_VERSION);
739 } else {
740 mUserVersion = userVersion;
741 writeUserListLocked();
742 }
743 }
744
Amith Yamasani13593602012-03-22 16:16:17 -0700745 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800747 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700748 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700749 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700750 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700751 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400752 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800753
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500754 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800755 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
756
Amith Yamasani13593602012-03-22 16:16:17 -0700757 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700758 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759
Amith Yamasani13593602012-03-22 16:16:17 -0700760 writeUserListLocked();
761 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762 }
763
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800764 private void scheduleWriteUserLocked(UserInfo userInfo) {
765 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
766 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
767 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
768 }
769 }
770
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700771 /*
772 * Writes the user file in this format:
773 *
774 * <user flags="20039023" id="0">
775 * <name>Primary</name>
776 * </user>
777 */
Amith Yamasani13593602012-03-22 16:16:17 -0700778 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700779 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700780 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700781 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700782 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700783 final BufferedOutputStream bos = new BufferedOutputStream(fos);
784
785 // XmlSerializer serializer = XmlUtils.serializerInstance();
786 final XmlSerializer serializer = new FastXmlSerializer();
787 serializer.setOutput(bos, "utf-8");
788 serializer.startDocument(null, true);
789 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
790
791 serializer.startTag(null, TAG_USER);
792 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700793 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700794 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700795 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
796 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
797 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700798 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
799 if (pinState != null) {
800 if (pinState.salt != 0) {
801 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
802 }
803 if (pinState.pinHash != null) {
804 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
805 }
806 if (pinState.failedAttempts != 0) {
807 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
808 Integer.toString(pinState.failedAttempts));
809 serializer.attribute(null, ATTR_LAST_RETRY_MS,
810 Long.toString(pinState.lastAttemptTime));
811 }
812 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700813 if (userInfo.iconPath != null) {
814 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
815 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700816 if (userInfo.partial) {
817 serializer.attribute(null, ATTR_PARTIAL, "true");
818 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700819 if (userInfo.guestToRemove) {
820 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
821 }
Kenny Guy2a764942014-04-02 13:29:20 +0100822 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
823 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
824 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000825 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700826
827 serializer.startTag(null, TAG_NAME);
828 serializer.text(userInfo.name);
829 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800830 Bundle restrictions = mUserRestrictions.get(userInfo.id);
831 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530832 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800833 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700834 serializer.endTag(null, TAG_USER);
835
836 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700837 userFile.finishWrite(fos);
838 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700839 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700840 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 }
842 }
843
844 /*
845 * Writes the user list file in this format:
846 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700847 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700848 * <user id="0"></user>
849 * <user id="2"></user>
850 * </users>
851 */
Amith Yamasani13593602012-03-22 16:16:17 -0700852 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700853 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700854 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700855 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700856 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700857 final BufferedOutputStream bos = new BufferedOutputStream(fos);
858
859 // XmlSerializer serializer = XmlUtils.serializerInstance();
860 final XmlSerializer serializer = new FastXmlSerializer();
861 serializer.setOutput(bos, "utf-8");
862 serializer.startDocument(null, true);
863 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
864
865 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700866 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700867 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700868
Adam Lesinskieddeb492014-09-08 17:50:03 -0700869 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530870 writeRestrictionsLocked(serializer, mGuestRestrictions);
871 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700872 for (int i = 0; i < mUsers.size(); i++) {
873 UserInfo user = mUsers.valueAt(i);
874 serializer.startTag(null, TAG_USER);
875 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
876 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700877 }
878
879 serializer.endTag(null, TAG_USERS);
880
881 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700882 userListFile.finishWrite(fos);
883 } catch (Exception e) {
884 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700885 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886 }
887 }
888
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530889 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
890 throws IOException {
891 serializer.startTag(null, TAG_RESTRICTIONS);
892 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
893 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
894 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
895 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
896 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
897 writeBoolean(serializer, restrictions,
898 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
899 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
900 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
901 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
902 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
903 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
904 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
905 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
906 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
907 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
908 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
909 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
910 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
911 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
912 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
913 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
914 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700915 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530922 serializer.endTag(null, TAG_RESTRICTIONS);
923 }
924
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800925 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700929 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700930 long creationTime = 0L;
931 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700932 long salt = 0L;
933 String pinHash = null;
934 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100935 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700936 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700937 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700938 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800939 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940
941 FileInputStream fis = null;
942 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700944 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700945 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700946 XmlPullParser parser = Xml.newPullParser();
947 parser.setInput(fis, null);
948 int type;
949 while ((type = parser.next()) != XmlPullParser.START_TAG
950 && type != XmlPullParser.END_DOCUMENT) {
951 ;
952 }
953
954 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700955 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700956 return null;
957 }
958
959 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700960 int storedId = readIntAttribute(parser, ATTR_ID, -1);
961 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 return null;
964 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700965 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
966 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700967 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700968 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
969 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700970 salt = readLongAttribute(parser, ATTR_SALT, 0L);
971 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
972 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
973 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100974 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
975 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700976 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
977 if ("true".equals(valueString)) {
978 partial = true;
979 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700980 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
981 if ("true".equals(valueString)) {
982 guestToRemove = true;
983 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800985 int outerDepth = parser.getDepth();
986 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
987 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
988 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
989 continue;
990 }
991 String tag = parser.getName();
992 if (TAG_NAME.equals(tag)) {
993 type = parser.next();
994 if (type == XmlPullParser.TEXT) {
995 name = parser.getText();
996 }
997 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530998 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700999 }
1000 }
1001 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001002
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001003 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001004 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001005 userInfo.creationTime = creationTime;
1006 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001007 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001008 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001009 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001010 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -07001011 if (salt != 0L) {
1012 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1013 if (pinState == null) {
1014 pinState = new RestrictionsPinState();
1015 mRestrictionsPinStates.put(id, pinState);
1016 }
1017 pinState.salt = salt;
1018 pinState.pinHash = pinHash;
1019 pinState.failedAttempts = failedAttempts;
1020 pinState.lastAttemptTime = lastAttemptTime;
1021 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001022 return userInfo;
1023
1024 } catch (IOException ioe) {
1025 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001026 } finally {
1027 if (fis != null) {
1028 try {
1029 fis.close();
1030 } catch (IOException e) {
1031 }
1032 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 }
1034 return null;
1035 }
1036
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301037 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1038 throws IOException {
1039 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1040 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1041 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1042 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1043 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1044 readBoolean(parser, restrictions,
1045 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1047 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1048 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1049 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1050 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1051 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1055 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1059 readBoolean(parser, restrictions,
1060 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1061 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001063 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001065 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001066 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001068 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001069 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301070 }
1071
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001072 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1073 String restrictionKey) {
1074 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001075 if (value != null) {
1076 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1077 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001078 }
1079
1080 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1081 throws IOException {
1082 if (restrictions.containsKey(restrictionKey)) {
1083 xml.attribute(null, restrictionKey,
1084 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1085 }
1086 }
1087
Amith Yamasani920ace02012-09-20 22:15:37 -07001088 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1089 String valueString = parser.getAttributeValue(null, attr);
1090 if (valueString == null) return defaultValue;
1091 try {
1092 return Integer.parseInt(valueString);
1093 } catch (NumberFormatException nfe) {
1094 return defaultValue;
1095 }
1096 }
1097
1098 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1099 String valueString = parser.getAttributeValue(null, attr);
1100 if (valueString == null) return defaultValue;
1101 try {
1102 return Long.parseLong(valueString);
1103 } catch (NumberFormatException nfe) {
1104 return defaultValue;
1105 }
1106 }
1107
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001108 private boolean isPackageInstalled(String pkg, int userId) {
1109 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1110 PackageManager.GET_UNINSTALLED_PACKAGES,
1111 userId);
1112 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1113 return false;
1114 }
1115 return true;
1116 }
1117
Amith Yamasanib82add22013-07-09 11:24:44 -07001118 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001119 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001120 * Does not do any permissions checking.
1121 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001122 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001123 synchronized (mPackagesLock) {
1124 File dir = Environment.getUserSystemDirectory(userId);
1125 String[] files = dir.list();
1126 if (files == null) return;
1127 for (String fileName : files) {
1128 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1129 File resFile = new File(dir, fileName);
1130 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001131 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001132 }
1133 }
1134 }
1135 }
1136 }
1137
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001138 /**
1139 * Removes the app restrictions file for a specific package and user id, if it exists.
1140 */
1141 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1142 synchronized (mPackagesLock) {
1143 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001144 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001145 if (resFile.exists()) {
1146 resFile.delete();
1147 }
1148 }
1149 }
1150
Kenny Guya52dc3e2014-02-11 15:33:14 +00001151 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001152 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001153 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001154 if (userId != UserHandle.USER_OWNER) {
1155 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001156 return null;
1157 }
Kenny Guy2a764942014-04-02 13:29:20 +01001158 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001159 }
1160
Amith Yamasani258848d2012-08-10 17:06:33 -07001161 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001162 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001163 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001164 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001165 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001166
Jessica Hummelbe81c802014-04-22 15:49:22 +01001167 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001168 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1169 UserManager.DISALLOW_ADD_USER, false)) {
1170 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1171 return null;
1172 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001173 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001174 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001175 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001176 try {
1177 synchronized (mInstallLock) {
1178 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001179 UserInfo parent = null;
1180 if (parentId != UserHandle.USER_NULL) {
1181 parent = getUserInfoLocked(parentId);
1182 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001183 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001184 // If we're not adding a guest user and the limit has been reached,
1185 // cannot add a user.
1186 if (!isGuest && isUserLimitReachedLocked()) {
1187 return null;
1188 }
1189 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001190 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001191 return null;
1192 }
1193 // Limit number of managed profiles that can be created
1194 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1195 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1196 >= MAX_MANAGED_PROFILES) {
1197 return null;
1198 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001199 int userId = getNextAvailableIdLocked();
1200 userInfo = new UserInfo(userId, name, null, flags);
1201 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1202 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001203 long now = System.currentTimeMillis();
1204 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001205 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001206 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001207 mUsers.put(userId, userInfo);
1208 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001209 if (parent != null) {
1210 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1211 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001212 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001213 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001214 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001215 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001216 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001217 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001218 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001219 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001220 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001221 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001222 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001223 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001224 if (userInfo != null) {
1225 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1226 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1227 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1228 android.Manifest.permission.MANAGE_USERS);
1229 }
1230 } finally {
1231 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001232 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001233 return userInfo;
1234 }
1235
Amith Yamasani95ab7842014-08-11 17:09:26 -07001236 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1237 int count = 0;
1238 for (int i = mUsers.size() - 1; i >= 0; i--) {
1239 UserInfo user = mUsers.valueAt(i);
1240 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1241 if ((user.flags & flags) != 0) {
1242 count++;
1243 }
1244 }
1245 }
1246 return count;
1247 }
1248
Amith Yamasani0b285492011-04-14 17:35:23 -07001249 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001250 * Find the current guest user. If the Guest user is partial,
1251 * then do not include it in the results as it is about to die.
1252 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1253 * the special handling of Guests being removed.
1254 */
1255 private UserInfo findCurrentGuestUserLocked() {
1256 final int size = mUsers.size();
1257 for (int i = 0; i < size; i++) {
1258 final UserInfo user = mUsers.valueAt(i);
1259 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1260 return user;
1261 }
1262 }
1263 return null;
1264 }
1265
1266 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001267 * Mark this guest user for deletion to allow us to create another guest
1268 * and switch to that user before actually removing this guest.
1269 * @param userHandle the userid of the current guest
1270 * @return whether the user could be marked for deletion
1271 */
1272 public boolean markGuestForDeletion(int userHandle) {
1273 checkManageUsersPermission("Only the system can remove users");
1274 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1275 UserManager.DISALLOW_REMOVE_USER, false)) {
1276 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1277 return false;
1278 }
1279
1280 long ident = Binder.clearCallingIdentity();
1281 try {
1282 final UserInfo user;
1283 synchronized (mPackagesLock) {
1284 user = mUsers.get(userHandle);
1285 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1286 return false;
1287 }
1288 if (!user.isGuest()) {
1289 return false;
1290 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001291 // We set this to a guest user that is to be removed. This is a temporary state
1292 // where we are allowed to add new Guest users, even if this one is still not
1293 // removed. This user will still show up in getUserInfo() calls.
1294 // If we don't get around to removing this Guest user, it will be purged on next
1295 // startup.
1296 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001297 // Mark it as disabled, so that it isn't returned any more when
1298 // profiles are queried.
1299 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001300 writeUserLocked(user);
1301 }
1302 } finally {
1303 Binder.restoreCallingIdentity(ident);
1304 }
1305 return true;
1306 }
1307
1308 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001309 * Removes a user and all data directories created for that user. This method should be called
1310 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001311 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001312 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001313 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001314 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001315 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1316 UserManager.DISALLOW_REMOVE_USER, false)) {
1317 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1318 return false;
1319 }
1320
Kenny Guyee58b4f2014-05-23 15:19:53 +01001321 long ident = Binder.clearCallingIdentity();
1322 try {
1323 final UserInfo user;
1324 synchronized (mPackagesLock) {
1325 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001326 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001327 return false;
1328 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001329
1330 // We remember deleted user IDs to prevent them from being
1331 // reused during the current boot; they can still be reused
1332 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001333 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001334
Kenny Guyee58b4f2014-05-23 15:19:53 +01001335 try {
1336 mAppOpsService.removeUser(userHandle);
1337 } catch (RemoteException e) {
1338 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1339 }
1340 // Set this to a partially created user, so that the user will be purged
1341 // on next startup, in case the runtime stops now before stopping and
1342 // removing the user completely.
1343 user.partial = true;
1344 // Mark it as disabled, so that it isn't returned any more when
1345 // profiles are queried.
1346 user.flags |= UserInfo.FLAG_DISABLED;
1347 writeUserLocked(user);
1348 }
1349
1350 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1351 && user.isManagedProfile()) {
1352 // Send broadcast to notify system that the user removed was a
1353 // managed user.
1354 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1355 }
1356
1357 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1358 int res;
1359 try {
1360 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1361 new IStopUserCallback.Stub() {
1362 @Override
1363 public void userStopped(int userId) {
1364 finishRemoveUser(userId);
1365 }
1366 @Override
1367 public void userStopAborted(int userId) {
1368 }
1369 });
1370 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001371 return false;
1372 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001373 return res == ActivityManager.USER_OP_SUCCESS;
1374 } finally {
1375 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001376 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001377 }
1378
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001379 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001380 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001381 // Let other services shutdown any activity and clean up their state before completely
1382 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001383 long ident = Binder.clearCallingIdentity();
1384 try {
1385 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1386 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001387 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1388 android.Manifest.permission.MANAGE_USERS,
1389
1390 new BroadcastReceiver() {
1391 @Override
1392 public void onReceive(Context context, Intent intent) {
1393 if (DBG) {
1394 Slog.i(LOG_TAG,
1395 "USER_REMOVED broadcast sent, cleaning up user data "
1396 + userHandle);
1397 }
1398 new Thread() {
1399 public void run() {
1400 synchronized (mInstallLock) {
1401 synchronized (mPackagesLock) {
1402 removeUserStateLocked(userHandle);
1403 }
1404 }
1405 }
1406 }.start();
1407 }
1408 },
1409
1410 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001411 } finally {
1412 Binder.restoreCallingIdentity(ident);
1413 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001414 }
1415
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001416 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001417 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001418 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001419
1420 // Remove this user from the list
1421 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001422
Amith Yamasani655d0e22013-06-12 14:19:10 -07001423 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001424 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001425 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001426 userFile.delete();
1427 // Update the user list
1428 writeUserListLocked();
1429 updateUserIdsLocked();
1430 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1431 }
1432
Amith Yamasani61f57372012-08-31 12:12:28 -07001433 private void removeDirectoryRecursive(File parent) {
1434 if (parent.isDirectory()) {
1435 String[] files = parent.list();
1436 for (String filename : files) {
1437 File child = new File(parent, filename);
1438 removeDirectoryRecursive(child);
1439 }
1440 }
1441 parent.delete();
1442 }
1443
Kenny Guyf8d3a232014-05-15 16:09:52 +01001444 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001445 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001446 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1447 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001448 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1449 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001450 }
1451
Amith Yamasani2a003292012-08-14 18:25:45 -07001452 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001453 public Bundle getApplicationRestrictions(String packageName) {
1454 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1455 }
1456
1457 @Override
1458 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001459 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001460 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001461 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001462 }
1463 synchronized (mPackagesLock) {
1464 // Read the restrictions from XML
1465 return readApplicationRestrictionsLocked(packageName, userId);
1466 }
1467 }
1468
1469 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001470 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001471 int userId) {
1472 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001473 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001474 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001475 }
1476 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001477 if (restrictions == null || restrictions.isEmpty()) {
1478 cleanAppRestrictionsForPackage(packageName, userId);
1479 } else {
1480 // Write the restrictions to XML
1481 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1482 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001483 }
Robin Lee66e5d962014-04-09 16:44:21 +01001484
Kenny Guyd21b2182014-07-17 16:38:55 +01001485 if (isPackageInstalled(packageName, userId)) {
1486 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1487 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1488 changeIntent.setPackage(packageName);
1489 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1490 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1491 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001492 }
1493
Amith Yamasani655d0e22013-06-12 14:19:10 -07001494 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001495 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001496 checkManageUsersPermission("Only system can modify the restrictions pin");
1497 int userId = UserHandle.getCallingUserId();
1498 synchronized (mPackagesLock) {
1499 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1500 if (pinState == null) {
1501 pinState = new RestrictionsPinState();
1502 }
1503 if (newPin == null) {
1504 pinState.salt = 0;
1505 pinState.pinHash = null;
1506 } else {
1507 try {
1508 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1509 } catch (NoSuchAlgorithmException e) {
1510 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1511 }
1512 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1513 pinState.failedAttempts = 0;
1514 }
1515 mRestrictionsPinStates.put(userId, pinState);
1516 writeUserLocked(mUsers.get(userId));
1517 }
1518 return true;
1519 }
1520
1521 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001522 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001523 checkManageUsersPermission("Only system can verify the restrictions pin");
1524 int userId = UserHandle.getCallingUserId();
1525 synchronized (mPackagesLock) {
1526 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1527 // If there's no pin set, return error code
1528 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1529 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1530 } else if (pin == null) {
1531 // If just checking if user can be prompted, return remaining time
1532 int waitTime = getRemainingTimeForPinAttempt(pinState);
1533 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1534 return waitTime;
1535 } else {
1536 int waitTime = getRemainingTimeForPinAttempt(pinState);
1537 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1538 if (waitTime > 0) {
1539 return waitTime;
1540 }
1541 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1542 pinState.failedAttempts = 0;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001543 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001544 return UserManager.PIN_VERIFICATION_SUCCESS;
1545 } else {
1546 pinState.failedAttempts++;
1547 pinState.lastAttemptTime = System.currentTimeMillis();
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001548 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001549 return waitTime;
1550 }
1551 }
1552 }
1553 }
1554
1555 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1556 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1557 BACKOFF_TIMES.length - 1);
1558 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1559 BACKOFF_TIMES[backoffIndex] : 0;
1560 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1561 0);
1562 }
1563
1564 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001565 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001566 int userId = UserHandle.getCallingUserId();
1567 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001568 return hasRestrictionsPinLocked(userId);
1569 }
1570 }
1571
1572 private boolean hasRestrictionsPinLocked(int userId) {
1573 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1574 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1575 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001576 }
1577 return true;
1578 }
1579
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001580 @Override
1581 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001582 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001583 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001584 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001585 }
1586
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001587 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001588 synchronized (mPackagesLock) {
1589 // Remove all user restrictions
1590 setUserRestrictions(new Bundle(), userHandle);
1591 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001592 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001593 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001594 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001595 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001596 if (unhideApps) {
1597 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001598 }
1599 }
1600
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001601 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001602 mHandler.post(new Runnable() {
1603 @Override
1604 public void run() {
1605 List<ApplicationInfo> apps =
1606 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1607 userHandle).getList();
1608 final long ident = Binder.clearCallingIdentity();
1609 try {
1610 for (ApplicationInfo appInfo : apps) {
1611 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001612 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1613 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001614 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001615 userHandle);
1616 }
1617 }
1618 } finally {
1619 Binder.restoreCallingIdentity(ident);
1620 }
1621 }
1622 });
1623 }
1624
Amith Yamasani655d0e22013-06-12 14:19:10 -07001625 /*
1626 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1627 * Not the most secure, but it is at least a second level of protection. First level is that
1628 * the file is in a location only readable by the system process.
1629 * @param password the password.
1630 * @param salt the randomly generated salt
1631 * @return the hash of the pattern in a String.
1632 */
1633 private String passwordToHash(String password, long salt) {
1634 if (password == null) {
1635 return null;
1636 }
1637 String algo = null;
1638 String hashed = salt + password;
1639 try {
1640 byte[] saltedPassword = (password + salt).getBytes();
1641 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1642 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1643 hashed = toHex(sha1) + toHex(md5);
1644 } catch (NoSuchAlgorithmException e) {
1645 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1646 }
1647 return hashed;
1648 }
1649
1650 private static String toHex(byte[] ary) {
1651 final String hex = "0123456789ABCDEF";
1652 String ret = "";
1653 for (int i = 0; i < ary.length; i++) {
1654 ret += hex.charAt((ary[i] >> 4) & 0xf);
1655 ret += hex.charAt(ary[i] & 0xf);
1656 }
1657 return ret;
1658 }
1659
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001661 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001662 try {
1663 return mContext.getPackageManager().getApplicationInfo(packageName,
1664 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1665 } catch (NameNotFoundException nnfe) {
1666 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001667 } finally {
1668 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001669 }
1670 }
1671
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001672 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001673 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001674 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 final ArrayList<String> values = new ArrayList<String>();
1676
1677 FileInputStream fis = null;
1678 try {
1679 AtomicFile restrictionsFile =
1680 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001681 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001682 fis = restrictionsFile.openRead();
1683 XmlPullParser parser = Xml.newPullParser();
1684 parser.setInput(fis, null);
1685 int type;
1686 while ((type = parser.next()) != XmlPullParser.START_TAG
1687 && type != XmlPullParser.END_DOCUMENT) {
1688 ;
1689 }
1690
1691 if (type != XmlPullParser.START_TAG) {
1692 Slog.e(LOG_TAG, "Unable to read restrictions file "
1693 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001694 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 }
1696
1697 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1698 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1699 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001700 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001701 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1702 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001703 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001704 int count = Integer.parseInt(multiple);
1705 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1706 if (type == XmlPullParser.START_TAG
1707 && parser.getName().equals(TAG_VALUE)) {
1708 values.add(parser.nextText().trim());
1709 count--;
1710 }
1711 }
1712 String [] valueStrings = new String[values.size()];
1713 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001714 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001715 } else {
1716 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001717 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1718 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1719 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1720 restrictions.putInt(key, Integer.parseInt(value));
1721 } else {
1722 restrictions.putString(key, value);
1723 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001724 }
1725 }
1726 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001727 } catch (IOException ioe) {
1728 } catch (XmlPullParserException pe) {
1729 } finally {
1730 if (fis != null) {
1731 try {
1732 fis.close();
1733 } catch (IOException e) {
1734 }
1735 }
1736 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001737 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001738 }
1739
1740 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001741 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001742 FileOutputStream fos = null;
1743 AtomicFile restrictionsFile = new AtomicFile(
1744 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001745 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001746 try {
1747 fos = restrictionsFile.startWrite();
1748 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1749
1750 // XmlSerializer serializer = XmlUtils.serializerInstance();
1751 final XmlSerializer serializer = new FastXmlSerializer();
1752 serializer.setOutput(bos, "utf-8");
1753 serializer.startDocument(null, true);
1754 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1755
1756 serializer.startTag(null, TAG_RESTRICTIONS);
1757
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001758 for (String key : restrictions.keySet()) {
1759 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001760 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001761 serializer.attribute(null, ATTR_KEY, key);
1762
1763 if (value instanceof Boolean) {
1764 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1765 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001766 } else if (value instanceof Integer) {
1767 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1768 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001769 } else if (value == null || value instanceof String) {
1770 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1771 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001772 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001773 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1774 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001775 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001776 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001777 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001778 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001779 serializer.endTag(null, TAG_VALUE);
1780 }
1781 }
1782 serializer.endTag(null, TAG_ENTRY);
1783 }
1784
1785 serializer.endTag(null, TAG_RESTRICTIONS);
1786
1787 serializer.endDocument();
1788 restrictionsFile.finishWrite(fos);
1789 } catch (Exception e) {
1790 restrictionsFile.failWrite(fos);
1791 Slog.e(LOG_TAG, "Error writing application restrictions list");
1792 }
1793 }
1794
1795 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001796 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001797 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001798 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001799 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001800 }
1801 }
1802
1803 @Override
1804 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001805 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001806 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001807 UserInfo info = getUserInfoLocked(userId);
1808 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001809 }
1810 // Not found
1811 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001812 }
1813 }
1814
Amith Yamasani0b285492011-04-14 17:35:23 -07001815 /**
1816 * Caches the list of user ids in an array, adjusting the array size when necessary.
1817 */
Amith Yamasani13593602012-03-22 16:16:17 -07001818 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001819 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001820 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001821 if (!mUsers.valueAt(i).partial) {
1822 num++;
1823 }
1824 }
Amith Yamasani16389312012-10-17 21:20:14 -07001825 final int[] newUsers = new int[num];
1826 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001827 for (int i = 0; i < mUsers.size(); i++) {
1828 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001829 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001830 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001831 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001832 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001833 }
1834
1835 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001836 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001837 * @param userId the user that was just foregrounded
1838 */
1839 public void userForeground(int userId) {
1840 synchronized (mPackagesLock) {
1841 UserInfo user = mUsers.get(userId);
1842 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001843 if (user == null || user.partial) {
1844 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1845 return;
1846 }
1847 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001848 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001849 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001850 }
1851 }
1852 }
1853
1854 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001855 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001856 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1857 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001858 * @return
1859 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001860 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001861 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001862 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001863 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001864 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001865 break;
1866 }
1867 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001868 }
Amith Yamasani195263742012-08-21 15:40:12 -07001869 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001870 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001871 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001872
Amith Yamasanifc95e702013-09-26 13:20:17 -07001873 private String packageToRestrictionsFileName(String packageName) {
1874 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1875 }
1876
1877 private String restrictionsFileNameToPackage(String fileName) {
1878 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1879 (int) (fileName.length() - XML_SUFFIX.length()));
1880 }
1881
Amith Yamasani920ace02012-09-20 22:15:37 -07001882 @Override
1883 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1884 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1885 != PackageManager.PERMISSION_GRANTED) {
1886 pw.println("Permission Denial: can't dump UserManager from from pid="
1887 + Binder.getCallingPid()
1888 + ", uid=" + Binder.getCallingUid()
1889 + " without permission "
1890 + android.Manifest.permission.DUMP);
1891 return;
1892 }
1893
1894 long now = System.currentTimeMillis();
1895 StringBuilder sb = new StringBuilder();
1896 synchronized (mPackagesLock) {
1897 pw.println("Users:");
1898 for (int i = 0; i < mUsers.size(); i++) {
1899 UserInfo user = mUsers.valueAt(i);
1900 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001901 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001902 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001903 if (user.partial) pw.print(" <partial>");
1904 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001905 pw.print(" Created: ");
1906 if (user.creationTime == 0) {
1907 pw.println("<unknown>");
1908 } else {
1909 sb.setLength(0);
1910 TimeUtils.formatDuration(now - user.creationTime, sb);
1911 sb.append(" ago");
1912 pw.println(sb);
1913 }
1914 pw.print(" Last logged in: ");
1915 if (user.lastLoggedInTime == 0) {
1916 pw.println("<unknown>");
1917 } else {
1918 sb.setLength(0);
1919 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1920 sb.append(" ago");
1921 pw.println(sb);
1922 }
1923 }
1924 }
1925 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001926
1927 final class MainHandler extends Handler {
1928
1929 @Override
1930 public void handleMessage(Message msg) {
1931 switch (msg.what) {
1932 case WRITE_USER_MSG:
1933 removeMessages(WRITE_USER_MSG, msg.obj);
1934 synchronized (mPackagesLock) {
1935 int userId = ((UserInfo) msg.obj).id;
1936 UserInfo userInfo = mUsers.get(userId);
1937 if (userInfo != null) {
1938 writeUserLocked(userInfo);
1939 }
1940 }
1941 }
1942 }
1943 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001944}