blob: 43469ba8af69ba85ace20ce49060d99664178593 [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
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
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;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.BufferedOutputStream;
63import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileOutputStream;
68import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070070import java.security.MessageDigest;
71import java.security.NoSuchAlgorithmException;
72import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070088 private static final String ATTR_SALT = "salt";
89 private static final String ATTR_PIN_HASH = "pinHash";
90 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
91 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070095 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010096 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053097 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700110 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111
Amith Yamasani0b285492011-04-14 17:35:23 -0700112 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasani5e486f52013-08-07 11:06:44 -0700121 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani655d0e22013-06-12 14:19:10 -0700125 // Number of attempts before jumping to the next BACKOFF_TIMES slot
126 private static final int BACKOFF_INC_INTERVAL = 5;
127
128 // Amount of time to force the user to wait before entering the PIN again, after failing
129 // BACKOFF_INC_INTERVAL times.
130 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
131
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530132
Dianne Hackborn4428e172012-08-24 17:43:05 -0700133 private final Context mContext;
134 private final PackageManagerService mPm;
135 private final Object mInstallLock;
136 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800138 private final Handler mHandler;
139
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private final File mUsersDir;
141 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700142 private final File mBaseUserPath;
143
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800144 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800145 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530146 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800147
Amith Yamasani655d0e22013-06-12 14:19:10 -0700148 class RestrictionsPinState {
149 long salt;
150 String pinHash;
151 int failedAttempts;
152 long lastAttemptTime;
153 }
154
155 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
156 new SparseArray<RestrictionsPinState>();
157
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800158 /**
159 * Set of user IDs being actively removed. Removed IDs linger in this set
160 * for several seconds to work around a VFS caching issue.
161 */
162 // @GuardedBy("mPackagesLock")
163 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700164
Amith Yamasani0b285492011-04-14 17:35:23 -0700165 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700166 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700167 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700168
Jason Monk62062992014-05-06 09:55:28 -0400169 private IAppOpsService mAppOpsService;
170
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172
Dianne Hackborn4428e172012-08-24 17:43:05 -0700173 public static UserManagerService getInstance() {
174 synchronized (UserManagerService.class) {
175 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178
179 /**
180 * Available for testing purposes.
181 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700182 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184 }
185
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 /**
187 * Called by package manager to create the service. This is closely
188 * associated with the package manager, and the given lock is the
189 * package manager's own lock.
190 */
191 UserManagerService(Context context, PackageManagerService pm,
192 Object installLock, Object packagesLock) {
193 this(context, pm, installLock, packagesLock,
194 Environment.getDataDirectory(),
195 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196 }
197
Dianne Hackborn4428e172012-08-24 17:43:05 -0700198 /**
199 * Available for testing purposes.
200 */
201 private UserManagerService(Context context, PackageManagerService pm,
202 Object installLock, Object packagesLock,
203 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700204 mContext = context;
205 mPm = pm;
206 mInstallLock = installLock;
207 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800208 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700209 synchronized (mInstallLock) {
210 synchronized (mPackagesLock) {
211 mUsersDir = new File(dataDir, USER_INFO_DIR);
212 mUsersDir.mkdirs();
213 // Make zeroth user directory, for services to migrate their files to that location
214 File userZeroDir = new File(mUsersDir, "0");
215 userZeroDir.mkdirs();
216 mBaseUserPath = baseUserPath;
217 FileUtils.setPermissions(mUsersDir.toString(),
218 FileUtils.S_IRWXU|FileUtils.S_IRWXG
219 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
220 -1, -1);
221 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
222 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700223 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700224 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
225 for (int i = 0; i < mUsers.size(); i++) {
226 UserInfo ui = mUsers.valueAt(i);
227 if (ui.partial && i != 0) {
228 partials.add(ui);
229 }
230 }
231 for (int i = 0; i < partials.size(); i++) {
232 UserInfo ui = partials.get(i);
233 Slog.w(LOG_TAG, "Removing partially created user #" + i
234 + " (name=" + ui.name + ")");
235 removeUserStateLocked(ui.id);
236 }
237 sInstance = this;
238 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700240 }
241
242 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700243 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400244 mAppOpsService = IAppOpsService.Stub.asInterface(
245 ServiceManager.getService(Context.APP_OPS_SERVICE));
246 for (int i = 0; i < mUserIds.length; ++i) {
247 try {
248 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
249 } catch (RemoteException e) {
250 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
251 }
252 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700253 }
254
255 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700256 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700257 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700258 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700259 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
260 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 UserInfo ui = mUsers.valueAt(i);
262 if (ui.partial) {
263 continue;
264 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800265 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700267 }
Amith Yamasani13593602012-03-22 16:16:17 -0700268 }
269 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700270 }
Amith Yamasani13593602012-03-22 16:16:17 -0700271 }
272
Amith Yamasani258848d2012-08-10 17:06:33 -0700273 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100274 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800275 if (userId != UserHandle.getCallingUserId()) {
276 checkManageUsersPermission("getting profiles related to user " + userId);
277 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700278 final long ident = Binder.clearCallingIdentity();
279 try {
280 synchronized (mPackagesLock) {
281 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100282 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700283 } finally {
284 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000285 }
286 }
287
Amith Yamasanibe465322014-04-24 13:45:17 -0700288 /** Assume permissions already checked and caller's identity cleared */
289 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 UserInfo user = getUserInfoLocked(userId);
291 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
292 for (int i = 0; i < mUsers.size(); i++) {
293 UserInfo profile = mUsers.valueAt(i);
294 if (!isProfileOf(user, profile)) {
295 continue;
296 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100297 if (enabledOnly && !profile.isEnabled()) {
298 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700299 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700300 if (mRemovingUserIds.get(profile.id)) {
301 continue;
302 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700303 users.add(profile);
304 }
305 return users;
306 }
307
Jessica Hummelbe81c802014-04-22 15:49:22 +0100308 @Override
309 public UserInfo getProfileParent(int userHandle) {
310 checkManageUsersPermission("get the profile parent");
311 synchronized (mPackagesLock) {
312 UserInfo profile = getUserInfoLocked(userHandle);
313 int parentUserId = profile.profileGroupId;
314 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
315 return null;
316 } else {
317 return getUserInfoLocked(parentUserId);
318 }
319 }
320 }
321
Kenny Guy2a764942014-04-02 13:29:20 +0100322 private boolean isProfileOf(UserInfo user, UserInfo profile) {
323 return user.id == profile.id ||
324 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
325 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000326 }
327
328 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100329 public void setUserEnabled(int userId) {
330 checkManageUsersPermission("enable user");
331 synchronized (mPackagesLock) {
332 UserInfo info = getUserInfoLocked(userId);
333 if (info != null && !info.isEnabled()) {
334 info.flags ^= UserInfo.FLAG_DISABLED;
335 writeUserLocked(info);
336 }
337 }
338 }
339
340 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700341 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700342 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700343 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700344 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700345 }
346 }
347
Amith Yamasani71e6c692013-03-24 17:39:28 -0700348 @Override
349 public boolean isRestricted() {
350 synchronized (mPackagesLock) {
351 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
352 }
353 }
354
Amith Yamasani195263742012-08-21 15:40:12 -0700355 /*
356 * Should be locked on mUsers before calling this.
357 */
358 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700360 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800361 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
363 return null;
364 }
365 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700366 }
367
Amith Yamasani13593602012-03-22 16:16:17 -0700368 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700369 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700370 return ArrayUtils.contains(mUserIds, userId);
371 }
372 }
373
Amith Yamasani258848d2012-08-10 17:06:33 -0700374 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700375 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700376 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700377 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700378 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700379 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700380 if (info == null || info.partial) {
381 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
382 return;
383 }
Amith Yamasani13593602012-03-22 16:16:17 -0700384 if (name != null && !name.equals(info.name)) {
385 info.name = name;
386 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700387 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700388 }
389 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700390 if (changed) {
391 sendUserInfoChangedBroadcast(userId);
392 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700393 }
394
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700396 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700397 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400398 long ident = Binder.clearCallingIdentity();
399 try {
400 synchronized (mPackagesLock) {
401 UserInfo info = mUsers.get(userId);
402 if (info == null || info.partial) {
403 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
404 return;
405 }
406 writeBitmapLocked(info, bitmap);
407 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700408 }
Jason Monk9a944532014-07-08 09:31:21 -0400409 sendUserInfoChangedBroadcast(userId);
410 } finally {
411 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700412 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700413 }
414
415 private void sendUserInfoChangedBroadcast(int userId) {
416 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
417 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
418 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700419 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700420 }
421
Amith Yamasani258848d2012-08-10 17:06:33 -0700422 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700423 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700424 synchronized (mPackagesLock) {
425 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700426 if (info == null || info.partial) {
427 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
428 return null;
429 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100430 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
431 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
432 || callingGroupId != info.profileGroupId) {
433 checkManageUsersPermission("get the icon of a user who is not related");
434 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 if (info.iconPath == null) {
436 return null;
437 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700438 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700439 }
440 }
441
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700442 public void makeInitialized(int userId) {
443 checkManageUsersPermission("makeInitialized");
444 synchronized (mPackagesLock) {
445 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 if (info == null || info.partial) {
447 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
448 }
449 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700450 info.flags |= UserInfo.FLAG_INITIALIZED;
451 writeUserLocked(info);
452 }
453 }
454 }
455
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800456 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530457 public Bundle getDefaultGuestRestrictions() {
458 checkManageUsersPermission("getDefaultGuestRestrictions");
459 synchronized (mPackagesLock) {
460 return new Bundle(mGuestRestrictions);
461 }
462 }
463
464 @Override
465 public void setDefaultGuestRestrictions(Bundle restrictions) {
466 checkManageUsersPermission("setDefaultGuestRestrictions");
467 synchronized (mPackagesLock) {
468 mGuestRestrictions.clear();
469 mGuestRestrictions.putAll(restrictions);
470 writeUserListLocked();
471 }
472 }
473
474 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800475 public Bundle getUserRestrictions(int userId) {
476 // checkManageUsersPermission("getUserRestrictions");
477
478 synchronized (mPackagesLock) {
479 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700480 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800481 }
482 }
483
484 @Override
485 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700486 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700487 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800488
489 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700490 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800491 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400492 long token = Binder.clearCallingIdentity();
493 try {
494 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
495 } catch (RemoteException e) {
496 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
497 } finally {
498 Binder.restoreCallingIdentity(token);
499 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800500 writeUserLocked(mUsers.get(userId));
501 }
502 }
503
Amith Yamasani258848d2012-08-10 17:06:33 -0700504 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700505 * Check if we've hit the limit of how many users can be created.
506 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700507 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700508 int aliveUserCount = 0;
509 final int totalUserCount = mUsers.size();
510 // Skip over users being removed
511 for (int i = 0; i < totalUserCount; i++) {
512 UserInfo user = mUsers.valueAt(i);
513 if (!mRemovingUserIds.get(user.id)) {
514 aliveUserCount++;
515 }
516 }
517 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700518 }
519
520 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700521 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700522 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700523 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700524 *
525 * @param message used as message if SecurityException is thrown
526 * @throws SecurityException if the caller is not system or root
527 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700528 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700529 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700530 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400531 && ActivityManager.checkComponentPermission(
532 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700533 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
534 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
535 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400536 }
537
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700538 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700539 try {
540 File dir = new File(mUsersDir, Integer.toString(info.id));
541 File file = new File(dir, USER_PHOTO_FILENAME);
542 if (!dir.exists()) {
543 dir.mkdir();
544 FileUtils.setPermissions(
545 dir.getPath(),
546 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
547 -1, -1);
548 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700549 FileOutputStream os;
550 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700551 info.iconPath = file.getAbsolutePath();
552 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700553 try {
554 os.close();
555 } catch (IOException ioe) {
556 // What the ... !
557 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700558 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700559 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700560 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700561 }
562
Amith Yamasani0b285492011-04-14 17:35:23 -0700563 /**
564 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
565 * cache it elsewhere.
566 * @return the array of user ids.
567 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700568 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700569 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700570 return mUserIds;
571 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700572 }
573
Dianne Hackborn4428e172012-08-24 17:43:05 -0700574 int[] getUserIdsLPr() {
575 return mUserIds;
576 }
577
Amith Yamasani13593602012-03-22 16:16:17 -0700578 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700579 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700580 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700581 return;
582 }
583 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700584 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700585 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700586 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700587 XmlPullParser parser = Xml.newPullParser();
588 parser.setInput(fis, null);
589 int type;
590 while ((type = parser.next()) != XmlPullParser.START_TAG
591 && type != XmlPullParser.END_DOCUMENT) {
592 ;
593 }
594
595 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700596 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700597 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700598 return;
599 }
600
Amith Yamasani2a003292012-08-14 18:25:45 -0700601 mNextSerialNumber = -1;
602 if (parser.getName().equals(TAG_USERS)) {
603 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
604 if (lastSerialNumber != null) {
605 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
606 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700607 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
608 if (versionNumber != null) {
609 mUserVersion = Integer.parseInt(versionNumber);
610 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700611 }
612
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700613 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530614 if (type == XmlPullParser.START_TAG) {
615 final String name = parser.getName();
616 if (name.equals(TAG_USER)) {
617 String id = parser.getAttributeValue(null, ATTR_ID);
618 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700619
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530620 if (user != null) {
621 mUsers.put(user.id, user);
622 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
623 mNextSerialNumber = user.id + 1;
624 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700625 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530626 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
627 mGuestRestrictions.clear();
628 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700629 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700630 }
631 }
Amith Yamasani13593602012-03-22 16:16:17 -0700632 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700633 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700634 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700635 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700636 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700637 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800638 } finally {
639 if (fis != null) {
640 try {
641 fis.close();
642 } catch (IOException e) {
643 }
644 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700645 }
646 }
647
Amith Yamasani6f34b412012-10-22 18:19:27 -0700648 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800649 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700650 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700651 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700652 int userVersion = mUserVersion;
653 if (userVersion < 1) {
654 // Assign a proper name for the owner, if not initialized correctly before
655 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
656 if ("Primary".equals(user.name)) {
657 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
658 writeUserLocked(user);
659 }
660 userVersion = 1;
661 }
662
Amith Yamasanibc9625052012-11-15 14:39:18 -0800663 if (userVersion < 2) {
664 // Owner should be marked as initialized
665 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
666 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
667 user.flags |= UserInfo.FLAG_INITIALIZED;
668 writeUserLocked(user);
669 }
670 userVersion = 2;
671 }
672
Amith Yamasani350962c2013-08-06 11:18:53 -0700673
Amith Yamasani5e486f52013-08-07 11:06:44 -0700674 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700675 userVersion = 4;
676 }
677
Amith Yamasani6f34b412012-10-22 18:19:27 -0700678 if (userVersion < USER_VERSION) {
679 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
680 + USER_VERSION);
681 } else {
682 mUserVersion = userVersion;
683 writeUserListLocked();
684 }
685 }
686
Amith Yamasani13593602012-03-22 16:16:17 -0700687 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700688 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800689 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700690 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700691 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700692 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700693 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400694 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800695
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500696 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800697 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
698
Amith Yamasani13593602012-03-22 16:16:17 -0700699 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700700
Amith Yamasani13593602012-03-22 16:16:17 -0700701 writeUserListLocked();
702 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700703 }
704
705 /*
706 * Writes the user file in this format:
707 *
708 * <user flags="20039023" id="0">
709 * <name>Primary</name>
710 * </user>
711 */
Amith Yamasani13593602012-03-22 16:16:17 -0700712 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700713 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700714 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700715 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700716 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700717 final BufferedOutputStream bos = new BufferedOutputStream(fos);
718
719 // XmlSerializer serializer = XmlUtils.serializerInstance();
720 final XmlSerializer serializer = new FastXmlSerializer();
721 serializer.setOutput(bos, "utf-8");
722 serializer.startDocument(null, true);
723 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
724
725 serializer.startTag(null, TAG_USER);
726 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700727 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700728 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700729 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
730 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
731 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700732 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
733 if (pinState != null) {
734 if (pinState.salt != 0) {
735 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
736 }
737 if (pinState.pinHash != null) {
738 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
739 }
740 if (pinState.failedAttempts != 0) {
741 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
742 Integer.toString(pinState.failedAttempts));
743 serializer.attribute(null, ATTR_LAST_RETRY_MS,
744 Long.toString(pinState.lastAttemptTime));
745 }
746 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700747 if (userInfo.iconPath != null) {
748 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
749 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700750 if (userInfo.partial) {
751 serializer.attribute(null, ATTR_PARTIAL, "true");
752 }
Kenny Guy2a764942014-04-02 13:29:20 +0100753 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
754 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
755 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000756 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757
758 serializer.startTag(null, TAG_NAME);
759 serializer.text(userInfo.name);
760 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800761 Bundle restrictions = mUserRestrictions.get(userInfo.id);
762 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530763 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800764 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 serializer.endTag(null, TAG_USER);
766
767 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700768 userFile.finishWrite(fos);
769 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700770 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700771 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 }
773 }
774
775 /*
776 * Writes the user list file in this format:
777 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700778 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 * <user id="0"></user>
780 * <user id="2"></user>
781 * </users>
782 */
Amith Yamasani13593602012-03-22 16:16:17 -0700783 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700784 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700787 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 final BufferedOutputStream bos = new BufferedOutputStream(fos);
789
790 // XmlSerializer serializer = XmlUtils.serializerInstance();
791 final XmlSerializer serializer = new FastXmlSerializer();
792 serializer.setOutput(bos, "utf-8");
793 serializer.startDocument(null, true);
794 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
795
796 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700798 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700799
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530800 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
801 writeRestrictionsLocked(serializer, mGuestRestrictions);
802 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700803 for (int i = 0; i < mUsers.size(); i++) {
804 UserInfo user = mUsers.valueAt(i);
805 serializer.startTag(null, TAG_USER);
806 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
807 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700808 }
809
810 serializer.endTag(null, TAG_USERS);
811
812 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700813 userListFile.finishWrite(fos);
814 } catch (Exception e) {
815 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700816 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 }
818 }
819
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530820 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
821 throws IOException {
822 serializer.startTag(null, TAG_RESTRICTIONS);
823 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
824 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
825 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
826 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
827 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
828 writeBoolean(serializer, restrictions,
829 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
830 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
831 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
832 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
833 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
834 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
835 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
836 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
837 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
838 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
839 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
840 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
841 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
842 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
843 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
844 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
845 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
846 writeBoolean(serializer, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400847 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530848 serializer.endTag(null, TAG_RESTRICTIONS);
849 }
850
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800851 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700853 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700855 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700856 long creationTime = 0L;
857 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700858 long salt = 0L;
859 String pinHash = null;
860 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100861 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700862 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700863 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800864 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865
866 FileInputStream fis = null;
867 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700868 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700869 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700870 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700871 XmlPullParser parser = Xml.newPullParser();
872 parser.setInput(fis, null);
873 int type;
874 while ((type = parser.next()) != XmlPullParser.START_TAG
875 && type != XmlPullParser.END_DOCUMENT) {
876 ;
877 }
878
879 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700880 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700881 return null;
882 }
883
884 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700885 int storedId = readIntAttribute(parser, ATTR_ID, -1);
886 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700887 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700888 return null;
889 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700890 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
891 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700892 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700893 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
894 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700895 salt = readLongAttribute(parser, ATTR_SALT, 0L);
896 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
897 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
898 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100899 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
900 UserInfo.NO_PROFILE_GROUP_ID);
901 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
902 // This attribute was added and renamed during development of L.
903 // TODO Remove upgrade path by 1st May 2014
904 profileGroupId = readIntAttribute(parser, "relatedGroupId",
905 UserInfo.NO_PROFILE_GROUP_ID);
906 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700907 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
908 if ("true".equals(valueString)) {
909 partial = true;
910 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800912 int outerDepth = parser.getDepth();
913 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
914 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
915 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
916 continue;
917 }
918 String tag = parser.getName();
919 if (TAG_NAME.equals(tag)) {
920 type = parser.next();
921 if (type == XmlPullParser.TEXT) {
922 name = parser.getText();
923 }
924 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530925 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 }
927 }
928 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700929
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700930 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700931 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700932 userInfo.creationTime = creationTime;
933 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700934 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100935 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800936 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700937 if (salt != 0L) {
938 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
939 if (pinState == null) {
940 pinState = new RestrictionsPinState();
941 mRestrictionsPinStates.put(id, pinState);
942 }
943 pinState.salt = salt;
944 pinState.pinHash = pinHash;
945 pinState.failedAttempts = failedAttempts;
946 pinState.lastAttemptTime = lastAttemptTime;
947 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700948 return userInfo;
949
950 } catch (IOException ioe) {
951 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800952 } finally {
953 if (fis != null) {
954 try {
955 fis.close();
956 } catch (IOException e) {
957 }
958 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700959 }
960 return null;
961 }
962
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530963 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
964 throws IOException {
965 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
966 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
967 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
968 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
969 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
970 readBoolean(parser, restrictions,
971 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
972 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
973 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
974 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
975 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
976 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
977 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
978 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
979 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
980 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
981 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
982 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
983 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
984 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
985 readBoolean(parser, restrictions,
986 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
987 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
988 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
989 readBoolean(parser, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400990 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530991 }
992
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800993 private void readBoolean(XmlPullParser parser, Bundle restrictions,
994 String restrictionKey) {
995 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700996 if (value != null) {
997 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
998 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800999 }
1000
1001 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1002 throws IOException {
1003 if (restrictions.containsKey(restrictionKey)) {
1004 xml.attribute(null, restrictionKey,
1005 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1006 }
1007 }
1008
Amith Yamasani920ace02012-09-20 22:15:37 -07001009 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1010 String valueString = parser.getAttributeValue(null, attr);
1011 if (valueString == null) return defaultValue;
1012 try {
1013 return Integer.parseInt(valueString);
1014 } catch (NumberFormatException nfe) {
1015 return defaultValue;
1016 }
1017 }
1018
1019 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1020 String valueString = parser.getAttributeValue(null, attr);
1021 if (valueString == null) return defaultValue;
1022 try {
1023 return Long.parseLong(valueString);
1024 } catch (NumberFormatException nfe) {
1025 return defaultValue;
1026 }
1027 }
1028
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001029 private boolean isPackageInstalled(String pkg, int userId) {
1030 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1031 PackageManager.GET_UNINSTALLED_PACKAGES,
1032 userId);
1033 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1034 return false;
1035 }
1036 return true;
1037 }
1038
Amith Yamasanib82add22013-07-09 11:24:44 -07001039 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001040 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001041 * Does not do any permissions checking.
1042 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001043 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001044 synchronized (mPackagesLock) {
1045 File dir = Environment.getUserSystemDirectory(userId);
1046 String[] files = dir.list();
1047 if (files == null) return;
1048 for (String fileName : files) {
1049 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1050 File resFile = new File(dir, fileName);
1051 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001052 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001053 }
1054 }
1055 }
1056 }
1057 }
1058
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001059 /**
1060 * Removes the app restrictions file for a specific package and user id, if it exists.
1061 */
1062 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1063 synchronized (mPackagesLock) {
1064 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001065 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001066 if (resFile.exists()) {
1067 resFile.delete();
1068 }
1069 }
1070 }
1071
Kenny Guya52dc3e2014-02-11 15:33:14 +00001072 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001073 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001074 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001075 if (userId != UserHandle.USER_OWNER) {
1076 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001077 return null;
1078 }
Kenny Guy2a764942014-04-02 13:29:20 +01001079 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001080 }
1081
Amith Yamasani258848d2012-08-10 17:06:33 -07001082 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001083 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001084 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001085 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001086 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001087
Jessica Hummelbe81c802014-04-22 15:49:22 +01001088 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001089 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1090 UserManager.DISALLOW_ADD_USER, false)) {
1091 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1092 return null;
1093 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001094 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001095 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001096 try {
1097 synchronized (mInstallLock) {
1098 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001099 UserInfo parent = null;
1100 if (parentId != UserHandle.USER_NULL) {
1101 parent = getUserInfoLocked(parentId);
1102 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001103 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001104 if (isUserLimitReachedLocked()) return null;
1105 int userId = getNextAvailableIdLocked();
1106 userInfo = new UserInfo(userId, name, null, flags);
1107 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1108 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001109 long now = System.currentTimeMillis();
1110 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001111 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001112 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001113 mUsers.put(userId, userInfo);
1114 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001115 if (parent != null) {
1116 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1117 parent.profileGroupId = parent.id;
1118 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001119 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001120 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001121 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001122 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001123 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001124 userInfo.partial = false;
1125 writeUserLocked(userInfo);
1126 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001127 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001128 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001129 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001130 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001131 if (userInfo != null) {
1132 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1133 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1134 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1135 android.Manifest.permission.MANAGE_USERS);
1136 }
1137 } finally {
1138 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001139 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001140 return userInfo;
1141 }
1142
Amith Yamasani0b285492011-04-14 17:35:23 -07001143 /**
1144 * Removes a user and all data directories created for that user. This method should be called
1145 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001146 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001147 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001148 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001149 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001150 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1151 UserManager.DISALLOW_REMOVE_USER, false)) {
1152 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1153 return false;
1154 }
1155
Kenny Guyee58b4f2014-05-23 15:19:53 +01001156 long ident = Binder.clearCallingIdentity();
1157 try {
1158 final UserInfo user;
1159 synchronized (mPackagesLock) {
1160 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001161 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001162 return false;
1163 }
1164 mRemovingUserIds.put(userHandle, true);
1165 try {
1166 mAppOpsService.removeUser(userHandle);
1167 } catch (RemoteException e) {
1168 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1169 }
1170 // Set this to a partially created user, so that the user will be purged
1171 // on next startup, in case the runtime stops now before stopping and
1172 // removing the user completely.
1173 user.partial = true;
1174 // Mark it as disabled, so that it isn't returned any more when
1175 // profiles are queried.
1176 user.flags |= UserInfo.FLAG_DISABLED;
1177 writeUserLocked(user);
1178 }
1179
1180 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1181 && user.isManagedProfile()) {
1182 // Send broadcast to notify system that the user removed was a
1183 // managed user.
1184 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1185 }
1186
1187 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1188 int res;
1189 try {
1190 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1191 new IStopUserCallback.Stub() {
1192 @Override
1193 public void userStopped(int userId) {
1194 finishRemoveUser(userId);
1195 }
1196 @Override
1197 public void userStopAborted(int userId) {
1198 }
1199 });
1200 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001201 return false;
1202 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001203 return res == ActivityManager.USER_OP_SUCCESS;
1204 } finally {
1205 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001206 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001207 }
1208
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001209 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001210 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001211 // Let other services shutdown any activity and clean up their state before completely
1212 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001213 long ident = Binder.clearCallingIdentity();
1214 try {
1215 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1216 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001217 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1218 android.Manifest.permission.MANAGE_USERS,
1219
1220 new BroadcastReceiver() {
1221 @Override
1222 public void onReceive(Context context, Intent intent) {
1223 if (DBG) {
1224 Slog.i(LOG_TAG,
1225 "USER_REMOVED broadcast sent, cleaning up user data "
1226 + userHandle);
1227 }
1228 new Thread() {
1229 public void run() {
1230 synchronized (mInstallLock) {
1231 synchronized (mPackagesLock) {
1232 removeUserStateLocked(userHandle);
1233 }
1234 }
1235 }
1236 }.start();
1237 }
1238 },
1239
1240 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001241 } finally {
1242 Binder.restoreCallingIdentity(ident);
1243 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001244 }
1245
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001246 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001247 // Cleanup package manager settings
1248 mPm.cleanUpUserLILPw(userHandle);
1249
1250 // Remove this user from the list
1251 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001252
1253 // Have user ID linger for several seconds to let external storage VFS
1254 // cache entries expire. This must be greater than the 'entry_valid'
1255 // timeout used by the FUSE daemon.
1256 mHandler.postDelayed(new Runnable() {
1257 @Override
1258 public void run() {
1259 synchronized (mPackagesLock) {
1260 mRemovingUserIds.delete(userHandle);
1261 }
1262 }
1263 }, MINUTE_IN_MILLIS);
1264
Amith Yamasani655d0e22013-06-12 14:19:10 -07001265 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001266 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001267 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001268 userFile.delete();
1269 // Update the user list
1270 writeUserListLocked();
1271 updateUserIdsLocked();
1272 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1273 }
1274
Amith Yamasani61f57372012-08-31 12:12:28 -07001275 private void removeDirectoryRecursive(File parent) {
1276 if (parent.isDirectory()) {
1277 String[] files = parent.list();
1278 for (String filename : files) {
1279 File child = new File(parent, filename);
1280 removeDirectoryRecursive(child);
1281 }
1282 }
1283 parent.delete();
1284 }
1285
Kenny Guyf8d3a232014-05-15 16:09:52 +01001286 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001287 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001288 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1289 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001290 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1291 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001292 }
1293
Amith Yamasani2a003292012-08-14 18:25:45 -07001294 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001295 public Bundle getApplicationRestrictions(String packageName) {
1296 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1297 }
1298
1299 @Override
1300 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001301 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001302 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001303 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001304 }
1305 synchronized (mPackagesLock) {
1306 // Read the restrictions from XML
1307 return readApplicationRestrictionsLocked(packageName, userId);
1308 }
1309 }
1310
1311 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001312 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001313 int userId) {
1314 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001315 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001316 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001317 }
1318 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001319 if (restrictions == null || restrictions.isEmpty()) {
1320 cleanAppRestrictionsForPackage(packageName, userId);
1321 } else {
1322 // Write the restrictions to XML
1323 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1324 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001325 }
Robin Lee66e5d962014-04-09 16:44:21 +01001326
Kenny Guyd21b2182014-07-17 16:38:55 +01001327 if (isPackageInstalled(packageName, userId)) {
1328 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1329 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1330 changeIntent.setPackage(packageName);
1331 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1332 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1333 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001334 }
1335
Amith Yamasani655d0e22013-06-12 14:19:10 -07001336 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001337 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001338 checkManageUsersPermission("Only system can modify the restrictions pin");
1339 int userId = UserHandle.getCallingUserId();
1340 synchronized (mPackagesLock) {
1341 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1342 if (pinState == null) {
1343 pinState = new RestrictionsPinState();
1344 }
1345 if (newPin == null) {
1346 pinState.salt = 0;
1347 pinState.pinHash = null;
1348 } else {
1349 try {
1350 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1351 } catch (NoSuchAlgorithmException e) {
1352 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1353 }
1354 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1355 pinState.failedAttempts = 0;
1356 }
1357 mRestrictionsPinStates.put(userId, pinState);
1358 writeUserLocked(mUsers.get(userId));
1359 }
1360 return true;
1361 }
1362
1363 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001364 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001365 checkManageUsersPermission("Only system can verify the restrictions pin");
1366 int userId = UserHandle.getCallingUserId();
1367 synchronized (mPackagesLock) {
1368 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1369 // If there's no pin set, return error code
1370 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1371 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1372 } else if (pin == null) {
1373 // If just checking if user can be prompted, return remaining time
1374 int waitTime = getRemainingTimeForPinAttempt(pinState);
1375 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1376 return waitTime;
1377 } else {
1378 int waitTime = getRemainingTimeForPinAttempt(pinState);
1379 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1380 if (waitTime > 0) {
1381 return waitTime;
1382 }
1383 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1384 pinState.failedAttempts = 0;
1385 writeUserLocked(mUsers.get(userId));
1386 return UserManager.PIN_VERIFICATION_SUCCESS;
1387 } else {
1388 pinState.failedAttempts++;
1389 pinState.lastAttemptTime = System.currentTimeMillis();
1390 writeUserLocked(mUsers.get(userId));
1391 return waitTime;
1392 }
1393 }
1394 }
1395 }
1396
1397 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1398 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1399 BACKOFF_TIMES.length - 1);
1400 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1401 BACKOFF_TIMES[backoffIndex] : 0;
1402 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1403 0);
1404 }
1405
1406 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001407 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001408 int userId = UserHandle.getCallingUserId();
1409 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001410 return hasRestrictionsPinLocked(userId);
1411 }
1412 }
1413
1414 private boolean hasRestrictionsPinLocked(int userId) {
1415 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1416 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1417 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001418 }
1419 return true;
1420 }
1421
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001422 @Override
1423 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001424 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001425 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001426 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001427 }
1428
Amith Yamasani5e486f52013-08-07 11:06:44 -07001429 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001430 synchronized (mPackagesLock) {
1431 // Remove all user restrictions
1432 setUserRestrictions(new Bundle(), userHandle);
1433 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001434 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001435 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001436 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001437 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001438 if (unblockApps) {
1439 unblockAllAppsForUser(userHandle);
1440 }
1441 }
1442
1443 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001444 mHandler.post(new Runnable() {
1445 @Override
1446 public void run() {
1447 List<ApplicationInfo> apps =
1448 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1449 userHandle).getList();
1450 final long ident = Binder.clearCallingIdentity();
1451 try {
1452 for (ApplicationInfo appInfo : apps) {
1453 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1454 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1455 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1456 userHandle);
1457 }
1458 }
1459 } finally {
1460 Binder.restoreCallingIdentity(ident);
1461 }
1462 }
1463 });
1464 }
1465
Amith Yamasani655d0e22013-06-12 14:19:10 -07001466 /*
1467 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1468 * Not the most secure, but it is at least a second level of protection. First level is that
1469 * the file is in a location only readable by the system process.
1470 * @param password the password.
1471 * @param salt the randomly generated salt
1472 * @return the hash of the pattern in a String.
1473 */
1474 private String passwordToHash(String password, long salt) {
1475 if (password == null) {
1476 return null;
1477 }
1478 String algo = null;
1479 String hashed = salt + password;
1480 try {
1481 byte[] saltedPassword = (password + salt).getBytes();
1482 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1483 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1484 hashed = toHex(sha1) + toHex(md5);
1485 } catch (NoSuchAlgorithmException e) {
1486 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1487 }
1488 return hashed;
1489 }
1490
1491 private static String toHex(byte[] ary) {
1492 final String hex = "0123456789ABCDEF";
1493 String ret = "";
1494 for (int i = 0; i < ary.length; i++) {
1495 ret += hex.charAt((ary[i] >> 4) & 0xf);
1496 ret += hex.charAt(ary[i] & 0xf);
1497 }
1498 return ret;
1499 }
1500
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001501 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001502 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001503 try {
1504 return mContext.getPackageManager().getApplicationInfo(packageName,
1505 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1506 } catch (NameNotFoundException nnfe) {
1507 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001508 } finally {
1509 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001510 }
1511 }
1512
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001513 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001514 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001515 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001516 final ArrayList<String> values = new ArrayList<String>();
1517
1518 FileInputStream fis = null;
1519 try {
1520 AtomicFile restrictionsFile =
1521 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001522 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001523 fis = restrictionsFile.openRead();
1524 XmlPullParser parser = Xml.newPullParser();
1525 parser.setInput(fis, null);
1526 int type;
1527 while ((type = parser.next()) != XmlPullParser.START_TAG
1528 && type != XmlPullParser.END_DOCUMENT) {
1529 ;
1530 }
1531
1532 if (type != XmlPullParser.START_TAG) {
1533 Slog.e(LOG_TAG, "Unable to read restrictions file "
1534 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001535 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001536 }
1537
1538 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1539 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1540 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001541 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001542 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1543 if (multiple != null) {
1544 int count = Integer.parseInt(multiple);
1545 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1546 if (type == XmlPullParser.START_TAG
1547 && parser.getName().equals(TAG_VALUE)) {
1548 values.add(parser.nextText().trim());
1549 count--;
1550 }
1551 }
1552 String [] valueStrings = new String[values.size()];
1553 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001554 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001555 } else {
1556 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001557 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1558 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1559 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1560 restrictions.putInt(key, Integer.parseInt(value));
1561 } else {
1562 restrictions.putString(key, value);
1563 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001564 }
1565 }
1566 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001567 } catch (IOException ioe) {
1568 } catch (XmlPullParserException pe) {
1569 } finally {
1570 if (fis != null) {
1571 try {
1572 fis.close();
1573 } catch (IOException e) {
1574 }
1575 }
1576 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001577 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001578 }
1579
1580 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001581 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 FileOutputStream fos = null;
1583 AtomicFile restrictionsFile = new AtomicFile(
1584 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001585 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001586 try {
1587 fos = restrictionsFile.startWrite();
1588 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1589
1590 // XmlSerializer serializer = XmlUtils.serializerInstance();
1591 final XmlSerializer serializer = new FastXmlSerializer();
1592 serializer.setOutput(bos, "utf-8");
1593 serializer.startDocument(null, true);
1594 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1595
1596 serializer.startTag(null, TAG_RESTRICTIONS);
1597
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001598 for (String key : restrictions.keySet()) {
1599 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001600 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001601 serializer.attribute(null, ATTR_KEY, key);
1602
1603 if (value instanceof Boolean) {
1604 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1605 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001606 } else if (value instanceof Integer) {
1607 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1608 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001609 } else if (value == null || value instanceof String) {
1610 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1611 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001612 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001613 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1614 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001615 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001616 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001618 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001619 serializer.endTag(null, TAG_VALUE);
1620 }
1621 }
1622 serializer.endTag(null, TAG_ENTRY);
1623 }
1624
1625 serializer.endTag(null, TAG_RESTRICTIONS);
1626
1627 serializer.endDocument();
1628 restrictionsFile.finishWrite(fos);
1629 } catch (Exception e) {
1630 restrictionsFile.failWrite(fos);
1631 Slog.e(LOG_TAG, "Error writing application restrictions list");
1632 }
1633 }
1634
1635 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001636 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001637 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001638 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001639 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001640 }
1641 }
1642
1643 @Override
1644 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001645 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001646 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001647 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001648 }
1649 // Not found
1650 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001651 }
1652 }
1653
Amith Yamasani0b285492011-04-14 17:35:23 -07001654 /**
1655 * Caches the list of user ids in an array, adjusting the array size when necessary.
1656 */
Amith Yamasani13593602012-03-22 16:16:17 -07001657 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001658 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001659 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001660 if (!mUsers.valueAt(i).partial) {
1661 num++;
1662 }
1663 }
Amith Yamasani16389312012-10-17 21:20:14 -07001664 final int[] newUsers = new int[num];
1665 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001666 for (int i = 0; i < mUsers.size(); i++) {
1667 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001668 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001669 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001670 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001671 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001672 }
1673
1674 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001675 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001676 * @param userId the user that was just foregrounded
1677 */
1678 public void userForeground(int userId) {
1679 synchronized (mPackagesLock) {
1680 UserInfo user = mUsers.get(userId);
1681 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001682 if (user == null || user.partial) {
1683 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1684 return;
1685 }
1686 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001687 user.lastLoggedInTime = now;
1688 writeUserLocked(user);
1689 }
1690 }
1691 }
1692
1693 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001694 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001695 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1696 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001697 * @return
1698 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001699 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001700 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001701 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001702 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001703 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001704 break;
1705 }
1706 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001707 }
Amith Yamasani195263742012-08-21 15:40:12 -07001708 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001709 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001710 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001711
Amith Yamasanifc95e702013-09-26 13:20:17 -07001712 private String packageToRestrictionsFileName(String packageName) {
1713 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1714 }
1715
1716 private String restrictionsFileNameToPackage(String fileName) {
1717 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1718 (int) (fileName.length() - XML_SUFFIX.length()));
1719 }
1720
Amith Yamasani920ace02012-09-20 22:15:37 -07001721 @Override
1722 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1723 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1724 != PackageManager.PERMISSION_GRANTED) {
1725 pw.println("Permission Denial: can't dump UserManager from from pid="
1726 + Binder.getCallingPid()
1727 + ", uid=" + Binder.getCallingUid()
1728 + " without permission "
1729 + android.Manifest.permission.DUMP);
1730 return;
1731 }
1732
1733 long now = System.currentTimeMillis();
1734 StringBuilder sb = new StringBuilder();
1735 synchronized (mPackagesLock) {
1736 pw.println("Users:");
1737 for (int i = 0; i < mUsers.size(); i++) {
1738 UserInfo user = mUsers.valueAt(i);
1739 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001740 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001741 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001742 if (user.partial) pw.print(" <partial>");
1743 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001744 pw.print(" Created: ");
1745 if (user.creationTime == 0) {
1746 pw.println("<unknown>");
1747 } else {
1748 sb.setLength(0);
1749 TimeUtils.formatDuration(now - user.creationTime, sb);
1750 sb.append(" ago");
1751 pw.println(sb);
1752 }
1753 pw.print(" Last logged in: ");
1754 if (user.lastLoggedInTime == 0) {
1755 pw.println("<unknown>");
1756 } else {
1757 sb.setLength(0);
1758 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1759 sb.append(" ago");
1760 pw.println(sb);
1761 }
1762 }
1763 }
1764 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001765}