blob: e6f5e3d0c12eb933ba67767d8648845ba1bfd949 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080032import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.os.Environment;
34import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080035import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080037import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010038import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070039import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Fyodor Kupolov262f9952015-03-23 18:55:11 -070053import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Fyodor Kupolov262f9952015-03-23 18:55:11 -070077import libcore.io.IoUtils;
78
Amith Yamasani258848d2012-08-10 17:06:33 -070079public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani2a003292012-08-14 18:25:45 -070081 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082
Amith Yamasani16389312012-10-17 21:20:14 -070083 private static final boolean DBG = false;
84
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070089 private static final String ATTR_CREATION_TIME = "created";
90 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070091 private static final String ATTR_SALT = "salt";
92 private static final String ATTR_PIN_HASH = "pinHash";
93 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
94 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070095 private static final String ATTR_SERIAL_NO = "serialNumber";
96 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070097 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070098 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070099 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100100 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530101 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800104 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String TAG_ENTRY = "entry";
106 private static final String TAG_VALUE = "value";
107 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
112 private static final String ATTR_TYPE_STRING = "s";
113 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700114 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700115 private static final String ATTR_TYPE_BUNDLE = "B";
116 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700117
Amith Yamasani0b285492011-04-14 17:35:23 -0700118 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700120 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100121 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800123 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700124 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800125
Amith Yamasani634cf312012-10-04 17:34:21 -0700126 private static final int MIN_USER_ID = 10;
127
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700128 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700129
Amith Yamasani920ace02012-09-20 22:15:37 -0700130 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
131
Amith Yamasani655d0e22013-06-12 14:19:10 -0700132 // Number of attempts before jumping to the next BACKOFF_TIMES slot
133 private static final int BACKOFF_INC_INTERVAL = 5;
134
Amith Yamasani95ab7842014-08-11 17:09:26 -0700135 // Maximum number of managed profiles permitted is 1. This cannot be increased
136 // without first making sure that the rest of the framework is prepared for it.
137 private static final int MAX_MANAGED_PROFILES = 1;
138
Amith Yamasani655d0e22013-06-12 14:19:10 -0700139 // Amount of time to force the user to wait before entering the PIN again, after failing
140 // BACKOFF_INC_INTERVAL times.
141 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
142
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800143 static final int WRITE_USER_MSG = 1;
144 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145
Dianne Hackborn4428e172012-08-24 17:43:05 -0700146 private final Context mContext;
147 private final PackageManagerService mPm;
148 private final Object mInstallLock;
149 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151 private final Handler mHandler;
152
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private final File mUsersDir;
154 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700155 private final File mBaseUserPath;
156
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800157 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800158 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800160
Amith Yamasani655d0e22013-06-12 14:19:10 -0700161 class RestrictionsPinState {
162 long salt;
163 String pinHash;
164 int failedAttempts;
165 long lastAttemptTime;
166 }
167
168 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
169 new SparseArray<RestrictionsPinState>();
170
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171 /**
172 * Set of user IDs being actively removed. Removed IDs linger in this set
173 * for several seconds to work around a VFS caching issue.
174 */
175 // @GuardedBy("mPackagesLock")
176 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Amith Yamasani0b285492011-04-14 17:35:23 -0700178 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700179 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700180 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700181
Jason Monk62062992014-05-06 09:55:28 -0400182 private IAppOpsService mAppOpsService;
183
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 public static UserManagerService getInstance() {
187 synchronized (UserManagerService.class) {
188 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
192 /**
193 * Available for testing purposes.
194 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700195 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Called by package manager to create the service. This is closely
201 * associated with the package manager, and the given lock is the
202 * package manager's own lock.
203 */
204 UserManagerService(Context context, PackageManagerService pm,
205 Object installLock, Object packagesLock) {
206 this(context, pm, installLock, packagesLock,
207 Environment.getDataDirectory(),
208 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700209 }
210
Dianne Hackborn4428e172012-08-24 17:43:05 -0700211 /**
212 * Available for testing purposes.
213 */
214 private UserManagerService(Context context, PackageManagerService pm,
215 Object installLock, Object packagesLock,
216 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 mContext = context;
218 mPm = pm;
219 mInstallLock = installLock;
220 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 synchronized (mInstallLock) {
223 synchronized (mPackagesLock) {
224 mUsersDir = new File(dataDir, USER_INFO_DIR);
225 mUsersDir.mkdirs();
226 // Make zeroth user directory, for services to migrate their files to that location
227 File userZeroDir = new File(mUsersDir, "0");
228 userZeroDir.mkdirs();
229 mBaseUserPath = baseUserPath;
230 FileUtils.setPermissions(mUsersDir.toString(),
231 FileUtils.S_IRWXU|FileUtils.S_IRWXG
232 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
233 -1, -1);
234 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800235 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700236 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700237 sInstance = this;
238 }
239 }
240 }
241
242 void systemReady() {
243 synchronized (mInstallLock) {
244 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700245 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700246 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
247 for (int i = 0; i < mUsers.size(); i++) {
248 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700249 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 partials.add(ui);
251 }
252 }
253 for (int i = 0; i < partials.size(); i++) {
254 UserInfo ui = partials.get(i);
255 Slog.w(LOG_TAG, "Removing partially created user #" + i
256 + " (name=" + ui.name + ")");
257 removeUserStateLocked(ui.id);
258 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700259 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700260 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700261 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400262 mAppOpsService = IAppOpsService.Stub.asInterface(
263 ServiceManager.getService(Context.APP_OPS_SERVICE));
264 for (int i = 0; i < mUserIds.length; ++i) {
265 try {
266 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
267 } catch (RemoteException e) {
268 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
269 }
270 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700271 }
272
273 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700274 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700275 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700276 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700277 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
278 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700279 UserInfo ui = mUsers.valueAt(i);
280 if (ui.partial) {
281 continue;
282 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800283 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700284 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700285 }
Amith Yamasani13593602012-03-22 16:16:17 -0700286 }
287 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700288 }
Amith Yamasani13593602012-03-22 16:16:17 -0700289 }
290
Amith Yamasani258848d2012-08-10 17:06:33 -0700291 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100292 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800293 if (userId != UserHandle.getCallingUserId()) {
294 checkManageUsersPermission("getting profiles related to user " + userId);
295 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700296 final long ident = Binder.clearCallingIdentity();
297 try {
298 synchronized (mPackagesLock) {
299 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100300 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 } finally {
302 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000303 }
304 }
305
Amith Yamasanibe465322014-04-24 13:45:17 -0700306 /** Assume permissions already checked and caller's identity cleared */
307 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 UserInfo user = getUserInfoLocked(userId);
309 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700310 if (user == null) {
311 // Probably a dying user
312 return users;
313 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700314 for (int i = 0; i < mUsers.size(); i++) {
315 UserInfo profile = mUsers.valueAt(i);
316 if (!isProfileOf(user, profile)) {
317 continue;
318 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100319 if (enabledOnly && !profile.isEnabled()) {
320 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700321 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700322 if (mRemovingUserIds.get(profile.id)) {
323 continue;
324 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700325 users.add(profile);
326 }
327 return users;
328 }
329
Jessica Hummelbe81c802014-04-22 15:49:22 +0100330 @Override
331 public UserInfo getProfileParent(int userHandle) {
332 checkManageUsersPermission("get the profile parent");
333 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700334 return getProfileParentLocked(userHandle);
335 }
336 }
337
338 private UserInfo getProfileParentLocked(int userHandle) {
339 UserInfo profile = getUserInfoLocked(userHandle);
340 if (profile == null) {
341 return null;
342 }
343 int parentUserId = profile.profileGroupId;
344 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
345 return null;
346 } else {
347 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100348 }
349 }
350
Kenny Guy2a764942014-04-02 13:29:20 +0100351 private boolean isProfileOf(UserInfo user, UserInfo profile) {
352 return user.id == profile.id ||
353 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
354 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000355 }
356
357 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100358 public void setUserEnabled(int userId) {
359 checkManageUsersPermission("enable user");
360 synchronized (mPackagesLock) {
361 UserInfo info = getUserInfoLocked(userId);
362 if (info != null && !info.isEnabled()) {
363 info.flags ^= UserInfo.FLAG_DISABLED;
364 writeUserLocked(info);
365 }
366 }
367 }
368
369 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700370 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700371 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700372 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700373 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700374 }
375 }
376
Amith Yamasani71e6c692013-03-24 17:39:28 -0700377 @Override
378 public boolean isRestricted() {
379 synchronized (mPackagesLock) {
380 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
381 }
382 }
383
Amith Yamasani195263742012-08-21 15:40:12 -0700384 /*
385 * Should be locked on mUsers before calling this.
386 */
387 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700388 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700389 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800390 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700391 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
392 return null;
393 }
394 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700395 }
396
Amith Yamasani13593602012-03-22 16:16:17 -0700397 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700398 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700399 return ArrayUtils.contains(mUserIds, userId);
400 }
401 }
402
Amith Yamasani258848d2012-08-10 17:06:33 -0700403 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700404 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700405 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700406 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700408 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700409 if (info == null || info.partial) {
410 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
411 return;
412 }
Amith Yamasani13593602012-03-22 16:16:17 -0700413 if (name != null && !name.equals(info.name)) {
414 info.name = name;
415 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700417 }
418 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 if (changed) {
420 sendUserInfoChangedBroadcast(userId);
421 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700422 }
423
Amith Yamasani258848d2012-08-10 17:06:33 -0700424 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700425 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700426 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400427 long ident = Binder.clearCallingIdentity();
428 try {
429 synchronized (mPackagesLock) {
430 UserInfo info = mUsers.get(userId);
431 if (info == null || info.partial) {
432 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
433 return;
434 }
435 writeBitmapLocked(info, bitmap);
436 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 }
Jason Monk9a944532014-07-08 09:31:21 -0400438 sendUserInfoChangedBroadcast(userId);
439 } finally {
440 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700441 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700442 }
443
444 private void sendUserInfoChangedBroadcast(int userId) {
445 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
446 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
447 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700448 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700449 }
450
Amith Yamasani258848d2012-08-10 17:06:33 -0700451 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100452 public ParcelFileDescriptor getUserIcon(int userId) {
453 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700454 synchronized (mPackagesLock) {
455 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700456 if (info == null || info.partial) {
457 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
458 return null;
459 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100460 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
461 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
462 || callingGroupId != info.profileGroupId) {
463 checkManageUsersPermission("get the icon of a user who is not related");
464 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 if (info.iconPath == null) {
466 return null;
467 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100468 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700469 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100470
471 try {
472 return ParcelFileDescriptor.open(
473 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
474 } catch (FileNotFoundException e) {
475 Log.e(LOG_TAG, "Couldn't find icon file", e);
476 }
477 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700478 }
479
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700480 public void makeInitialized(int userId) {
481 checkManageUsersPermission("makeInitialized");
482 synchronized (mPackagesLock) {
483 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700484 if (info == null || info.partial) {
485 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
486 }
487 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700488 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800489 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700490 }
491 }
492 }
493
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700494 /**
495 * If default guest restrictions haven't been initialized yet, add the basic
496 * restrictions.
497 */
498 private void initDefaultGuestRestrictions() {
499 if (mGuestRestrictions.isEmpty()) {
500 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800501 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700502 }
503 }
504
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800505 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530506 public Bundle getDefaultGuestRestrictions() {
507 checkManageUsersPermission("getDefaultGuestRestrictions");
508 synchronized (mPackagesLock) {
509 return new Bundle(mGuestRestrictions);
510 }
511 }
512
513 @Override
514 public void setDefaultGuestRestrictions(Bundle restrictions) {
515 checkManageUsersPermission("setDefaultGuestRestrictions");
516 synchronized (mPackagesLock) {
517 mGuestRestrictions.clear();
518 mGuestRestrictions.putAll(restrictions);
519 writeUserListLocked();
520 }
521 }
522
523 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700524 public boolean hasUserRestriction(String restrictionKey, int userId) {
525 synchronized (mPackagesLock) {
526 Bundle restrictions = mUserRestrictions.get(userId);
527 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
528 }
529 }
530
531 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800532 public Bundle getUserRestrictions(int userId) {
533 // checkManageUsersPermission("getUserRestrictions");
534
535 synchronized (mPackagesLock) {
536 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700537 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800538 }
539 }
540
541 @Override
542 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700543 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700544 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800545
546 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700547 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800548 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400549 long token = Binder.clearCallingIdentity();
550 try {
551 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
552 } catch (RemoteException e) {
553 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
554 } finally {
555 Binder.restoreCallingIdentity(token);
556 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800557 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800558 }
559 }
560
Amith Yamasani258848d2012-08-10 17:06:33 -0700561 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700562 * Check if we've hit the limit of how many users can be created.
563 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700564 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700565 int aliveUserCount = 0;
566 final int totalUserCount = mUsers.size();
567 // Skip over users being removed
568 for (int i = 0; i < totalUserCount; i++) {
569 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700570 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700571 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700572 aliveUserCount++;
573 }
574 }
575 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700576 }
577
578 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700579 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700580 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700581 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700582 *
583 * @param message used as message if SecurityException is thrown
584 * @throws SecurityException if the caller is not system or root
585 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700586 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700587 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700588 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400589 && ActivityManager.checkComponentPermission(
590 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700591 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
592 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
593 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400594 }
595
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700596 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 try {
598 File dir = new File(mUsersDir, Integer.toString(info.id));
599 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100600 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700601 if (!dir.exists()) {
602 dir.mkdir();
603 FileUtils.setPermissions(
604 dir.getPath(),
605 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
606 -1, -1);
607 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700608 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100609 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
610 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700611 info.iconPath = file.getAbsolutePath();
612 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700613 try {
614 os.close();
615 } catch (IOException ioe) {
616 // What the ... !
617 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100618 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700619 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700620 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700621 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700622 }
623
Amith Yamasani0b285492011-04-14 17:35:23 -0700624 /**
625 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
626 * cache it elsewhere.
627 * @return the array of user ids.
628 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700629 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700630 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700631 return mUserIds;
632 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700633 }
634
Dianne Hackborn4428e172012-08-24 17:43:05 -0700635 int[] getUserIdsLPr() {
636 return mUserIds;
637 }
638
Amith Yamasani13593602012-03-22 16:16:17 -0700639 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700641 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700642 return;
643 }
644 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700645 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700646 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700647 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700648 XmlPullParser parser = Xml.newPullParser();
649 parser.setInput(fis, null);
650 int type;
651 while ((type = parser.next()) != XmlPullParser.START_TAG
652 && type != XmlPullParser.END_DOCUMENT) {
653 ;
654 }
655
656 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700657 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700658 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700659 return;
660 }
661
Amith Yamasani2a003292012-08-14 18:25:45 -0700662 mNextSerialNumber = -1;
663 if (parser.getName().equals(TAG_USERS)) {
664 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
665 if (lastSerialNumber != null) {
666 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
667 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700668 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
669 if (versionNumber != null) {
670 mUserVersion = Integer.parseInt(versionNumber);
671 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700672 }
673
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700674 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530675 if (type == XmlPullParser.START_TAG) {
676 final String name = parser.getName();
677 if (name.equals(TAG_USER)) {
678 String id = parser.getAttributeValue(null, ATTR_ID);
679 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700680
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530681 if (user != null) {
682 mUsers.put(user.id, user);
683 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
684 mNextSerialNumber = user.id + 1;
685 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700686 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530687 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800688 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
689 && type != XmlPullParser.END_TAG) {
690 if (type == XmlPullParser.START_TAG) {
691 if (parser.getName().equals(TAG_RESTRICTIONS)) {
692 readRestrictionsLocked(parser, mGuestRestrictions);
693 }
694 break;
695 }
696 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700697 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 }
699 }
Amith Yamasani13593602012-03-22 16:16:17 -0700700 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700701 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700702 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700703 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700704 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700705 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800706 } finally {
707 if (fis != null) {
708 try {
709 fis.close();
710 } catch (IOException e) {
711 }
712 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700713 }
714 }
715
Amith Yamasani6f34b412012-10-22 18:19:27 -0700716 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800717 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700718 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700719 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700720 int userVersion = mUserVersion;
721 if (userVersion < 1) {
722 // Assign a proper name for the owner, if not initialized correctly before
723 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
724 if ("Primary".equals(user.name)) {
725 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800726 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700727 }
728 userVersion = 1;
729 }
730
Amith Yamasanibc9625052012-11-15 14:39:18 -0800731 if (userVersion < 2) {
732 // Owner should be marked as initialized
733 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
734 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
735 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800736 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800737 }
738 userVersion = 2;
739 }
740
Amith Yamasani350962c2013-08-06 11:18:53 -0700741
Amith Yamasani5e486f52013-08-07 11:06:44 -0700742 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700743 userVersion = 4;
744 }
745
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700746 if (userVersion < 5) {
747 initDefaultGuestRestrictions();
748 userVersion = 5;
749 }
750
Amith Yamasani6f34b412012-10-22 18:19:27 -0700751 if (userVersion < USER_VERSION) {
752 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
753 + USER_VERSION);
754 } else {
755 mUserVersion = userVersion;
756 writeUserListLocked();
757 }
758 }
759
Amith Yamasani13593602012-03-22 16:16:17 -0700760 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700761 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800762 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700763 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700764 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700766 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400767 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800768
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500769 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800770 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
771
Amith Yamasani13593602012-03-22 16:16:17 -0700772 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700773 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774
Amith Yamasani13593602012-03-22 16:16:17 -0700775 writeUserListLocked();
776 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700777 }
778
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800779 private void scheduleWriteUserLocked(UserInfo userInfo) {
780 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
781 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
782 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
783 }
784 }
785
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 /*
787 * Writes the user file in this format:
788 *
789 * <user flags="20039023" id="0">
790 * <name>Primary</name>
791 * </user>
792 */
Amith Yamasani13593602012-03-22 16:16:17 -0700793 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700794 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700795 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700796 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 final BufferedOutputStream bos = new BufferedOutputStream(fos);
799
800 // XmlSerializer serializer = XmlUtils.serializerInstance();
801 final XmlSerializer serializer = new FastXmlSerializer();
802 serializer.setOutput(bos, "utf-8");
803 serializer.startDocument(null, true);
804 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
805
806 serializer.startTag(null, TAG_USER);
807 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700808 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700809 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700810 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
811 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
812 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700813 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
814 if (pinState != null) {
815 if (pinState.salt != 0) {
816 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
817 }
818 if (pinState.pinHash != null) {
819 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
820 }
821 if (pinState.failedAttempts != 0) {
822 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
823 Integer.toString(pinState.failedAttempts));
824 serializer.attribute(null, ATTR_LAST_RETRY_MS,
825 Long.toString(pinState.lastAttemptTime));
826 }
827 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700828 if (userInfo.iconPath != null) {
829 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
830 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700831 if (userInfo.partial) {
832 serializer.attribute(null, ATTR_PARTIAL, "true");
833 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700834 if (userInfo.guestToRemove) {
835 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
836 }
Kenny Guy2a764942014-04-02 13:29:20 +0100837 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
838 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
839 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000840 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841
842 serializer.startTag(null, TAG_NAME);
843 serializer.text(userInfo.name);
844 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800845 Bundle restrictions = mUserRestrictions.get(userInfo.id);
846 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530847 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800848 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700849 serializer.endTag(null, TAG_USER);
850
851 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700852 userFile.finishWrite(fos);
853 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700854 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700855 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700856 }
857 }
858
859 /*
860 * Writes the user list file in this format:
861 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700862 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700863 * <user id="0"></user>
864 * <user id="2"></user>
865 * </users>
866 */
Amith Yamasani13593602012-03-22 16:16:17 -0700867 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700868 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700869 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700870 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700871 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700872 final BufferedOutputStream bos = new BufferedOutputStream(fos);
873
874 // XmlSerializer serializer = XmlUtils.serializerInstance();
875 final XmlSerializer serializer = new FastXmlSerializer();
876 serializer.setOutput(bos, "utf-8");
877 serializer.startDocument(null, true);
878 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
879
880 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700881 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700882 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700883
Adam Lesinskieddeb492014-09-08 17:50:03 -0700884 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530885 writeRestrictionsLocked(serializer, mGuestRestrictions);
886 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700887 for (int i = 0; i < mUsers.size(); i++) {
888 UserInfo user = mUsers.valueAt(i);
889 serializer.startTag(null, TAG_USER);
890 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
891 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700892 }
893
894 serializer.endTag(null, TAG_USERS);
895
896 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700897 userListFile.finishWrite(fos);
898 } catch (Exception e) {
899 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700900 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700901 }
902 }
903
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530904 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
905 throws IOException {
906 serializer.startTag(null, TAG_RESTRICTIONS);
907 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
908 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
909 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
910 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
911 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
912 writeBoolean(serializer, restrictions,
913 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
914 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
915 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
922 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
923 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
929 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700930 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
931 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400932 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700933 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
934 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000935 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000936 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530937 serializer.endTag(null, TAG_RESTRICTIONS);
938 }
939
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800940 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700941 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700942 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700943 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700944 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700945 long creationTime = 0L;
946 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700947 long salt = 0L;
948 String pinHash = null;
949 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100950 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700951 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700953 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800954 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700955
956 FileInputStream fis = null;
957 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700958 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700959 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700960 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700961 XmlPullParser parser = Xml.newPullParser();
962 parser.setInput(fis, null);
963 int type;
964 while ((type = parser.next()) != XmlPullParser.START_TAG
965 && type != XmlPullParser.END_DOCUMENT) {
966 ;
967 }
968
969 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700970 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700971 return null;
972 }
973
974 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700975 int storedId = readIntAttribute(parser, ATTR_ID, -1);
976 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700977 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700978 return null;
979 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700980 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
981 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700982 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700983 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
984 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700985 salt = readLongAttribute(parser, ATTR_SALT, 0L);
986 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
987 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
988 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100989 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
990 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700991 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
992 if ("true".equals(valueString)) {
993 partial = true;
994 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700995 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
996 if ("true".equals(valueString)) {
997 guestToRemove = true;
998 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700999
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001000 int outerDepth = parser.getDepth();
1001 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1002 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1003 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1004 continue;
1005 }
1006 String tag = parser.getName();
1007 if (TAG_NAME.equals(tag)) {
1008 type = parser.next();
1009 if (type == XmlPullParser.TEXT) {
1010 name = parser.getText();
1011 }
1012 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301013 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001014 }
1015 }
1016 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001017
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001018 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001019 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001020 userInfo.creationTime = creationTime;
1021 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001022 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001023 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001024 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001025 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -07001026 if (salt != 0L) {
1027 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1028 if (pinState == null) {
1029 pinState = new RestrictionsPinState();
1030 mRestrictionsPinStates.put(id, pinState);
1031 }
1032 pinState.salt = salt;
1033 pinState.pinHash = pinHash;
1034 pinState.failedAttempts = failedAttempts;
1035 pinState.lastAttemptTime = lastAttemptTime;
1036 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001037 return userInfo;
1038
1039 } catch (IOException ioe) {
1040 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001041 } finally {
1042 if (fis != null) {
1043 try {
1044 fis.close();
1045 } catch (IOException e) {
1046 }
1047 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001048 }
1049 return null;
1050 }
1051
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301052 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1053 throws IOException {
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1059 readBoolean(parser, restrictions,
1060 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1061 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1065 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1066 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1068 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1069 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1070 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1071 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1072 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1073 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1074 readBoolean(parser, restrictions,
1075 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1076 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1077 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001078 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1079 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001080 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001081 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1082 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001083 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001084 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301085 }
1086
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001087 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1088 String restrictionKey) {
1089 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001090 if (value != null) {
1091 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1092 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001093 }
1094
1095 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1096 throws IOException {
1097 if (restrictions.containsKey(restrictionKey)) {
1098 xml.attribute(null, restrictionKey,
1099 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1100 }
1101 }
1102
Amith Yamasani920ace02012-09-20 22:15:37 -07001103 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1104 String valueString = parser.getAttributeValue(null, attr);
1105 if (valueString == null) return defaultValue;
1106 try {
1107 return Integer.parseInt(valueString);
1108 } catch (NumberFormatException nfe) {
1109 return defaultValue;
1110 }
1111 }
1112
1113 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1114 String valueString = parser.getAttributeValue(null, attr);
1115 if (valueString == null) return defaultValue;
1116 try {
1117 return Long.parseLong(valueString);
1118 } catch (NumberFormatException nfe) {
1119 return defaultValue;
1120 }
1121 }
1122
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001123 private boolean isPackageInstalled(String pkg, int userId) {
1124 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1125 PackageManager.GET_UNINSTALLED_PACKAGES,
1126 userId);
1127 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1128 return false;
1129 }
1130 return true;
1131 }
1132
Amith Yamasanib82add22013-07-09 11:24:44 -07001133 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001134 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001135 * Does not do any permissions checking.
1136 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001137 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001138 synchronized (mPackagesLock) {
1139 File dir = Environment.getUserSystemDirectory(userId);
1140 String[] files = dir.list();
1141 if (files == null) return;
1142 for (String fileName : files) {
1143 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1144 File resFile = new File(dir, fileName);
1145 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001146 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001147 }
1148 }
1149 }
1150 }
1151 }
1152
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001153 /**
1154 * Removes the app restrictions file for a specific package and user id, if it exists.
1155 */
1156 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1157 synchronized (mPackagesLock) {
1158 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001159 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001160 if (resFile.exists()) {
1161 resFile.delete();
1162 }
1163 }
1164 }
1165
Kenny Guya52dc3e2014-02-11 15:33:14 +00001166 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001167 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001168 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001169 if (userId != UserHandle.USER_OWNER) {
1170 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001171 return null;
1172 }
Kenny Guy2a764942014-04-02 13:29:20 +01001173 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001174 }
1175
Amith Yamasani258848d2012-08-10 17:06:33 -07001176 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001177 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001178 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001179 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001180 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001181
Jessica Hummelbe81c802014-04-22 15:49:22 +01001182 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001183 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1184 UserManager.DISALLOW_ADD_USER, false)) {
1185 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1186 return null;
1187 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001188 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001189 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001190 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001191 try {
1192 synchronized (mInstallLock) {
1193 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001194 UserInfo parent = null;
1195 if (parentId != UserHandle.USER_NULL) {
1196 parent = getUserInfoLocked(parentId);
1197 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001198 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001199 // If we're not adding a guest user and the limit has been reached,
1200 // cannot add a user.
1201 if (!isGuest && isUserLimitReachedLocked()) {
1202 return null;
1203 }
1204 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001205 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001206 return null;
1207 }
1208 // Limit number of managed profiles that can be created
1209 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1210 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1211 >= MAX_MANAGED_PROFILES) {
1212 return null;
1213 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001214 int userId = getNextAvailableIdLocked();
1215 userInfo = new UserInfo(userId, name, null, flags);
1216 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1217 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001218 long now = System.currentTimeMillis();
1219 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001220 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001221 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001222 mUsers.put(userId, userInfo);
1223 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001224 if (parent != null) {
1225 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1226 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001227 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001228 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001229 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001230 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001231 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001232 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001233 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001234 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001235 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001236 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001237 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001238 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001239 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001240 if (userInfo != null) {
1241 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1242 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1243 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1244 android.Manifest.permission.MANAGE_USERS);
1245 }
1246 } finally {
1247 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001248 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001249 return userInfo;
1250 }
1251
Amith Yamasani95ab7842014-08-11 17:09:26 -07001252 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1253 int count = 0;
1254 for (int i = mUsers.size() - 1; i >= 0; i--) {
1255 UserInfo user = mUsers.valueAt(i);
1256 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1257 if ((user.flags & flags) != 0) {
1258 count++;
1259 }
1260 }
1261 }
1262 return count;
1263 }
1264
Amith Yamasani0b285492011-04-14 17:35:23 -07001265 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001266 * Find the current guest user. If the Guest user is partial,
1267 * then do not include it in the results as it is about to die.
1268 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1269 * the special handling of Guests being removed.
1270 */
1271 private UserInfo findCurrentGuestUserLocked() {
1272 final int size = mUsers.size();
1273 for (int i = 0; i < size; i++) {
1274 final UserInfo user = mUsers.valueAt(i);
1275 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1276 return user;
1277 }
1278 }
1279 return null;
1280 }
1281
1282 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001283 * Mark this guest user for deletion to allow us to create another guest
1284 * and switch to that user before actually removing this guest.
1285 * @param userHandle the userid of the current guest
1286 * @return whether the user could be marked for deletion
1287 */
1288 public boolean markGuestForDeletion(int userHandle) {
1289 checkManageUsersPermission("Only the system can remove users");
1290 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1291 UserManager.DISALLOW_REMOVE_USER, false)) {
1292 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1293 return false;
1294 }
1295
1296 long ident = Binder.clearCallingIdentity();
1297 try {
1298 final UserInfo user;
1299 synchronized (mPackagesLock) {
1300 user = mUsers.get(userHandle);
1301 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1302 return false;
1303 }
1304 if (!user.isGuest()) {
1305 return false;
1306 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001307 // We set this to a guest user that is to be removed. This is a temporary state
1308 // where we are allowed to add new Guest users, even if this one is still not
1309 // removed. This user will still show up in getUserInfo() calls.
1310 // If we don't get around to removing this Guest user, it will be purged on next
1311 // startup.
1312 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001313 // Mark it as disabled, so that it isn't returned any more when
1314 // profiles are queried.
1315 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001316 writeUserLocked(user);
1317 }
1318 } finally {
1319 Binder.restoreCallingIdentity(ident);
1320 }
1321 return true;
1322 }
1323
1324 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001325 * Removes a user and all data directories created for that user. This method should be called
1326 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001327 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001328 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001329 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001330 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001331 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1332 UserManager.DISALLOW_REMOVE_USER, false)) {
1333 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1334 return false;
1335 }
1336
Kenny Guyee58b4f2014-05-23 15:19:53 +01001337 long ident = Binder.clearCallingIdentity();
1338 try {
1339 final UserInfo user;
1340 synchronized (mPackagesLock) {
1341 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001342 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001343 return false;
1344 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001345
1346 // We remember deleted user IDs to prevent them from being
1347 // reused during the current boot; they can still be reused
1348 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001349 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001350
Kenny Guyee58b4f2014-05-23 15:19:53 +01001351 try {
1352 mAppOpsService.removeUser(userHandle);
1353 } catch (RemoteException e) {
1354 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1355 }
1356 // Set this to a partially created user, so that the user will be purged
1357 // on next startup, in case the runtime stops now before stopping and
1358 // removing the user completely.
1359 user.partial = true;
1360 // Mark it as disabled, so that it isn't returned any more when
1361 // profiles are queried.
1362 user.flags |= UserInfo.FLAG_DISABLED;
1363 writeUserLocked(user);
1364 }
1365
1366 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1367 && user.isManagedProfile()) {
1368 // Send broadcast to notify system that the user removed was a
1369 // managed user.
1370 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1371 }
1372
1373 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1374 int res;
1375 try {
1376 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1377 new IStopUserCallback.Stub() {
1378 @Override
1379 public void userStopped(int userId) {
1380 finishRemoveUser(userId);
1381 }
1382 @Override
1383 public void userStopAborted(int userId) {
1384 }
1385 });
1386 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001387 return false;
1388 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001389 return res == ActivityManager.USER_OP_SUCCESS;
1390 } finally {
1391 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001392 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001393 }
1394
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001395 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001396 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001397 // Let other services shutdown any activity and clean up their state before completely
1398 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001399 long ident = Binder.clearCallingIdentity();
1400 try {
1401 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1402 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001403 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1404 android.Manifest.permission.MANAGE_USERS,
1405
1406 new BroadcastReceiver() {
1407 @Override
1408 public void onReceive(Context context, Intent intent) {
1409 if (DBG) {
1410 Slog.i(LOG_TAG,
1411 "USER_REMOVED broadcast sent, cleaning up user data "
1412 + userHandle);
1413 }
1414 new Thread() {
1415 public void run() {
1416 synchronized (mInstallLock) {
1417 synchronized (mPackagesLock) {
1418 removeUserStateLocked(userHandle);
1419 }
1420 }
1421 }
1422 }.start();
1423 }
1424 },
1425
1426 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001427 } finally {
1428 Binder.restoreCallingIdentity(ident);
1429 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001430 }
1431
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001432 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001433 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001434 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001435
1436 // Remove this user from the list
1437 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001438
Amith Yamasani655d0e22013-06-12 14:19:10 -07001439 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001440 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001441 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001442 userFile.delete();
1443 // Update the user list
1444 writeUserListLocked();
1445 updateUserIdsLocked();
1446 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1447 }
1448
Amith Yamasani61f57372012-08-31 12:12:28 -07001449 private void removeDirectoryRecursive(File parent) {
1450 if (parent.isDirectory()) {
1451 String[] files = parent.list();
1452 for (String filename : files) {
1453 File child = new File(parent, filename);
1454 removeDirectoryRecursive(child);
1455 }
1456 }
1457 parent.delete();
1458 }
1459
Kenny Guyf8d3a232014-05-15 16:09:52 +01001460 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001461 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001462 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1463 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001464 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1465 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001466 }
1467
Amith Yamasani2a003292012-08-14 18:25:45 -07001468 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001469 public Bundle getApplicationRestrictions(String packageName) {
1470 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1471 }
1472
1473 @Override
1474 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001475 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001476 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001477 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001478 }
1479 synchronized (mPackagesLock) {
1480 // Read the restrictions from XML
1481 return readApplicationRestrictionsLocked(packageName, userId);
1482 }
1483 }
1484
1485 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001486 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001487 int userId) {
1488 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001489 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001490 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001491 }
1492 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001493 if (restrictions == null || restrictions.isEmpty()) {
1494 cleanAppRestrictionsForPackage(packageName, userId);
1495 } else {
1496 // Write the restrictions to XML
1497 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1498 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001499 }
Robin Lee66e5d962014-04-09 16:44:21 +01001500
Kenny Guyd21b2182014-07-17 16:38:55 +01001501 if (isPackageInstalled(packageName, userId)) {
1502 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1503 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1504 changeIntent.setPackage(packageName);
1505 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1506 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1507 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001508 }
1509
Amith Yamasani655d0e22013-06-12 14:19:10 -07001510 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001511 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001512 checkManageUsersPermission("Only system can modify the restrictions pin");
1513 int userId = UserHandle.getCallingUserId();
1514 synchronized (mPackagesLock) {
1515 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1516 if (pinState == null) {
1517 pinState = new RestrictionsPinState();
1518 }
1519 if (newPin == null) {
1520 pinState.salt = 0;
1521 pinState.pinHash = null;
1522 } else {
1523 try {
1524 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1525 } catch (NoSuchAlgorithmException e) {
1526 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1527 }
1528 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1529 pinState.failedAttempts = 0;
1530 }
1531 mRestrictionsPinStates.put(userId, pinState);
1532 writeUserLocked(mUsers.get(userId));
1533 }
1534 return true;
1535 }
1536
1537 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001538 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001539 checkManageUsersPermission("Only system can verify the restrictions pin");
1540 int userId = UserHandle.getCallingUserId();
1541 synchronized (mPackagesLock) {
1542 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1543 // If there's no pin set, return error code
1544 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1545 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1546 } else if (pin == null) {
1547 // If just checking if user can be prompted, return remaining time
1548 int waitTime = getRemainingTimeForPinAttempt(pinState);
1549 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1550 return waitTime;
1551 } else {
1552 int waitTime = getRemainingTimeForPinAttempt(pinState);
1553 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1554 if (waitTime > 0) {
1555 return waitTime;
1556 }
1557 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1558 pinState.failedAttempts = 0;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001559 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001560 return UserManager.PIN_VERIFICATION_SUCCESS;
1561 } else {
1562 pinState.failedAttempts++;
1563 pinState.lastAttemptTime = System.currentTimeMillis();
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001564 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001565 return waitTime;
1566 }
1567 }
1568 }
1569 }
1570
1571 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1572 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1573 BACKOFF_TIMES.length - 1);
1574 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1575 BACKOFF_TIMES[backoffIndex] : 0;
1576 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1577 0);
1578 }
1579
1580 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001581 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001582 int userId = UserHandle.getCallingUserId();
1583 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001584 return hasRestrictionsPinLocked(userId);
1585 }
1586 }
1587
1588 private boolean hasRestrictionsPinLocked(int userId) {
1589 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1590 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1591 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001592 }
1593 return true;
1594 }
1595
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001596 @Override
1597 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001598 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001599 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001600 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001601 }
1602
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001603 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001604 synchronized (mPackagesLock) {
1605 // Remove all user restrictions
1606 setUserRestrictions(new Bundle(), userHandle);
1607 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001608 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001609 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001610 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001611 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001612 if (unhideApps) {
1613 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001614 }
1615 }
1616
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001617 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001618 mHandler.post(new Runnable() {
1619 @Override
1620 public void run() {
1621 List<ApplicationInfo> apps =
1622 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1623 userHandle).getList();
1624 final long ident = Binder.clearCallingIdentity();
1625 try {
1626 for (ApplicationInfo appInfo : apps) {
1627 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001628 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1629 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001630 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001631 userHandle);
1632 }
1633 }
1634 } finally {
1635 Binder.restoreCallingIdentity(ident);
1636 }
1637 }
1638 });
1639 }
1640
Amith Yamasani655d0e22013-06-12 14:19:10 -07001641 /*
1642 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1643 * Not the most secure, but it is at least a second level of protection. First level is that
1644 * the file is in a location only readable by the system process.
1645 * @param password the password.
1646 * @param salt the randomly generated salt
1647 * @return the hash of the pattern in a String.
1648 */
1649 private String passwordToHash(String password, long salt) {
1650 if (password == null) {
1651 return null;
1652 }
1653 String algo = null;
1654 String hashed = salt + password;
1655 try {
1656 byte[] saltedPassword = (password + salt).getBytes();
1657 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1658 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1659 hashed = toHex(sha1) + toHex(md5);
1660 } catch (NoSuchAlgorithmException e) {
1661 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1662 }
1663 return hashed;
1664 }
1665
1666 private static String toHex(byte[] ary) {
1667 final String hex = "0123456789ABCDEF";
1668 String ret = "";
1669 for (int i = 0; i < ary.length; i++) {
1670 ret += hex.charAt((ary[i] >> 4) & 0xf);
1671 ret += hex.charAt(ary[i] & 0xf);
1672 }
1673 return ret;
1674 }
1675
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001676 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001677 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001678 try {
1679 return mContext.getPackageManager().getApplicationInfo(packageName,
1680 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1681 } catch (NameNotFoundException nnfe) {
1682 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001683 } finally {
1684 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001685 }
1686 }
1687
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001688 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001689 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001690 AtomicFile restrictionsFile =
1691 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1692 packageToRestrictionsFileName(packageName)));
1693 return readApplicationRestrictionsLocked(restrictionsFile);
1694 }
1695
1696 @VisibleForTesting
1697 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001698 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001699 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001700 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001701 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001702 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001703
1704 FileInputStream fis = null;
1705 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001706 fis = restrictionsFile.openRead();
1707 XmlPullParser parser = Xml.newPullParser();
1708 parser.setInput(fis, null);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001709 XmlUtils.nextElement(parser);
1710 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001711 Slog.e(LOG_TAG, "Unable to read restrictions file "
1712 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001713 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001714 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001715 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1716 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001717 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001718 } catch (IOException|XmlPullParserException e) {
1719 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001720 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001721 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001722 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001723 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001724 }
1725
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001726 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1727 XmlPullParser parser) throws XmlPullParserException, IOException {
1728 int type = parser.getEventType();
1729 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1730 String key = parser.getAttributeValue(null, ATTR_KEY);
1731 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1732 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1733 if (multiple != null) {
1734 values.clear();
1735 int count = Integer.parseInt(multiple);
1736 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1737 if (type == XmlPullParser.START_TAG
1738 && parser.getName().equals(TAG_VALUE)) {
1739 values.add(parser.nextText().trim());
1740 count--;
1741 }
1742 }
1743 String [] valueStrings = new String[values.size()];
1744 values.toArray(valueStrings);
1745 restrictions.putStringArray(key, valueStrings);
1746 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1747 restrictions.putBundle(key, readBundleEntry(parser, values));
1748 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1749 final int outerDepth = parser.getDepth();
1750 ArrayList<Bundle> bundleList = new ArrayList<>();
1751 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1752 Bundle childBundle = readBundleEntry(parser, values);
1753 bundleList.add(childBundle);
1754 }
1755 restrictions.putParcelableArray(key,
1756 bundleList.toArray(new Bundle[bundleList.size()]));
1757 } else {
1758 String value = parser.nextText().trim();
1759 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1760 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1761 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1762 restrictions.putInt(key, Integer.parseInt(value));
1763 } else {
1764 restrictions.putString(key, value);
1765 }
1766 }
1767 }
1768 }
1769
1770 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1771 throws IOException, XmlPullParserException {
1772 Bundle childBundle = new Bundle();
1773 final int outerDepth = parser.getDepth();
1774 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1775 readEntry(childBundle, values, parser);
1776 }
1777 return childBundle;
1778 }
1779
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001780 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001781 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001782 AtomicFile restrictionsFile = new AtomicFile(
1783 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001784 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001785 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1786 }
1787
1788 @VisibleForTesting
1789 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1790 AtomicFile restrictionsFile) {
1791 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001792 try {
1793 fos = restrictionsFile.startWrite();
1794 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1795
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001796 final XmlSerializer serializer = new FastXmlSerializer();
1797 serializer.setOutput(bos, "utf-8");
1798 serializer.startDocument(null, true);
1799 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1800
1801 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001802 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001803 serializer.endTag(null, TAG_RESTRICTIONS);
1804
1805 serializer.endDocument();
1806 restrictionsFile.finishWrite(fos);
1807 } catch (Exception e) {
1808 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001809 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1810 }
1811 }
1812
1813 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1814 throws IOException {
1815 for (String key : restrictions.keySet()) {
1816 Object value = restrictions.get(key);
1817 serializer.startTag(null, TAG_ENTRY);
1818 serializer.attribute(null, ATTR_KEY, key);
1819
1820 if (value instanceof Boolean) {
1821 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1822 serializer.text(value.toString());
1823 } else if (value instanceof Integer) {
1824 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1825 serializer.text(value.toString());
1826 } else if (value == null || value instanceof String) {
1827 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1828 serializer.text(value != null ? (String) value : "");
1829 } else if (value instanceof Bundle) {
1830 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1831 writeBundle((Bundle) value, serializer);
1832 } else if (value instanceof Parcelable[]) {
1833 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1834 Parcelable[] array = (Parcelable[]) value;
1835 for (Parcelable parcelable : array) {
1836 if (!(parcelable instanceof Bundle)) {
1837 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1838 }
1839 serializer.startTag(null, TAG_ENTRY);
1840 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1841 writeBundle((Bundle) parcelable, serializer);
1842 serializer.endTag(null, TAG_ENTRY);
1843 }
1844 } else {
1845 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1846 String[] values = (String[]) value;
1847 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1848 for (String choice : values) {
1849 serializer.startTag(null, TAG_VALUE);
1850 serializer.text(choice != null ? choice : "");
1851 serializer.endTag(null, TAG_VALUE);
1852 }
1853 }
1854 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001855 }
1856 }
1857
1858 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001859 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001860 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001861 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001862 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001863 }
1864 }
1865
1866 @Override
1867 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001868 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001869 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001870 UserInfo info = getUserInfoLocked(userId);
1871 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001872 }
1873 // Not found
1874 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001875 }
1876 }
1877
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001878 @Override
1879 public long getUserCreationTime(int userHandle) {
1880 int callingUserId = UserHandle.getCallingUserId();
1881 UserInfo userInfo = null;
1882 synchronized (mPackagesLock) {
1883 if (callingUserId == userHandle) {
1884 userInfo = getUserInfoLocked(userHandle);
1885 } else {
1886 UserInfo parent = getProfileParentLocked(userHandle);
1887 if (parent != null && parent.id == callingUserId) {
1888 userInfo = getUserInfoLocked(userHandle);
1889 }
1890 }
1891 }
1892 if (userInfo == null) {
1893 throw new SecurityException("userHandle can only be the calling user or a managed "
1894 + "profile associated with this user");
1895 }
1896 return userInfo.creationTime;
1897 }
1898
Amith Yamasani0b285492011-04-14 17:35:23 -07001899 /**
1900 * Caches the list of user ids in an array, adjusting the array size when necessary.
1901 */
Amith Yamasani13593602012-03-22 16:16:17 -07001902 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001903 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001904 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001905 if (!mUsers.valueAt(i).partial) {
1906 num++;
1907 }
1908 }
Amith Yamasani16389312012-10-17 21:20:14 -07001909 final int[] newUsers = new int[num];
1910 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001911 for (int i = 0; i < mUsers.size(); i++) {
1912 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001913 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001914 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001915 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001916 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001917 }
1918
1919 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001920 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001921 * @param userId the user that was just foregrounded
1922 */
1923 public void userForeground(int userId) {
1924 synchronized (mPackagesLock) {
1925 UserInfo user = mUsers.get(userId);
1926 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001927 if (user == null || user.partial) {
1928 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1929 return;
1930 }
1931 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001932 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001933 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001934 }
1935 }
1936 }
1937
1938 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001939 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001940 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1941 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001942 * @return
1943 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001944 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001945 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001946 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001947 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001948 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001949 break;
1950 }
1951 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 }
Amith Yamasani195263742012-08-21 15:40:12 -07001953 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001955 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001956
Amith Yamasanifc95e702013-09-26 13:20:17 -07001957 private String packageToRestrictionsFileName(String packageName) {
1958 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1959 }
1960
1961 private String restrictionsFileNameToPackage(String fileName) {
1962 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1963 (int) (fileName.length() - XML_SUFFIX.length()));
1964 }
1965
Amith Yamasani920ace02012-09-20 22:15:37 -07001966 @Override
1967 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1968 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1969 != PackageManager.PERMISSION_GRANTED) {
1970 pw.println("Permission Denial: can't dump UserManager from from pid="
1971 + Binder.getCallingPid()
1972 + ", uid=" + Binder.getCallingUid()
1973 + " without permission "
1974 + android.Manifest.permission.DUMP);
1975 return;
1976 }
1977
1978 long now = System.currentTimeMillis();
1979 StringBuilder sb = new StringBuilder();
1980 synchronized (mPackagesLock) {
1981 pw.println("Users:");
1982 for (int i = 0; i < mUsers.size(); i++) {
1983 UserInfo user = mUsers.valueAt(i);
1984 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001985 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001986 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001987 if (user.partial) pw.print(" <partial>");
1988 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001989 pw.print(" Created: ");
1990 if (user.creationTime == 0) {
1991 pw.println("<unknown>");
1992 } else {
1993 sb.setLength(0);
1994 TimeUtils.formatDuration(now - user.creationTime, sb);
1995 sb.append(" ago");
1996 pw.println(sb);
1997 }
1998 pw.print(" Last logged in: ");
1999 if (user.lastLoggedInTime == 0) {
2000 pw.println("<unknown>");
2001 } else {
2002 sb.setLength(0);
2003 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2004 sb.append(" ago");
2005 pw.println(sb);
2006 }
2007 }
2008 }
2009 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002010
2011 final class MainHandler extends Handler {
2012
2013 @Override
2014 public void handleMessage(Message msg) {
2015 switch (msg.what) {
2016 case WRITE_USER_MSG:
2017 removeMessages(WRITE_USER_MSG, msg.obj);
2018 synchronized (mPackagesLock) {
2019 int userId = ((UserInfo) msg.obj).id;
2020 UserInfo userInfo = mUsers.get(userId);
2021 if (userInfo != null) {
2022 writeUserLocked(userInfo);
2023 }
2024 }
2025 }
2026 }
2027 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028}