blob: 194e85de978e9663e03c27b1c443dde969005681 [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;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070055import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
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
Amith Yamasani258848d2012-08-10 17:06:33 -070077public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani16389312012-10-17 21:20:14 -070081 private static final boolean DBG = false;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070087 private static final String ATTR_CREATION_TIME = "created";
88 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070089 private static final String ATTR_SALT = "salt";
90 private static final String ATTR_PIN_HASH = "pinHash";
91 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
92 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070093 private static final String ATTR_SERIAL_NO = "serialNumber";
94 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070095 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053098 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800101 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String TAG_ENTRY = "entry";
103 private static final String TAG_VALUE = "value";
104 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800106 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
109 private static final String ATTR_TYPE_STRING = "s";
110 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700111 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112
Amith Yamasani0b285492011-04-14 17:35:23 -0700113 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700118 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800119
Amith Yamasani634cf312012-10-04 17:34:21 -0700120 private static final int MIN_USER_ID = 10;
121
Amith Yamasani5e486f52013-08-07 11:06:44 -0700122 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700123
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
125
Amith Yamasani655d0e22013-06-12 14:19:10 -0700126 // Number of attempts before jumping to the next BACKOFF_TIMES slot
127 private static final int BACKOFF_INC_INTERVAL = 5;
128
129 // Amount of time to force the user to wait before entering the PIN again, after failing
130 // BACKOFF_INC_INTERVAL times.
131 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
132
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530133
Dianne Hackborn4428e172012-08-24 17:43:05 -0700134 private final Context mContext;
135 private final PackageManagerService mPm;
136 private final Object mInstallLock;
137 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800139 private final Handler mHandler;
140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private final File mUsersDir;
142 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700143 private final File mBaseUserPath;
144
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800145 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800146 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530147 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800148
Amith Yamasani655d0e22013-06-12 14:19:10 -0700149 class RestrictionsPinState {
150 long salt;
151 String pinHash;
152 int failedAttempts;
153 long lastAttemptTime;
154 }
155
156 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
157 new SparseArray<RestrictionsPinState>();
158
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800159 /**
160 * Set of user IDs being actively removed. Removed IDs linger in this set
161 * for several seconds to work around a VFS caching issue.
162 */
163 // @GuardedBy("mPackagesLock")
164 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165
Amith Yamasani0b285492011-04-14 17:35:23 -0700166 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700167 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700168 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700169
Jason Monk62062992014-05-06 09:55:28 -0400170 private IAppOpsService mAppOpsService;
171
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700173
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174 public static UserManagerService getInstance() {
175 synchronized (UserManagerService.class) {
176 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
180 /**
181 * Available for testing purposes.
182 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700183 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 }
186
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 /**
188 * Called by package manager to create the service. This is closely
189 * associated with the package manager, and the given lock is the
190 * package manager's own lock.
191 */
192 UserManagerService(Context context, PackageManagerService pm,
193 Object installLock, Object packagesLock) {
194 this(context, pm, installLock, packagesLock,
195 Environment.getDataDirectory(),
196 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Available for testing purposes.
201 */
202 private UserManagerService(Context context, PackageManagerService pm,
203 Object installLock, Object packagesLock,
204 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700205 mContext = context;
206 mPm = pm;
207 mInstallLock = installLock;
208 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800209 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700210 synchronized (mInstallLock) {
211 synchronized (mPackagesLock) {
212 mUsersDir = new File(dataDir, USER_INFO_DIR);
213 mUsersDir.mkdirs();
214 // Make zeroth user directory, for services to migrate their files to that location
215 File userZeroDir = new File(mUsersDir, "0");
216 userZeroDir.mkdirs();
217 mBaseUserPath = baseUserPath;
218 FileUtils.setPermissions(mUsersDir.toString(),
219 FileUtils.S_IRWXU|FileUtils.S_IRWXG
220 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
221 -1, -1);
222 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
223 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700224 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
226 for (int i = 0; i < mUsers.size(); i++) {
227 UserInfo ui = mUsers.valueAt(i);
228 if (ui.partial && i != 0) {
229 partials.add(ui);
230 }
231 }
232 for (int i = 0; i < partials.size(); i++) {
233 UserInfo ui = partials.get(i);
234 Slog.w(LOG_TAG, "Removing partially created user #" + i
235 + " (name=" + ui.name + ")");
236 removeUserStateLocked(ui.id);
237 }
238 sInstance = this;
239 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700241 }
242
243 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700244 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700245 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400246 mAppOpsService = IAppOpsService.Stub.asInterface(
247 ServiceManager.getService(Context.APP_OPS_SERVICE));
248 for (int i = 0; i < mUserIds.length; ++i) {
249 try {
250 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
251 } catch (RemoteException e) {
252 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
253 }
254 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 }
256
257 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700258 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700259 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700260 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700261 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
262 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700263 UserInfo ui = mUsers.valueAt(i);
264 if (ui.partial) {
265 continue;
266 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800267 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700269 }
Amith Yamasani13593602012-03-22 16:16:17 -0700270 }
271 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700272 }
Amith Yamasani13593602012-03-22 16:16:17 -0700273 }
274
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100276 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800277 if (userId != UserHandle.getCallingUserId()) {
278 checkManageUsersPermission("getting profiles related to user " + userId);
279 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700280 final long ident = Binder.clearCallingIdentity();
281 try {
282 synchronized (mPackagesLock) {
283 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100284 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 } finally {
286 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000287 }
288 }
289
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 /** Assume permissions already checked and caller's identity cleared */
291 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700292 UserInfo user = getUserInfoLocked(userId);
293 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
294 for (int i = 0; i < mUsers.size(); i++) {
295 UserInfo profile = mUsers.valueAt(i);
296 if (!isProfileOf(user, profile)) {
297 continue;
298 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100299 if (enabledOnly && !profile.isEnabled()) {
300 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 }
302 users.add(profile);
303 }
304 return users;
305 }
306
Jessica Hummelbe81c802014-04-22 15:49:22 +0100307 @Override
308 public UserInfo getProfileParent(int userHandle) {
309 checkManageUsersPermission("get the profile parent");
310 synchronized (mPackagesLock) {
311 UserInfo profile = getUserInfoLocked(userHandle);
312 int parentUserId = profile.profileGroupId;
313 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
314 return null;
315 } else {
316 return getUserInfoLocked(parentUserId);
317 }
318 }
319 }
320
Kenny Guy2a764942014-04-02 13:29:20 +0100321 private boolean isProfileOf(UserInfo user, UserInfo profile) {
322 return user.id == profile.id ||
323 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
324 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000325 }
326
327 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100328 public void setUserEnabled(int userId) {
329 checkManageUsersPermission("enable user");
330 synchronized (mPackagesLock) {
331 UserInfo info = getUserInfoLocked(userId);
332 if (info != null && !info.isEnabled()) {
333 info.flags ^= UserInfo.FLAG_DISABLED;
334 writeUserLocked(info);
335 }
336 }
337 }
338
339 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700340 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700341 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700342 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700343 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700344 }
345 }
346
Amith Yamasani71e6c692013-03-24 17:39:28 -0700347 @Override
348 public boolean isRestricted() {
349 synchronized (mPackagesLock) {
350 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
351 }
352 }
353
Amith Yamasani195263742012-08-21 15:40:12 -0700354 /*
355 * Should be locked on mUsers before calling this.
356 */
357 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700358 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700359 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800360 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
362 return null;
363 }
364 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700365 }
366
Amith Yamasani13593602012-03-22 16:16:17 -0700367 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700368 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700369 return ArrayUtils.contains(mUserIds, userId);
370 }
371 }
372
Amith Yamasani258848d2012-08-10 17:06:33 -0700373 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700374 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700375 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700376 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700377 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700378 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700379 if (info == null || info.partial) {
380 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
381 return;
382 }
Amith Yamasani13593602012-03-22 16:16:17 -0700383 if (name != null && !name.equals(info.name)) {
384 info.name = name;
385 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700387 }
388 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700389 if (changed) {
390 sendUserInfoChangedBroadcast(userId);
391 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700392 }
393
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700395 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700396 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700397 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700398 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700399 if (info == null || info.partial) {
400 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
401 return;
402 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700403 writeBitmapLocked(info, bitmap);
404 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700405 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700406 sendUserInfoChangedBroadcast(userId);
407 }
408
409 private void sendUserInfoChangedBroadcast(int userId) {
410 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
411 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
412 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700413 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700414 }
415
Amith Yamasani258848d2012-08-10 17:06:33 -0700416 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700417 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700418 synchronized (mPackagesLock) {
419 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 if (info == null || info.partial) {
421 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
422 return null;
423 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100424 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
425 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
426 || callingGroupId != info.profileGroupId) {
427 checkManageUsersPermission("get the icon of a user who is not related");
428 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700429 if (info.iconPath == null) {
430 return null;
431 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700432 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700433 }
434 }
435
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700436 public void makeInitialized(int userId) {
437 checkManageUsersPermission("makeInitialized");
438 synchronized (mPackagesLock) {
439 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 if (info == null || info.partial) {
441 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
442 }
443 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700444 info.flags |= UserInfo.FLAG_INITIALIZED;
445 writeUserLocked(info);
446 }
447 }
448 }
449
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800450 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530451 public Bundle getDefaultGuestRestrictions() {
452 checkManageUsersPermission("getDefaultGuestRestrictions");
453 synchronized (mPackagesLock) {
454 return new Bundle(mGuestRestrictions);
455 }
456 }
457
458 @Override
459 public void setDefaultGuestRestrictions(Bundle restrictions) {
460 checkManageUsersPermission("setDefaultGuestRestrictions");
461 synchronized (mPackagesLock) {
462 mGuestRestrictions.clear();
463 mGuestRestrictions.putAll(restrictions);
464 writeUserListLocked();
465 }
466 }
467
468 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800469 public Bundle getUserRestrictions(int userId) {
470 // checkManageUsersPermission("getUserRestrictions");
471
472 synchronized (mPackagesLock) {
473 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700474 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800475 }
476 }
477
478 @Override
479 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700480 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700481 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800482
483 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700484 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800485 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400486 long token = Binder.clearCallingIdentity();
487 try {
488 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
489 } catch (RemoteException e) {
490 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
491 } finally {
492 Binder.restoreCallingIdentity(token);
493 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800494 writeUserLocked(mUsers.get(userId));
495 }
496 }
497
Amith Yamasani258848d2012-08-10 17:06:33 -0700498 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700499 * Check if we've hit the limit of how many users can be created.
500 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700501 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700502 int aliveUserCount = 0;
503 final int totalUserCount = mUsers.size();
504 // Skip over users being removed
505 for (int i = 0; i < totalUserCount; i++) {
506 UserInfo user = mUsers.valueAt(i);
507 if (!mRemovingUserIds.get(user.id)) {
508 aliveUserCount++;
509 }
510 }
511 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700512 }
513
514 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700515 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700516 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700517 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700518 *
519 * @param message used as message if SecurityException is thrown
520 * @throws SecurityException if the caller is not system or root
521 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700522 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700523 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700524 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400525 && ActivityManager.checkComponentPermission(
526 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700527 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
528 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
529 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400530 }
531
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700532 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700533 try {
534 File dir = new File(mUsersDir, Integer.toString(info.id));
535 File file = new File(dir, USER_PHOTO_FILENAME);
536 if (!dir.exists()) {
537 dir.mkdir();
538 FileUtils.setPermissions(
539 dir.getPath(),
540 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
541 -1, -1);
542 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700543 FileOutputStream os;
544 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700545 info.iconPath = file.getAbsolutePath();
546 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700547 try {
548 os.close();
549 } catch (IOException ioe) {
550 // What the ... !
551 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700553 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700554 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700555 }
556
Amith Yamasani0b285492011-04-14 17:35:23 -0700557 /**
558 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
559 * cache it elsewhere.
560 * @return the array of user ids.
561 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700562 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700563 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700564 return mUserIds;
565 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700566 }
567
Dianne Hackborn4428e172012-08-24 17:43:05 -0700568 int[] getUserIdsLPr() {
569 return mUserIds;
570 }
571
Amith Yamasani13593602012-03-22 16:16:17 -0700572 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700573 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700574 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700575 return;
576 }
577 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700578 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700579 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700580 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700581 XmlPullParser parser = Xml.newPullParser();
582 parser.setInput(fis, null);
583 int type;
584 while ((type = parser.next()) != XmlPullParser.START_TAG
585 && type != XmlPullParser.END_DOCUMENT) {
586 ;
587 }
588
589 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700590 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700591 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700592 return;
593 }
594
Amith Yamasani2a003292012-08-14 18:25:45 -0700595 mNextSerialNumber = -1;
596 if (parser.getName().equals(TAG_USERS)) {
597 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
598 if (lastSerialNumber != null) {
599 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
600 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700601 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
602 if (versionNumber != null) {
603 mUserVersion = Integer.parseInt(versionNumber);
604 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700605 }
606
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700607 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530608 if (type == XmlPullParser.START_TAG) {
609 final String name = parser.getName();
610 if (name.equals(TAG_USER)) {
611 String id = parser.getAttributeValue(null, ATTR_ID);
612 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700613
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530614 if (user != null) {
615 mUsers.put(user.id, user);
616 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
617 mNextSerialNumber = user.id + 1;
618 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700619 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530620 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
621 mGuestRestrictions.clear();
622 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700623 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700624 }
625 }
Amith Yamasani13593602012-03-22 16:16:17 -0700626 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700627 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700628 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700629 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700630 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700631 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800632 } finally {
633 if (fis != null) {
634 try {
635 fis.close();
636 } catch (IOException e) {
637 }
638 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700639 }
640 }
641
Amith Yamasani6f34b412012-10-22 18:19:27 -0700642 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800643 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700644 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700645 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700646 int userVersion = mUserVersion;
647 if (userVersion < 1) {
648 // Assign a proper name for the owner, if not initialized correctly before
649 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
650 if ("Primary".equals(user.name)) {
651 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
652 writeUserLocked(user);
653 }
654 userVersion = 1;
655 }
656
Amith Yamasanibc9625052012-11-15 14:39:18 -0800657 if (userVersion < 2) {
658 // Owner should be marked as initialized
659 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
660 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
661 user.flags |= UserInfo.FLAG_INITIALIZED;
662 writeUserLocked(user);
663 }
664 userVersion = 2;
665 }
666
Amith Yamasani350962c2013-08-06 11:18:53 -0700667
Amith Yamasani5e486f52013-08-07 11:06:44 -0700668 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700669 userVersion = 4;
670 }
671
Amith Yamasani6f34b412012-10-22 18:19:27 -0700672 if (userVersion < USER_VERSION) {
673 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
674 + USER_VERSION);
675 } else {
676 mUserVersion = userVersion;
677 writeUserListLocked();
678 }
679 }
680
Amith Yamasani13593602012-03-22 16:16:17 -0700681 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700682 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800683 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700684 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700685 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700686 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700687 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400688 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800689
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500690 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800691 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
692
Amith Yamasani13593602012-03-22 16:16:17 -0700693 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700694
Amith Yamasani13593602012-03-22 16:16:17 -0700695 writeUserListLocked();
696 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700697 }
698
699 /*
700 * Writes the user file in this format:
701 *
702 * <user flags="20039023" id="0">
703 * <name>Primary</name>
704 * </user>
705 */
Amith Yamasani13593602012-03-22 16:16:17 -0700706 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700707 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700708 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700709 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700710 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700711 final BufferedOutputStream bos = new BufferedOutputStream(fos);
712
713 // XmlSerializer serializer = XmlUtils.serializerInstance();
714 final XmlSerializer serializer = new FastXmlSerializer();
715 serializer.setOutput(bos, "utf-8");
716 serializer.startDocument(null, true);
717 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
718
719 serializer.startTag(null, TAG_USER);
720 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700721 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700723 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
724 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
725 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700726 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
727 if (pinState != null) {
728 if (pinState.salt != 0) {
729 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
730 }
731 if (pinState.pinHash != null) {
732 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
733 }
734 if (pinState.failedAttempts != 0) {
735 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
736 Integer.toString(pinState.failedAttempts));
737 serializer.attribute(null, ATTR_LAST_RETRY_MS,
738 Long.toString(pinState.lastAttemptTime));
739 }
740 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700741 if (userInfo.iconPath != null) {
742 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
743 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700744 if (userInfo.partial) {
745 serializer.attribute(null, ATTR_PARTIAL, "true");
746 }
Kenny Guy2a764942014-04-02 13:29:20 +0100747 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
748 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
749 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000750 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700751
752 serializer.startTag(null, TAG_NAME);
753 serializer.text(userInfo.name);
754 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800755 Bundle restrictions = mUserRestrictions.get(userInfo.id);
756 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530757 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800758 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 serializer.endTag(null, TAG_USER);
760
761 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700762 userFile.finishWrite(fos);
763 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700764 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 }
767 }
768
769 /*
770 * Writes the user list file in this format:
771 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700772 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 * <user id="0"></user>
774 * <user id="2"></user>
775 * </users>
776 */
Amith Yamasani13593602012-03-22 16:16:17 -0700777 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700778 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700779 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700781 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700782 final BufferedOutputStream bos = new BufferedOutputStream(fos);
783
784 // XmlSerializer serializer = XmlUtils.serializerInstance();
785 final XmlSerializer serializer = new FastXmlSerializer();
786 serializer.setOutput(bos, "utf-8");
787 serializer.startDocument(null, true);
788 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
789
790 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700791 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700792 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700793
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530794 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
795 writeRestrictionsLocked(serializer, mGuestRestrictions);
796 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700797 for (int i = 0; i < mUsers.size(); i++) {
798 UserInfo user = mUsers.valueAt(i);
799 serializer.startTag(null, TAG_USER);
800 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
801 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 }
803
804 serializer.endTag(null, TAG_USERS);
805
806 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700807 userListFile.finishWrite(fos);
808 } catch (Exception e) {
809 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700810 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811 }
812 }
813
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530814 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
815 throws IOException {
816 serializer.startTag(null, TAG_RESTRICTIONS);
817 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
818 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
819 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
820 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
821 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
822 writeBoolean(serializer, restrictions,
823 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
824 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
825 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
826 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
827 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
828 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
829 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
830 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
831 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
832 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
833 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
834 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
835 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
836 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
837 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
838 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
839 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
840 writeBoolean(serializer, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400841 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530842 serializer.endTag(null, TAG_RESTRICTIONS);
843 }
844
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800845 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700846 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700847 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700848 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700849 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700850 long creationTime = 0L;
851 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700852 long salt = 0L;
853 String pinHash = null;
854 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100855 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700856 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700857 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800858 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700859
860 FileInputStream fis = null;
861 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700862 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700863 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700864 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865 XmlPullParser parser = Xml.newPullParser();
866 parser.setInput(fis, null);
867 int type;
868 while ((type = parser.next()) != XmlPullParser.START_TAG
869 && type != XmlPullParser.END_DOCUMENT) {
870 ;
871 }
872
873 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700874 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700875 return null;
876 }
877
878 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700879 int storedId = readIntAttribute(parser, ATTR_ID, -1);
880 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700881 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700882 return null;
883 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700884 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
885 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700886 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700887 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
888 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700889 salt = readLongAttribute(parser, ATTR_SALT, 0L);
890 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
891 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
892 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100893 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
894 UserInfo.NO_PROFILE_GROUP_ID);
895 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
896 // This attribute was added and renamed during development of L.
897 // TODO Remove upgrade path by 1st May 2014
898 profileGroupId = readIntAttribute(parser, "relatedGroupId",
899 UserInfo.NO_PROFILE_GROUP_ID);
900 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700901 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
902 if ("true".equals(valueString)) {
903 partial = true;
904 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700905
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800906 int outerDepth = parser.getDepth();
907 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
908 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
909 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
910 continue;
911 }
912 String tag = parser.getName();
913 if (TAG_NAME.equals(tag)) {
914 type = parser.next();
915 if (type == XmlPullParser.TEXT) {
916 name = parser.getText();
917 }
918 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530919 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700920 }
921 }
922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700924 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700925 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700926 userInfo.creationTime = creationTime;
927 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700928 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100929 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800930 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700931 if (salt != 0L) {
932 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
933 if (pinState == null) {
934 pinState = new RestrictionsPinState();
935 mRestrictionsPinStates.put(id, pinState);
936 }
937 pinState.salt = salt;
938 pinState.pinHash = pinHash;
939 pinState.failedAttempts = failedAttempts;
940 pinState.lastAttemptTime = lastAttemptTime;
941 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700942 return userInfo;
943
944 } catch (IOException ioe) {
945 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800946 } finally {
947 if (fis != null) {
948 try {
949 fis.close();
950 } catch (IOException e) {
951 }
952 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700953 }
954 return null;
955 }
956
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530957 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
958 throws IOException {
959 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
960 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
961 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
962 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
963 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
964 readBoolean(parser, restrictions,
965 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
966 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
967 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
968 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
969 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
970 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
971 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
972 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
973 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
974 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
975 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
976 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
977 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
978 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
979 readBoolean(parser, restrictions,
980 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
981 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
982 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
983 readBoolean(parser, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400984 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530985 }
986
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800987 private void readBoolean(XmlPullParser parser, Bundle restrictions,
988 String restrictionKey) {
989 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700990 if (value != null) {
991 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
992 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800993 }
994
995 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
996 throws IOException {
997 if (restrictions.containsKey(restrictionKey)) {
998 xml.attribute(null, restrictionKey,
999 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1000 }
1001 }
1002
Amith Yamasani920ace02012-09-20 22:15:37 -07001003 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1004 String valueString = parser.getAttributeValue(null, attr);
1005 if (valueString == null) return defaultValue;
1006 try {
1007 return Integer.parseInt(valueString);
1008 } catch (NumberFormatException nfe) {
1009 return defaultValue;
1010 }
1011 }
1012
1013 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1014 String valueString = parser.getAttributeValue(null, attr);
1015 if (valueString == null) return defaultValue;
1016 try {
1017 return Long.parseLong(valueString);
1018 } catch (NumberFormatException nfe) {
1019 return defaultValue;
1020 }
1021 }
1022
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001023 private boolean isPackageInstalled(String pkg, int userId) {
1024 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1025 PackageManager.GET_UNINSTALLED_PACKAGES,
1026 userId);
1027 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1028 return false;
1029 }
1030 return true;
1031 }
1032
Amith Yamasanib82add22013-07-09 11:24:44 -07001033 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001034 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1035 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001036 * Does not do any permissions checking.
1037 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001038 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001039 synchronized (mPackagesLock) {
1040 File dir = Environment.getUserSystemDirectory(userId);
1041 String[] files = dir.list();
1042 if (files == null) return;
1043 for (String fileName : files) {
1044 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1045 File resFile = new File(dir, fileName);
1046 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001047 if (all) {
1048 resFile.delete();
1049 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001050 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001051 if (!isPackageInstalled(pkg, userId)) {
1052 resFile.delete();
1053 }
1054 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001055 }
1056 }
1057 }
1058 }
1059 }
1060
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001061 /**
1062 * Removes the app restrictions file for a specific package and user id, if it exists.
1063 */
1064 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1065 synchronized (mPackagesLock) {
1066 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001067 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001068 if (resFile.exists()) {
1069 resFile.delete();
1070 }
1071 }
1072 }
1073
Kenny Guya52dc3e2014-02-11 15:33:14 +00001074 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001075 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001076 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001077 if (userId != UserHandle.USER_OWNER) {
1078 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001079 return null;
1080 }
Kenny Guy2a764942014-04-02 13:29:20 +01001081 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001082 }
1083
Amith Yamasani258848d2012-08-10 17:06:33 -07001084 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001085 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001086 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001087 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001088 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001089
Jessica Hummelbe81c802014-04-22 15:49:22 +01001090 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001091 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1092 UserManager.DISALLOW_ADD_USER, false)) {
1093 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1094 return null;
1095 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001096 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001097 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001098 try {
1099 synchronized (mInstallLock) {
1100 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001101 UserInfo parent = null;
1102 if (parentId != UserHandle.USER_NULL) {
1103 parent = getUserInfoLocked(parentId);
1104 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001105 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001106 if (isUserLimitReachedLocked()) return null;
1107 int userId = getNextAvailableIdLocked();
1108 userInfo = new UserInfo(userId, name, null, flags);
1109 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1110 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001111 long now = System.currentTimeMillis();
1112 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001113 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001114 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001115 mUsers.put(userId, userInfo);
1116 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001117 if (parent != null) {
1118 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1119 parent.profileGroupId = parent.id;
1120 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001121 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001122 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001123 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001124 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001125 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001126 userInfo.partial = false;
1127 writeUserLocked(userInfo);
1128 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001129 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001130 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001131 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001132 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001133 if (userInfo != null) {
1134 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1135 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1136 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1137 android.Manifest.permission.MANAGE_USERS);
1138 }
1139 } finally {
1140 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001141 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001142 return userInfo;
1143 }
1144
Amith Yamasani0b285492011-04-14 17:35:23 -07001145 /**
1146 * Removes a user and all data directories created for that user. This method should be called
1147 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001148 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001149 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001150 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001151 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001152 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1153 UserManager.DISALLOW_REMOVE_USER, false)) {
1154 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1155 return false;
1156 }
1157
Kenny Guyee58b4f2014-05-23 15:19:53 +01001158 long ident = Binder.clearCallingIdentity();
1159 try {
1160 final UserInfo user;
1161 synchronized (mPackagesLock) {
1162 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001163 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001164 return false;
1165 }
1166 mRemovingUserIds.put(userHandle, true);
1167 try {
1168 mAppOpsService.removeUser(userHandle);
1169 } catch (RemoteException e) {
1170 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1171 }
1172 // Set this to a partially created user, so that the user will be purged
1173 // on next startup, in case the runtime stops now before stopping and
1174 // removing the user completely.
1175 user.partial = true;
1176 // Mark it as disabled, so that it isn't returned any more when
1177 // profiles are queried.
1178 user.flags |= UserInfo.FLAG_DISABLED;
1179 writeUserLocked(user);
1180 }
1181
1182 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1183 && user.isManagedProfile()) {
1184 // Send broadcast to notify system that the user removed was a
1185 // managed user.
1186 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1187 }
1188
1189 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1190 int res;
1191 try {
1192 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1193 new IStopUserCallback.Stub() {
1194 @Override
1195 public void userStopped(int userId) {
1196 finishRemoveUser(userId);
1197 }
1198 @Override
1199 public void userStopAborted(int userId) {
1200 }
1201 });
1202 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001203 return false;
1204 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001205 return res == ActivityManager.USER_OP_SUCCESS;
1206 } finally {
1207 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001208 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001209 }
1210
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001211 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001212 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001213 // Let other services shutdown any activity and clean up their state before completely
1214 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001215 long ident = Binder.clearCallingIdentity();
1216 try {
1217 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1218 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001219 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1220 android.Manifest.permission.MANAGE_USERS,
1221
1222 new BroadcastReceiver() {
1223 @Override
1224 public void onReceive(Context context, Intent intent) {
1225 if (DBG) {
1226 Slog.i(LOG_TAG,
1227 "USER_REMOVED broadcast sent, cleaning up user data "
1228 + userHandle);
1229 }
1230 new Thread() {
1231 public void run() {
1232 synchronized (mInstallLock) {
1233 synchronized (mPackagesLock) {
1234 removeUserStateLocked(userHandle);
1235 }
1236 }
1237 }
1238 }.start();
1239 }
1240 },
1241
1242 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001243 } finally {
1244 Binder.restoreCallingIdentity(ident);
1245 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001246 }
1247
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001248 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001249 // Cleanup package manager settings
1250 mPm.cleanUpUserLILPw(userHandle);
1251
1252 // Remove this user from the list
1253 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001254
1255 // Have user ID linger for several seconds to let external storage VFS
1256 // cache entries expire. This must be greater than the 'entry_valid'
1257 // timeout used by the FUSE daemon.
1258 mHandler.postDelayed(new Runnable() {
1259 @Override
1260 public void run() {
1261 synchronized (mPackagesLock) {
1262 mRemovingUserIds.delete(userHandle);
1263 }
1264 }
1265 }, MINUTE_IN_MILLIS);
1266
Amith Yamasani655d0e22013-06-12 14:19:10 -07001267 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001268 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001269 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001270 userFile.delete();
1271 // Update the user list
1272 writeUserListLocked();
1273 updateUserIdsLocked();
1274 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1275 }
1276
Amith Yamasani61f57372012-08-31 12:12:28 -07001277 private void removeDirectoryRecursive(File parent) {
1278 if (parent.isDirectory()) {
1279 String[] files = parent.list();
1280 for (String filename : files) {
1281 File child = new File(parent, filename);
1282 removeDirectoryRecursive(child);
1283 }
1284 }
1285 parent.delete();
1286 }
1287
Kenny Guyf8d3a232014-05-15 16:09:52 +01001288 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001289 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001290 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1291 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001292 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1293 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001294 }
1295
Amith Yamasani2a003292012-08-14 18:25:45 -07001296 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001297 public Bundle getApplicationRestrictions(String packageName) {
1298 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1299 }
1300
1301 @Override
1302 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001303 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001304 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001305 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001306 }
1307 synchronized (mPackagesLock) {
1308 // Read the restrictions from XML
1309 return readApplicationRestrictionsLocked(packageName, userId);
1310 }
1311 }
1312
1313 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001314 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001315 int userId) {
1316 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001317 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001318 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001319 }
1320 synchronized (mPackagesLock) {
1321 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001322 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001323 }
Robin Lee66e5d962014-04-09 16:44:21 +01001324
1325 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1326 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1327 changeIntent.setPackage(packageName);
1328 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1329 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001330 }
1331
Amith Yamasani655d0e22013-06-12 14:19:10 -07001332 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001333 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001334 checkManageUsersPermission("Only system can modify the restrictions pin");
1335 int userId = UserHandle.getCallingUserId();
1336 synchronized (mPackagesLock) {
1337 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1338 if (pinState == null) {
1339 pinState = new RestrictionsPinState();
1340 }
1341 if (newPin == null) {
1342 pinState.salt = 0;
1343 pinState.pinHash = null;
1344 } else {
1345 try {
1346 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1347 } catch (NoSuchAlgorithmException e) {
1348 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1349 }
1350 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1351 pinState.failedAttempts = 0;
1352 }
1353 mRestrictionsPinStates.put(userId, pinState);
1354 writeUserLocked(mUsers.get(userId));
1355 }
1356 return true;
1357 }
1358
1359 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001360 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001361 checkManageUsersPermission("Only system can verify the restrictions pin");
1362 int userId = UserHandle.getCallingUserId();
1363 synchronized (mPackagesLock) {
1364 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1365 // If there's no pin set, return error code
1366 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1367 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1368 } else if (pin == null) {
1369 // If just checking if user can be prompted, return remaining time
1370 int waitTime = getRemainingTimeForPinAttempt(pinState);
1371 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1372 return waitTime;
1373 } else {
1374 int waitTime = getRemainingTimeForPinAttempt(pinState);
1375 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1376 if (waitTime > 0) {
1377 return waitTime;
1378 }
1379 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1380 pinState.failedAttempts = 0;
1381 writeUserLocked(mUsers.get(userId));
1382 return UserManager.PIN_VERIFICATION_SUCCESS;
1383 } else {
1384 pinState.failedAttempts++;
1385 pinState.lastAttemptTime = System.currentTimeMillis();
1386 writeUserLocked(mUsers.get(userId));
1387 return waitTime;
1388 }
1389 }
1390 }
1391 }
1392
1393 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1394 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1395 BACKOFF_TIMES.length - 1);
1396 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1397 BACKOFF_TIMES[backoffIndex] : 0;
1398 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1399 0);
1400 }
1401
1402 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001403 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001404 int userId = UserHandle.getCallingUserId();
1405 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001406 return hasRestrictionsPinLocked(userId);
1407 }
1408 }
1409
1410 private boolean hasRestrictionsPinLocked(int userId) {
1411 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1412 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1413 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001414 }
1415 return true;
1416 }
1417
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001418 @Override
1419 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001420 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001421 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001422 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001423 }
1424
Amith Yamasani5e486f52013-08-07 11:06:44 -07001425 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001426 synchronized (mPackagesLock) {
1427 // Remove all user restrictions
1428 setUserRestrictions(new Bundle(), userHandle);
1429 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001430 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001431 // Remove any app restrictions
1432 cleanAppRestrictions(userHandle, true);
1433 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001434 if (unblockApps) {
1435 unblockAllAppsForUser(userHandle);
1436 }
1437 }
1438
1439 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001440 mHandler.post(new Runnable() {
1441 @Override
1442 public void run() {
1443 List<ApplicationInfo> apps =
1444 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1445 userHandle).getList();
1446 final long ident = Binder.clearCallingIdentity();
1447 try {
1448 for (ApplicationInfo appInfo : apps) {
1449 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1450 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1451 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1452 userHandle);
1453 }
1454 }
1455 } finally {
1456 Binder.restoreCallingIdentity(ident);
1457 }
1458 }
1459 });
1460 }
1461
Amith Yamasani655d0e22013-06-12 14:19:10 -07001462 /*
1463 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1464 * Not the most secure, but it is at least a second level of protection. First level is that
1465 * the file is in a location only readable by the system process.
1466 * @param password the password.
1467 * @param salt the randomly generated salt
1468 * @return the hash of the pattern in a String.
1469 */
1470 private String passwordToHash(String password, long salt) {
1471 if (password == null) {
1472 return null;
1473 }
1474 String algo = null;
1475 String hashed = salt + password;
1476 try {
1477 byte[] saltedPassword = (password + salt).getBytes();
1478 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1479 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1480 hashed = toHex(sha1) + toHex(md5);
1481 } catch (NoSuchAlgorithmException e) {
1482 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1483 }
1484 return hashed;
1485 }
1486
1487 private static String toHex(byte[] ary) {
1488 final String hex = "0123456789ABCDEF";
1489 String ret = "";
1490 for (int i = 0; i < ary.length; i++) {
1491 ret += hex.charAt((ary[i] >> 4) & 0xf);
1492 ret += hex.charAt(ary[i] & 0xf);
1493 }
1494 return ret;
1495 }
1496
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001497 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001498 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001499 try {
1500 return mContext.getPackageManager().getApplicationInfo(packageName,
1501 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1502 } catch (NameNotFoundException nnfe) {
1503 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001504 } finally {
1505 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001506 }
1507 }
1508
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001509 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001510 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001511 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001512 final ArrayList<String> values = new ArrayList<String>();
1513
1514 FileInputStream fis = null;
1515 try {
1516 AtomicFile restrictionsFile =
1517 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001518 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001519 fis = restrictionsFile.openRead();
1520 XmlPullParser parser = Xml.newPullParser();
1521 parser.setInput(fis, null);
1522 int type;
1523 while ((type = parser.next()) != XmlPullParser.START_TAG
1524 && type != XmlPullParser.END_DOCUMENT) {
1525 ;
1526 }
1527
1528 if (type != XmlPullParser.START_TAG) {
1529 Slog.e(LOG_TAG, "Unable to read restrictions file "
1530 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001531 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001532 }
1533
1534 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1535 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1536 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001537 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1539 if (multiple != null) {
1540 int count = Integer.parseInt(multiple);
1541 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1542 if (type == XmlPullParser.START_TAG
1543 && parser.getName().equals(TAG_VALUE)) {
1544 values.add(parser.nextText().trim());
1545 count--;
1546 }
1547 }
1548 String [] valueStrings = new String[values.size()];
1549 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001550 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001551 } else {
1552 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001553 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1554 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1555 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1556 restrictions.putInt(key, Integer.parseInt(value));
1557 } else {
1558 restrictions.putString(key, value);
1559 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001560 }
1561 }
1562 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001563 } catch (IOException ioe) {
1564 } catch (XmlPullParserException pe) {
1565 } finally {
1566 if (fis != null) {
1567 try {
1568 fis.close();
1569 } catch (IOException e) {
1570 }
1571 }
1572 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001573 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001574 }
1575
1576 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001577 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001578 FileOutputStream fos = null;
1579 AtomicFile restrictionsFile = new AtomicFile(
1580 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001581 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 try {
1583 fos = restrictionsFile.startWrite();
1584 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1585
1586 // XmlSerializer serializer = XmlUtils.serializerInstance();
1587 final XmlSerializer serializer = new FastXmlSerializer();
1588 serializer.setOutput(bos, "utf-8");
1589 serializer.startDocument(null, true);
1590 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1591
1592 serializer.startTag(null, TAG_RESTRICTIONS);
1593
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001594 for (String key : restrictions.keySet()) {
1595 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001596 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001597 serializer.attribute(null, ATTR_KEY, key);
1598
1599 if (value instanceof Boolean) {
1600 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1601 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001602 } else if (value instanceof Integer) {
1603 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1604 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001605 } else if (value == null || value instanceof String) {
1606 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1607 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001609 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1610 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001611 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001612 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001613 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001614 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001615 serializer.endTag(null, TAG_VALUE);
1616 }
1617 }
1618 serializer.endTag(null, TAG_ENTRY);
1619 }
1620
1621 serializer.endTag(null, TAG_RESTRICTIONS);
1622
1623 serializer.endDocument();
1624 restrictionsFile.finishWrite(fos);
1625 } catch (Exception e) {
1626 restrictionsFile.failWrite(fos);
1627 Slog.e(LOG_TAG, "Error writing application restrictions list");
1628 }
1629 }
1630
1631 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001632 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001633 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001634 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001635 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001636 }
1637 }
1638
1639 @Override
1640 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001641 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001642 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001643 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001644 }
1645 // Not found
1646 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001647 }
1648 }
1649
Amith Yamasani0b285492011-04-14 17:35:23 -07001650 /**
1651 * Caches the list of user ids in an array, adjusting the array size when necessary.
1652 */
Amith Yamasani13593602012-03-22 16:16:17 -07001653 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001654 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001655 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001656 if (!mUsers.valueAt(i).partial) {
1657 num++;
1658 }
1659 }
Amith Yamasani16389312012-10-17 21:20:14 -07001660 final int[] newUsers = new int[num];
1661 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001662 for (int i = 0; i < mUsers.size(); i++) {
1663 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001664 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001665 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001666 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001667 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001668 }
1669
1670 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001671 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001672 * @param userId the user that was just foregrounded
1673 */
1674 public void userForeground(int userId) {
1675 synchronized (mPackagesLock) {
1676 UserInfo user = mUsers.get(userId);
1677 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001678 if (user == null || user.partial) {
1679 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1680 return;
1681 }
1682 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001683 user.lastLoggedInTime = now;
1684 writeUserLocked(user);
1685 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001686 // If this is not a restricted profile and there is no restrictions pin, clean up
1687 // all restrictions files that might have been left behind, else clean up just the
1688 // ones with uninstalled packages
1689 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1690 final long salt = pinState == null ? 0 : pinState.salt;
1691 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001692 }
1693 }
1694
1695 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001696 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001697 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1698 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001699 * @return
1700 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001701 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001702 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001703 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001704 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001705 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001706 break;
1707 }
1708 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001709 }
Amith Yamasani195263742012-08-21 15:40:12 -07001710 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001711 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001712 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001713
Amith Yamasanifc95e702013-09-26 13:20:17 -07001714 private String packageToRestrictionsFileName(String packageName) {
1715 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1716 }
1717
1718 private String restrictionsFileNameToPackage(String fileName) {
1719 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1720 (int) (fileName.length() - XML_SUFFIX.length()));
1721 }
1722
Amith Yamasani920ace02012-09-20 22:15:37 -07001723 @Override
1724 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1725 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1726 != PackageManager.PERMISSION_GRANTED) {
1727 pw.println("Permission Denial: can't dump UserManager from from pid="
1728 + Binder.getCallingPid()
1729 + ", uid=" + Binder.getCallingUid()
1730 + " without permission "
1731 + android.Manifest.permission.DUMP);
1732 return;
1733 }
1734
1735 long now = System.currentTimeMillis();
1736 StringBuilder sb = new StringBuilder();
1737 synchronized (mPackagesLock) {
1738 pw.println("Users:");
1739 for (int i = 0; i < mUsers.size(); i++) {
1740 UserInfo user = mUsers.valueAt(i);
1741 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001742 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001743 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001744 if (user.partial) pw.print(" <partial>");
1745 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001746 pw.print(" Created: ");
1747 if (user.creationTime == 0) {
1748 pw.println("<unknown>");
1749 } else {
1750 sb.setLength(0);
1751 TimeUtils.formatDuration(now - user.creationTime, sb);
1752 sb.append(" ago");
1753 pw.println(sb);
1754 }
1755 pw.print(" Last logged in: ");
1756 if (user.lastLoggedInTime == 0) {
1757 pw.println("<unknown>");
1758 } else {
1759 sb.setLength(0);
1760 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1761 sb.append(" ago");
1762 pw.println(sb);
1763 }
1764 }
1765 }
1766 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001767
1768 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1769 @Override
1770 public void onPackageRemoved(String pkg, int uid) {
1771 final int userId = this.getChangingUserId();
1772 // Package could be disappearing because it is being blocked, so also check if
1773 // it has been uninstalled.
1774 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1775 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1776 cleanAppRestrictionsForPackage(pkg, userId);
1777 }
1778 }
1779 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001780}