blob: ebcbecdd7fe592cbb77ecb2586f81819fc3d7950 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080032import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.os.Environment;
34import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080035import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080037import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010038import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070039import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070045import android.os.storage.StorageManager;
46import android.os.storage.VolumeInfo;
47import android.system.ErrnoException;
48import android.system.Os;
49import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070050import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070051import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Slog;
53import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070055import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import android.util.Xml;
57
Fyodor Kupolovb5013302015-04-17 17:59:14 -070058import com.google.android.collect.Sets;
59
Fyodor Kupolov262f9952015-03-23 18:55:11 -070060import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040061import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080062import com.android.internal.util.ArrayUtils;
63import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070064import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68import org.xmlpull.v1.XmlSerializer;
69
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import java.io.BufferedOutputStream;
71import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070072import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070074import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.io.FileOutputStream;
76import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070077import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010078import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.util.ArrayList;
80import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070081import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082
Fyodor Kupolov262f9952015-03-23 18:55:11 -070083import libcore.io.IoUtils;
84
Amith Yamasani258848d2012-08-10 17:06:33 -070085public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070086
Amith Yamasani2a003292012-08-14 18:25:45 -070087 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088
Amith Yamasani16389312012-10-17 21:20:14 -070089 private static final boolean DBG = false;
90
Amith Yamasani4b2e9342011-03-31 12:38:53 -070091 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070093 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070095 private static final String ATTR_CREATION_TIME = "created";
96 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070097 private static final String ATTR_SERIAL_NO = "serialNumber";
98 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070099 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700100 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700101 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100102 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530103 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800106 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800107 private static final String TAG_ENTRY = "entry";
108 private static final String TAG_VALUE = "value";
109 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700110 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800111 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700113 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
114 private static final String ATTR_TYPE_STRING = "s";
115 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700116 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700117 private static final String ATTR_TYPE_BUNDLE = "B";
118 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700119
Amith Yamasani0b285492011-04-14 17:35:23 -0700120 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700122 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100123 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800125 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700126 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127
Amith Yamasani634cf312012-10-04 17:34:21 -0700128 private static final int MIN_USER_ID = 10;
129
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700130 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700131
Amith Yamasani920ace02012-09-20 22:15:37 -0700132 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
133
Amith Yamasani95ab7842014-08-11 17:09:26 -0700134 // Maximum number of managed profiles permitted is 1. This cannot be increased
135 // without first making sure that the rest of the framework is prepared for it.
136 private static final int MAX_MANAGED_PROFILES = 1;
137
Andres Moralesc5548c02015-08-05 10:23:12 -0700138 /**
139 * Flag indicating whether device credentials are shared among same-user profiles.
140 */
141 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
142
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700143 // Set of user restrictions, which can only be enforced by the system
144 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
145 UserManager.DISALLOW_RECORD_AUDIO);
146
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800147 static final int WRITE_USER_MSG = 1;
148 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530149
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700150 private static final String XATTR_SERIAL = "user.serial";
151
Dianne Hackborn4428e172012-08-24 17:43:05 -0700152 private final Context mContext;
153 private final PackageManagerService mPm;
154 private final Object mInstallLock;
155 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800157 private final Handler mHandler;
158
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700159 private final File mUsersDir;
160 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800162 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800163 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530164 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800165
166 /**
167 * Set of user IDs being actively removed. Removed IDs linger in this set
168 * for several seconds to work around a VFS caching issue.
169 */
170 // @GuardedBy("mPackagesLock")
171 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172
Amith Yamasani0b285492011-04-14 17:35:23 -0700173 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700174 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700175 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700176
Jason Monk62062992014-05-06 09:55:28 -0400177 private IAppOpsService mAppOpsService;
178
Amith Yamasani258848d2012-08-10 17:06:33 -0700179 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 public static UserManagerService getInstance() {
182 synchronized (UserManagerService.class) {
183 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700185 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186
187 /**
188 * Available for testing purposes.
189 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 }
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 /**
195 * Called by package manager to create the service. This is closely
196 * associated with the package manager, and the given lock is the
197 * package manager's own lock.
198 */
199 UserManagerService(Context context, PackageManagerService pm,
200 Object installLock, Object packagesLock) {
201 this(context, pm, installLock, packagesLock,
202 Environment.getDataDirectory(),
203 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700204 }
205
Dianne Hackborn4428e172012-08-24 17:43:05 -0700206 /**
207 * Available for testing purposes.
208 */
209 private UserManagerService(Context context, PackageManagerService pm,
210 Object installLock, Object packagesLock,
211 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700212 mContext = context;
213 mPm = pm;
214 mInstallLock = installLock;
215 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800216 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 synchronized (mInstallLock) {
218 synchronized (mPackagesLock) {
219 mUsersDir = new File(dataDir, USER_INFO_DIR);
220 mUsersDir.mkdirs();
221 // Make zeroth user directory, for services to migrate their files to that location
222 File userZeroDir = new File(mUsersDir, "0");
223 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700224 FileUtils.setPermissions(mUsersDir.toString(),
225 FileUtils.S_IRWXU|FileUtils.S_IRWXG
226 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
227 -1, -1);
228 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800229 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700231 sInstance = this;
232 }
233 }
234 }
235
236 void systemReady() {
237 synchronized (mInstallLock) {
238 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700239 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700240 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
241 for (int i = 0; i < mUsers.size(); i++) {
242 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700243 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700244 partials.add(ui);
245 }
246 }
247 for (int i = 0; i < partials.size(); i++) {
248 UserInfo ui = partials.get(i);
249 Slog.w(LOG_TAG, "Removing partially created user #" + i
250 + " (name=" + ui.name + ")");
251 removeUserStateLocked(ui.id);
252 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700253 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700254 }
Amith Yamasani06bf8242015-05-08 16:36:21 -0700255 onUserForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400256 mAppOpsService = IAppOpsService.Stub.asInterface(
257 ServiceManager.getService(Context.APP_OPS_SERVICE));
258 for (int i = 0; i < mUserIds.length; ++i) {
259 try {
260 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
261 } catch (RemoteException e) {
262 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
263 }
264 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700265 }
266
267 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700268 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700269 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700270 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700271 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
272 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 UserInfo ui = mUsers.valueAt(i);
274 if (ui.partial) {
275 continue;
276 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800277 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700278 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700279 }
Amith Yamasani13593602012-03-22 16:16:17 -0700280 }
281 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700282 }
Amith Yamasani13593602012-03-22 16:16:17 -0700283 }
284
Amith Yamasani258848d2012-08-10 17:06:33 -0700285 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100286 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800287 if (userId != UserHandle.getCallingUserId()) {
288 checkManageUsersPermission("getting profiles related to user " + userId);
289 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 final long ident = Binder.clearCallingIdentity();
291 try {
292 synchronized (mPackagesLock) {
293 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100294 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700295 } finally {
296 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000297 }
298 }
299
Amith Yamasanibe465322014-04-24 13:45:17 -0700300 /** Assume permissions already checked and caller's identity cleared */
301 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700302 UserInfo user = getUserInfoLocked(userId);
303 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700304 if (user == null) {
305 // Probably a dying user
306 return users;
307 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 for (int i = 0; i < mUsers.size(); i++) {
309 UserInfo profile = mUsers.valueAt(i);
310 if (!isProfileOf(user, profile)) {
311 continue;
312 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100313 if (enabledOnly && !profile.isEnabled()) {
314 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700315 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700316 if (mRemovingUserIds.get(profile.id)) {
317 continue;
318 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700319 users.add(profile);
320 }
321 return users;
322 }
323
Jessica Hummelbe81c802014-04-22 15:49:22 +0100324 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700325 public int getCredentialOwnerProfile(int userHandle) {
326 checkManageUsersPermission("get the credential owner");
327 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
328 synchronized (mPackagesLock) {
329 UserInfo profileParent = getProfileParentLocked(userHandle);
330 if (profileParent != null) {
331 return profileParent.id;
332 }
333 }
334 }
335
336 return userHandle;
337 }
338
339 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100340 public UserInfo getProfileParent(int userHandle) {
341 checkManageUsersPermission("get the profile parent");
342 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700343 return getProfileParentLocked(userHandle);
344 }
345 }
346
347 private UserInfo getProfileParentLocked(int userHandle) {
348 UserInfo profile = getUserInfoLocked(userHandle);
349 if (profile == null) {
350 return null;
351 }
352 int parentUserId = profile.profileGroupId;
353 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
354 return null;
355 } else {
356 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100357 }
358 }
359
Kenny Guy2a764942014-04-02 13:29:20 +0100360 private boolean isProfileOf(UserInfo user, UserInfo profile) {
361 return user.id == profile.id ||
362 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
363 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000364 }
365
366 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100367 public void setUserEnabled(int userId) {
368 checkManageUsersPermission("enable user");
369 synchronized (mPackagesLock) {
370 UserInfo info = getUserInfoLocked(userId);
371 if (info != null && !info.isEnabled()) {
372 info.flags ^= UserInfo.FLAG_DISABLED;
373 writeUserLocked(info);
374 }
375 }
376 }
377
378 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700380 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700382 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700383 }
384 }
385
Amith Yamasani71e6c692013-03-24 17:39:28 -0700386 @Override
387 public boolean isRestricted() {
388 synchronized (mPackagesLock) {
389 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
390 }
391 }
392
Amith Yamasani195263742012-08-21 15:40:12 -0700393 /*
394 * Should be locked on mUsers before calling this.
395 */
396 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700397 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700398 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800399 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700400 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
401 return null;
402 }
403 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700404 }
405
Amith Yamasani13593602012-03-22 16:16:17 -0700406 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700408 return ArrayUtils.contains(mUserIds, userId);
409 }
410 }
411
Amith Yamasani258848d2012-08-10 17:06:33 -0700412 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700413 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700414 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700415 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700416 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700417 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 if (info == null || info.partial) {
419 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
420 return;
421 }
Amith Yamasani13593602012-03-22 16:16:17 -0700422 if (name != null && !name.equals(info.name)) {
423 info.name = name;
424 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700425 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700426 }
427 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700428 if (changed) {
429 sendUserInfoChangedBroadcast(userId);
430 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700431 }
432
Amith Yamasani258848d2012-08-10 17:06:33 -0700433 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700434 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700435 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400436 long ident = Binder.clearCallingIdentity();
437 try {
438 synchronized (mPackagesLock) {
439 UserInfo info = mUsers.get(userId);
440 if (info == null || info.partial) {
441 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
442 return;
443 }
444 writeBitmapLocked(info, bitmap);
445 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 }
Jason Monk9a944532014-07-08 09:31:21 -0400447 sendUserInfoChangedBroadcast(userId);
448 } finally {
449 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700450 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700451 }
452
453 private void sendUserInfoChangedBroadcast(int userId) {
454 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
455 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
456 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700457 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700458 }
459
Amith Yamasani258848d2012-08-10 17:06:33 -0700460 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100461 public ParcelFileDescriptor getUserIcon(int userId) {
462 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700463 synchronized (mPackagesLock) {
464 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 if (info == null || info.partial) {
466 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
467 return null;
468 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100469 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
470 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
471 || callingGroupId != info.profileGroupId) {
472 checkManageUsersPermission("get the icon of a user who is not related");
473 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700474 if (info.iconPath == null) {
475 return null;
476 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100477 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700478 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100479
480 try {
481 return ParcelFileDescriptor.open(
482 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
483 } catch (FileNotFoundException e) {
484 Log.e(LOG_TAG, "Couldn't find icon file", e);
485 }
486 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700487 }
488
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700489 public void makeInitialized(int userId) {
490 checkManageUsersPermission("makeInitialized");
491 synchronized (mPackagesLock) {
492 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700493 if (info == null || info.partial) {
494 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
495 }
496 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700497 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800498 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700499 }
500 }
501 }
502
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700503 /**
504 * If default guest restrictions haven't been initialized yet, add the basic
505 * restrictions.
506 */
507 private void initDefaultGuestRestrictions() {
508 if (mGuestRestrictions.isEmpty()) {
509 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800510 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700511 }
512 }
513
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800514 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530515 public Bundle getDefaultGuestRestrictions() {
516 checkManageUsersPermission("getDefaultGuestRestrictions");
517 synchronized (mPackagesLock) {
518 return new Bundle(mGuestRestrictions);
519 }
520 }
521
522 @Override
523 public void setDefaultGuestRestrictions(Bundle restrictions) {
524 checkManageUsersPermission("setDefaultGuestRestrictions");
525 synchronized (mPackagesLock) {
526 mGuestRestrictions.clear();
527 mGuestRestrictions.putAll(restrictions);
528 writeUserListLocked();
529 }
530 }
531
532 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700533 public boolean hasUserRestriction(String restrictionKey, int userId) {
534 synchronized (mPackagesLock) {
535 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700536 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700537 }
538 }
539
540 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800541 public Bundle getUserRestrictions(int userId) {
542 // checkManageUsersPermission("getUserRestrictions");
543
544 synchronized (mPackagesLock) {
545 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700546 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800547 }
548 }
549
550 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700551 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700552 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700553 synchronized (mPackagesLock) {
554 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
555 Bundle restrictions = getUserRestrictions(userId);
556 restrictions.putBoolean(key, value);
557 setUserRestrictionsInternalLocked(restrictions, userId);
558 }
559 }
560 }
561
562 @Override
563 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
564 checkSystemOrRoot("setSystemControlledUserRestriction");
565 synchronized (mPackagesLock) {
566 Bundle restrictions = getUserRestrictions(userId);
567 restrictions.putBoolean(key, value);
568 setUserRestrictionsInternalLocked(restrictions, userId);
569 }
570 }
571
572 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800573 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700574 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700575 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800576
577 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700578 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
579 // Restore the original state of system controlled restrictions from oldUserRestrictions
580 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
581 restrictions.remove(key);
582 if (oldUserRestrictions.containsKey(key)) {
583 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
584 }
Jason Monk62062992014-05-06 09:55:28 -0400585 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700586 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800587 }
588 }
589
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700590 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
591 final Bundle userRestrictions = mUserRestrictions.get(userId);
592 userRestrictions.clear();
593 userRestrictions.putAll(restrictions);
594 long token = Binder.clearCallingIdentity();
595 try {
596 mAppOpsService.setUserRestrictions(userRestrictions, userId);
597 } catch (RemoteException e) {
598 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
599 } finally {
600 Binder.restoreCallingIdentity(token);
601 }
602 scheduleWriteUserLocked(mUsers.get(userId));
603 }
604
Amith Yamasani258848d2012-08-10 17:06:33 -0700605 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700606 * Check if we've hit the limit of how many users can be created.
607 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700608 private boolean isUserLimitReachedLocked() {
Nicolas Prevot72434b72015-05-13 12:15:03 -0700609 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
610 }
611
612 @Override
613 public boolean canAddMoreManagedProfiles() {
614 checkManageUsersPermission("check if more managed profiles can be added.");
615 if (ActivityManager.isLowRamDeviceStatic()) {
616 return false;
617 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700618 if (!mContext.getPackageManager().hasSystemFeature(
619 PackageManager.FEATURE_MANAGED_USERS)) {
620 return false;
621 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700622 synchronized(mPackagesLock) {
623 // Limit number of managed profiles that can be created
624 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
625 >= MAX_MANAGED_PROFILES) {
626 return false;
627 }
628 int usersCount = getAliveUsersExcludingGuestsCountLocked();
629 // We allow creating a managed profile in the special case where there is only one user.
630 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
631 }
632 }
633
634 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700635 int aliveUserCount = 0;
636 final int totalUserCount = mUsers.size();
637 // Skip over users being removed
638 for (int i = 0; i < totalUserCount; i++) {
639 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700640 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700641 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700642 aliveUserCount++;
643 }
644 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700645 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700646 }
647
648 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700649 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700650 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700651 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700652 *
653 * @param message used as message if SecurityException is thrown
654 * @throws SecurityException if the caller is not system or root
655 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700656 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700657 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400659 && ActivityManager.checkComponentPermission(
660 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700661 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
662 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
663 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400664 }
665
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700666 private static void checkSystemOrRoot(String message) {
667 final int uid = Binder.getCallingUid();
668 if (uid != Process.SYSTEM_UID && uid != 0) {
669 throw new SecurityException("Only system may call: " + message);
670 }
671 }
672
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700673 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700674 try {
675 File dir = new File(mUsersDir, Integer.toString(info.id));
676 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100677 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700678 if (!dir.exists()) {
679 dir.mkdir();
680 FileUtils.setPermissions(
681 dir.getPath(),
682 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
683 -1, -1);
684 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700685 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100686 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
687 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700688 info.iconPath = file.getAbsolutePath();
689 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700690 try {
691 os.close();
692 } catch (IOException ioe) {
693 // What the ... !
694 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100695 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700696 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700697 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700698 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700699 }
700
Amith Yamasani0b285492011-04-14 17:35:23 -0700701 /**
702 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
703 * cache it elsewhere.
704 * @return the array of user ids.
705 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700706 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700707 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700708 return mUserIds;
709 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700710 }
711
Dianne Hackborn4428e172012-08-24 17:43:05 -0700712 int[] getUserIdsLPr() {
713 return mUserIds;
714 }
715
Amith Yamasani13593602012-03-22 16:16:17 -0700716 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700717 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700718 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700719 return;
720 }
721 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700722 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700723 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700724 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700725 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100726 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700727 int type;
728 while ((type = parser.next()) != XmlPullParser.START_TAG
729 && type != XmlPullParser.END_DOCUMENT) {
730 ;
731 }
732
733 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700734 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700735 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700736 return;
737 }
738
Amith Yamasani2a003292012-08-14 18:25:45 -0700739 mNextSerialNumber = -1;
740 if (parser.getName().equals(TAG_USERS)) {
741 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
742 if (lastSerialNumber != null) {
743 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
744 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700745 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
746 if (versionNumber != null) {
747 mUserVersion = Integer.parseInt(versionNumber);
748 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700749 }
750
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700751 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530752 if (type == XmlPullParser.START_TAG) {
753 final String name = parser.getName();
754 if (name.equals(TAG_USER)) {
755 String id = parser.getAttributeValue(null, ATTR_ID);
756 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700757
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530758 if (user != null) {
759 mUsers.put(user.id, user);
760 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
761 mNextSerialNumber = user.id + 1;
762 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700763 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530764 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800765 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
766 && type != XmlPullParser.END_TAG) {
767 if (type == XmlPullParser.START_TAG) {
768 if (parser.getName().equals(TAG_RESTRICTIONS)) {
769 readRestrictionsLocked(parser, mGuestRestrictions);
770 }
771 break;
772 }
773 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700774 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700775 }
776 }
Amith Yamasani13593602012-03-22 16:16:17 -0700777 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700778 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700780 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700781 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700782 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800783 } finally {
784 if (fis != null) {
785 try {
786 fis.close();
787 } catch (IOException e) {
788 }
789 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 }
791 }
792
Amith Yamasani6f34b412012-10-22 18:19:27 -0700793 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800794 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700795 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700796 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700797 int userVersion = mUserVersion;
798 if (userVersion < 1) {
799 // Assign a proper name for the owner, if not initialized correctly before
800 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
801 if ("Primary".equals(user.name)) {
802 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800803 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700804 }
805 userVersion = 1;
806 }
807
Amith Yamasanibc9625052012-11-15 14:39:18 -0800808 if (userVersion < 2) {
809 // Owner should be marked as initialized
810 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
811 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
812 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800813 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800814 }
815 userVersion = 2;
816 }
817
Amith Yamasani350962c2013-08-06 11:18:53 -0700818
Amith Yamasani5e486f52013-08-07 11:06:44 -0700819 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700820 userVersion = 4;
821 }
822
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700823 if (userVersion < 5) {
824 initDefaultGuestRestrictions();
825 userVersion = 5;
826 }
827
Amith Yamasani6f34b412012-10-22 18:19:27 -0700828 if (userVersion < USER_VERSION) {
829 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
830 + USER_VERSION);
831 } else {
832 mUserVersion = userVersion;
833 writeUserListLocked();
834 }
835 }
836
Amith Yamasani13593602012-03-22 16:16:17 -0700837 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700838 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800839 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700840 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700841 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700842 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700843 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400844 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800845
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500846 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800847 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
848
Amith Yamasani13593602012-03-22 16:16:17 -0700849 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700850 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700851
Amith Yamasani13593602012-03-22 16:16:17 -0700852 writeUserListLocked();
853 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 }
855
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800856 private void scheduleWriteUserLocked(UserInfo userInfo) {
857 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
858 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
859 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
860 }
861 }
862
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700863 /*
864 * Writes the user file in this format:
865 *
866 * <user flags="20039023" id="0">
867 * <name>Primary</name>
868 * </user>
869 */
Amith Yamasani13593602012-03-22 16:16:17 -0700870 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700871 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700872 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700874 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700875 final BufferedOutputStream bos = new BufferedOutputStream(fos);
876
877 // XmlSerializer serializer = XmlUtils.serializerInstance();
878 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100879 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700880 serializer.startDocument(null, true);
881 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
882
883 serializer.startTag(null, TAG_USER);
884 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700885 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700887 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
888 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
889 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700890 if (userInfo.iconPath != null) {
891 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
892 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700893 if (userInfo.partial) {
894 serializer.attribute(null, ATTR_PARTIAL, "true");
895 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700896 if (userInfo.guestToRemove) {
897 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
898 }
Kenny Guy2a764942014-04-02 13:29:20 +0100899 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
900 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
901 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000902 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700903
904 serializer.startTag(null, TAG_NAME);
905 serializer.text(userInfo.name);
906 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800907 Bundle restrictions = mUserRestrictions.get(userInfo.id);
908 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530909 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800910 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 serializer.endTag(null, TAG_USER);
912
913 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700914 userFile.finishWrite(fos);
915 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700916 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700917 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918 }
919 }
920
921 /*
922 * Writes the user list file in this format:
923 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700924 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700925 * <user id="0"></user>
926 * <user id="2"></user>
927 * </users>
928 */
Amith Yamasani13593602012-03-22 16:16:17 -0700929 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700930 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700931 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700933 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 final BufferedOutputStream bos = new BufferedOutputStream(fos);
935
936 // XmlSerializer serializer = XmlUtils.serializerInstance();
937 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100938 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 serializer.startDocument(null, true);
940 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
941
942 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700944 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945
Adam Lesinskieddeb492014-09-08 17:50:03 -0700946 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530947 writeRestrictionsLocked(serializer, mGuestRestrictions);
948 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 for (int i = 0; i < mUsers.size(); i++) {
950 UserInfo user = mUsers.valueAt(i);
951 serializer.startTag(null, TAG_USER);
952 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
953 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700954 }
955
956 serializer.endTag(null, TAG_USERS);
957
958 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700959 userListFile.finishWrite(fos);
960 } catch (Exception e) {
961 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 }
964 }
965
Andres Moralesc5548c02015-08-05 10:23:12 -0700966 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530967 throws IOException {
968 serializer.startTag(null, TAG_RESTRICTIONS);
969 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
970 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
971 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
972 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
973 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
974 writeBoolean(serializer, restrictions,
975 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
976 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
977 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
978 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
979 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
980 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
981 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
982 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -0700983 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530984 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
985 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
986 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
987 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
988 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
989 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
990 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
991 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
992 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700993 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
994 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -0700995 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -0400996 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700997 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001001 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301002 serializer.endTag(null, TAG_RESTRICTIONS);
1003 }
1004
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001005 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001007 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001009 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001010 long creationTime = 0L;
1011 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001012 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001013 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001014 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001015 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001016
1017 FileInputStream fis = null;
1018 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001019 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001020 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001021 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001022 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001023 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001024 int type;
1025 while ((type = parser.next()) != XmlPullParser.START_TAG
1026 && type != XmlPullParser.END_DOCUMENT) {
1027 ;
1028 }
1029
1030 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001031 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001032 return null;
1033 }
1034
1035 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001036 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1037 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001038 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 return null;
1040 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001041 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1042 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001043 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001044 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1045 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001046 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1047 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001048 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1049 if ("true".equals(valueString)) {
1050 partial = true;
1051 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001052 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1053 if ("true".equals(valueString)) {
1054 guestToRemove = true;
1055 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001057 int outerDepth = parser.getDepth();
1058 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1059 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1060 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1061 continue;
1062 }
1063 String tag = parser.getName();
1064 if (TAG_NAME.equals(tag)) {
1065 type = parser.next();
1066 if (type == XmlPullParser.TEXT) {
1067 name = parser.getText();
1068 }
1069 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301070 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001071 }
1072 }
1073 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001074
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001075 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001076 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001077 userInfo.creationTime = creationTime;
1078 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001079 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001080 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001081 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001082 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001083 return userInfo;
1084
1085 } catch (IOException ioe) {
1086 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001087 } finally {
1088 if (fis != null) {
1089 try {
1090 fis.close();
1091 } catch (IOException e) {
1092 }
1093 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001094 }
1095 return null;
1096 }
1097
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301098 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1099 throws IOException {
1100 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1101 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1102 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1103 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1104 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1105 readBoolean(parser, restrictions,
1106 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1107 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1108 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1109 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1110 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1111 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1112 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1113 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -07001114 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301115 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1116 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1117 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1118 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1119 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1120 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1121 readBoolean(parser, restrictions,
1122 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1123 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1124 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001125 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1126 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001127 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001128 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001129 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1130 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001131 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001132 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001133 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301134 }
1135
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001136 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1137 String restrictionKey) {
1138 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001139 if (value != null) {
1140 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1141 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001142 }
1143
1144 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1145 throws IOException {
1146 if (restrictions.containsKey(restrictionKey)) {
1147 xml.attribute(null, restrictionKey,
1148 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1149 }
1150 }
1151
Amith Yamasani920ace02012-09-20 22:15:37 -07001152 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1153 String valueString = parser.getAttributeValue(null, attr);
1154 if (valueString == null) return defaultValue;
1155 try {
1156 return Integer.parseInt(valueString);
1157 } catch (NumberFormatException nfe) {
1158 return defaultValue;
1159 }
1160 }
1161
1162 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1163 String valueString = parser.getAttributeValue(null, attr);
1164 if (valueString == null) return defaultValue;
1165 try {
1166 return Long.parseLong(valueString);
1167 } catch (NumberFormatException nfe) {
1168 return defaultValue;
1169 }
1170 }
1171
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001172 private boolean isPackageInstalled(String pkg, int userId) {
1173 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1174 PackageManager.GET_UNINSTALLED_PACKAGES,
1175 userId);
1176 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1177 return false;
1178 }
1179 return true;
1180 }
1181
Amith Yamasanib82add22013-07-09 11:24:44 -07001182 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001183 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001184 * Does not do any permissions checking.
1185 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001186 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001187 synchronized (mPackagesLock) {
1188 File dir = Environment.getUserSystemDirectory(userId);
1189 String[] files = dir.list();
1190 if (files == null) return;
1191 for (String fileName : files) {
1192 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1193 File resFile = new File(dir, fileName);
1194 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001195 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001196 }
1197 }
1198 }
1199 }
1200 }
1201
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001202 /**
1203 * Removes the app restrictions file for a specific package and user id, if it exists.
1204 */
1205 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1206 synchronized (mPackagesLock) {
1207 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001208 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001209 if (resFile.exists()) {
1210 resFile.delete();
1211 }
1212 }
1213 }
1214
Kenny Guya52dc3e2014-02-11 15:33:14 +00001215 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001216 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001217 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001218 if (userId != UserHandle.USER_OWNER) {
1219 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001220 return null;
1221 }
Kenny Guy2a764942014-04-02 13:29:20 +01001222 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001223 }
1224
Amith Yamasani258848d2012-08-10 17:06:33 -07001225 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001226 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001227 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001228 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001229 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001230
Jessica Hummelbe81c802014-04-22 15:49:22 +01001231 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001232 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1233 UserManager.DISALLOW_ADD_USER, false)) {
1234 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1235 return null;
1236 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001237 if (ActivityManager.isLowRamDeviceStatic()) {
1238 return null;
1239 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001240 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot72434b72015-05-13 12:15:03 -07001241 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001242 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001243 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001244 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001245 try {
1246 synchronized (mInstallLock) {
1247 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001248 UserInfo parent = null;
1249 if (parentId != UserHandle.USER_NULL) {
1250 parent = getUserInfoLocked(parentId);
1251 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001252 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001253 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1254 return null;
1255 }
1256 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1257 // If we're not adding a guest user or a managed profile and the limit has
1258 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001259 return null;
1260 }
1261 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001262 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001263 return null;
1264 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001265 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001266 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001267 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001268 long now = System.currentTimeMillis();
1269 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001270 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001271 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001272 mUsers.put(userId, userInfo);
1273 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001274 if (parent != null) {
1275 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1276 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001277 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001278 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001279 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001280 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001281 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1282 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1283 final String volumeUuid = vol.getFsUuid();
1284 try {
1285 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1286 userId);
1287 prepareUserDirectory(userDir);
1288 enforceSerialNumber(userDir, userInfo.serialNumber);
1289 } catch (IOException e) {
1290 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1291 }
1292 }
1293 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001294 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001295 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001296 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001297 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001298 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001299 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001300 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001301 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001302 if (userInfo != null) {
1303 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1304 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1305 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1306 android.Manifest.permission.MANAGE_USERS);
1307 }
1308 } finally {
1309 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001310 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 return userInfo;
1312 }
1313
Amith Yamasani95ab7842014-08-11 17:09:26 -07001314 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1315 int count = 0;
1316 for (int i = mUsers.size() - 1; i >= 0; i--) {
1317 UserInfo user = mUsers.valueAt(i);
1318 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1319 if ((user.flags & flags) != 0) {
1320 count++;
1321 }
1322 }
1323 }
1324 return count;
1325 }
1326
Amith Yamasani0b285492011-04-14 17:35:23 -07001327 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001328 * Find the current guest user. If the Guest user is partial,
1329 * then do not include it in the results as it is about to die.
1330 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1331 * the special handling of Guests being removed.
1332 */
1333 private UserInfo findCurrentGuestUserLocked() {
1334 final int size = mUsers.size();
1335 for (int i = 0; i < size; i++) {
1336 final UserInfo user = mUsers.valueAt(i);
1337 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1338 return user;
1339 }
1340 }
1341 return null;
1342 }
1343
1344 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001345 * Mark this guest user for deletion to allow us to create another guest
1346 * and switch to that user before actually removing this guest.
1347 * @param userHandle the userid of the current guest
1348 * @return whether the user could be marked for deletion
1349 */
1350 public boolean markGuestForDeletion(int userHandle) {
1351 checkManageUsersPermission("Only the system can remove users");
1352 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1353 UserManager.DISALLOW_REMOVE_USER, false)) {
1354 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1355 return false;
1356 }
1357
1358 long ident = Binder.clearCallingIdentity();
1359 try {
1360 final UserInfo user;
1361 synchronized (mPackagesLock) {
1362 user = mUsers.get(userHandle);
1363 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1364 return false;
1365 }
1366 if (!user.isGuest()) {
1367 return false;
1368 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001369 // We set this to a guest user that is to be removed. This is a temporary state
1370 // where we are allowed to add new Guest users, even if this one is still not
1371 // removed. This user will still show up in getUserInfo() calls.
1372 // If we don't get around to removing this Guest user, it will be purged on next
1373 // startup.
1374 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001375 // Mark it as disabled, so that it isn't returned any more when
1376 // profiles are queried.
1377 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001378 writeUserLocked(user);
1379 }
1380 } finally {
1381 Binder.restoreCallingIdentity(ident);
1382 }
1383 return true;
1384 }
1385
1386 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001387 * Removes a user and all data directories created for that user. This method should be called
1388 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001389 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001390 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001391 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001392 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001393 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1394 UserManager.DISALLOW_REMOVE_USER, false)) {
1395 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1396 return false;
1397 }
1398
Kenny Guyee58b4f2014-05-23 15:19:53 +01001399 long ident = Binder.clearCallingIdentity();
1400 try {
1401 final UserInfo user;
1402 synchronized (mPackagesLock) {
1403 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001404 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001405 return false;
1406 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001407
1408 // We remember deleted user IDs to prevent them from being
1409 // reused during the current boot; they can still be reused
1410 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001411 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001412
Kenny Guyee58b4f2014-05-23 15:19:53 +01001413 try {
1414 mAppOpsService.removeUser(userHandle);
1415 } catch (RemoteException e) {
1416 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1417 }
1418 // Set this to a partially created user, so that the user will be purged
1419 // on next startup, in case the runtime stops now before stopping and
1420 // removing the user completely.
1421 user.partial = true;
1422 // Mark it as disabled, so that it isn't returned any more when
1423 // profiles are queried.
1424 user.flags |= UserInfo.FLAG_DISABLED;
1425 writeUserLocked(user);
1426 }
1427
1428 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1429 && user.isManagedProfile()) {
1430 // Send broadcast to notify system that the user removed was a
1431 // managed user.
1432 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1433 }
1434
1435 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1436 int res;
1437 try {
1438 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1439 new IStopUserCallback.Stub() {
1440 @Override
1441 public void userStopped(int userId) {
1442 finishRemoveUser(userId);
1443 }
1444 @Override
1445 public void userStopAborted(int userId) {
1446 }
1447 });
1448 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001449 return false;
1450 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001451 return res == ActivityManager.USER_OP_SUCCESS;
1452 } finally {
1453 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001454 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001455 }
1456
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001457 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001458 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001459 // Let other services shutdown any activity and clean up their state before completely
1460 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001461 long ident = Binder.clearCallingIdentity();
1462 try {
1463 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1464 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001465 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1466 android.Manifest.permission.MANAGE_USERS,
1467
1468 new BroadcastReceiver() {
1469 @Override
1470 public void onReceive(Context context, Intent intent) {
1471 if (DBG) {
1472 Slog.i(LOG_TAG,
1473 "USER_REMOVED broadcast sent, cleaning up user data "
1474 + userHandle);
1475 }
1476 new Thread() {
1477 public void run() {
1478 synchronized (mInstallLock) {
1479 synchronized (mPackagesLock) {
1480 removeUserStateLocked(userHandle);
1481 }
1482 }
1483 }
1484 }.start();
1485 }
1486 },
1487
1488 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001489 } finally {
1490 Binder.restoreCallingIdentity(ident);
1491 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001492 }
1493
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001494 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001495 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001496 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001497
1498 // Remove this user from the list
1499 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001500 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001501 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001502 userFile.delete();
1503 // Update the user list
1504 writeUserListLocked();
1505 updateUserIdsLocked();
1506 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1507 }
1508
Amith Yamasani61f57372012-08-31 12:12:28 -07001509 private void removeDirectoryRecursive(File parent) {
1510 if (parent.isDirectory()) {
1511 String[] files = parent.list();
1512 for (String filename : files) {
1513 File child = new File(parent, filename);
1514 removeDirectoryRecursive(child);
1515 }
1516 }
1517 parent.delete();
1518 }
1519
Kenny Guyf8d3a232014-05-15 16:09:52 +01001520 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001521 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001522 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1523 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001524 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1525 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001526 }
1527
Amith Yamasani2a003292012-08-14 18:25:45 -07001528 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001529 public Bundle getApplicationRestrictions(String packageName) {
1530 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1531 }
1532
1533 @Override
1534 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001535 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001536 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001537 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 }
1539 synchronized (mPackagesLock) {
1540 // Read the restrictions from XML
1541 return readApplicationRestrictionsLocked(packageName, userId);
1542 }
1543 }
1544
1545 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001546 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001547 int userId) {
1548 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001549 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001550 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001551 }
1552 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001553 if (restrictions == null || restrictions.isEmpty()) {
1554 cleanAppRestrictionsForPackage(packageName, userId);
1555 } else {
1556 // Write the restrictions to XML
1557 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1558 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001559 }
Robin Lee66e5d962014-04-09 16:44:21 +01001560
Kenny Guyd21b2182014-07-17 16:38:55 +01001561 if (isPackageInstalled(packageName, userId)) {
1562 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1563 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1564 changeIntent.setPackage(packageName);
1565 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1566 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1567 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568 }
1569
Amith Yamasani655d0e22013-06-12 14:19:10 -07001570 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001571 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001572 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001573 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001574 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001575 }
1576
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001577 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001578 synchronized (mPackagesLock) {
1579 // Remove all user restrictions
1580 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001581 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001582 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001583 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001584 if (unhideApps) {
1585 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001586 }
1587 }
1588
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001589 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001590 mHandler.post(new Runnable() {
1591 @Override
1592 public void run() {
1593 List<ApplicationInfo> apps =
1594 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1595 userHandle).getList();
1596 final long ident = Binder.clearCallingIdentity();
1597 try {
1598 for (ApplicationInfo appInfo : apps) {
1599 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001600 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1601 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001602 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001603 userHandle);
1604 }
1605 }
1606 } finally {
1607 Binder.restoreCallingIdentity(ident);
1608 }
1609 }
1610 });
1611 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001612 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001613 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001614 try {
1615 return mContext.getPackageManager().getApplicationInfo(packageName,
1616 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1617 } catch (NameNotFoundException nnfe) {
1618 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001619 } finally {
1620 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001621 }
1622 }
1623
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001624 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001625 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001626 AtomicFile restrictionsFile =
1627 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1628 packageToRestrictionsFileName(packageName)));
1629 return readApplicationRestrictionsLocked(restrictionsFile);
1630 }
1631
1632 @VisibleForTesting
1633 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001634 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001635 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001636 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001637 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001638 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001639
1640 FileInputStream fis = null;
1641 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001642 fis = restrictionsFile.openRead();
1643 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001644 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001645 XmlUtils.nextElement(parser);
1646 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 Slog.e(LOG_TAG, "Unable to read restrictions file "
1648 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001649 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001650 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001651 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1652 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001653 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001654 } catch (IOException|XmlPullParserException e) {
1655 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001656 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001657 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001658 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001659 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 }
1661
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001662 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1663 XmlPullParser parser) throws XmlPullParserException, IOException {
1664 int type = parser.getEventType();
1665 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1666 String key = parser.getAttributeValue(null, ATTR_KEY);
1667 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1668 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1669 if (multiple != null) {
1670 values.clear();
1671 int count = Integer.parseInt(multiple);
1672 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1673 if (type == XmlPullParser.START_TAG
1674 && parser.getName().equals(TAG_VALUE)) {
1675 values.add(parser.nextText().trim());
1676 count--;
1677 }
1678 }
1679 String [] valueStrings = new String[values.size()];
1680 values.toArray(valueStrings);
1681 restrictions.putStringArray(key, valueStrings);
1682 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1683 restrictions.putBundle(key, readBundleEntry(parser, values));
1684 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1685 final int outerDepth = parser.getDepth();
1686 ArrayList<Bundle> bundleList = new ArrayList<>();
1687 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1688 Bundle childBundle = readBundleEntry(parser, values);
1689 bundleList.add(childBundle);
1690 }
1691 restrictions.putParcelableArray(key,
1692 bundleList.toArray(new Bundle[bundleList.size()]));
1693 } else {
1694 String value = parser.nextText().trim();
1695 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1696 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1697 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1698 restrictions.putInt(key, Integer.parseInt(value));
1699 } else {
1700 restrictions.putString(key, value);
1701 }
1702 }
1703 }
1704 }
1705
1706 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1707 throws IOException, XmlPullParserException {
1708 Bundle childBundle = new Bundle();
1709 final int outerDepth = parser.getDepth();
1710 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1711 readEntry(childBundle, values, parser);
1712 }
1713 return childBundle;
1714 }
1715
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001716 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001717 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001718 AtomicFile restrictionsFile = new AtomicFile(
1719 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001720 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001721 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1722 }
1723
1724 @VisibleForTesting
1725 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1726 AtomicFile restrictionsFile) {
1727 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001728 try {
1729 fos = restrictionsFile.startWrite();
1730 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1731
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001732 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001733 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001734 serializer.startDocument(null, true);
1735 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1736
1737 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001738 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001739 serializer.endTag(null, TAG_RESTRICTIONS);
1740
1741 serializer.endDocument();
1742 restrictionsFile.finishWrite(fos);
1743 } catch (Exception e) {
1744 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001745 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1746 }
1747 }
1748
1749 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1750 throws IOException {
1751 for (String key : restrictions.keySet()) {
1752 Object value = restrictions.get(key);
1753 serializer.startTag(null, TAG_ENTRY);
1754 serializer.attribute(null, ATTR_KEY, key);
1755
1756 if (value instanceof Boolean) {
1757 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1758 serializer.text(value.toString());
1759 } else if (value instanceof Integer) {
1760 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1761 serializer.text(value.toString());
1762 } else if (value == null || value instanceof String) {
1763 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1764 serializer.text(value != null ? (String) value : "");
1765 } else if (value instanceof Bundle) {
1766 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1767 writeBundle((Bundle) value, serializer);
1768 } else if (value instanceof Parcelable[]) {
1769 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1770 Parcelable[] array = (Parcelable[]) value;
1771 for (Parcelable parcelable : array) {
1772 if (!(parcelable instanceof Bundle)) {
1773 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1774 }
1775 serializer.startTag(null, TAG_ENTRY);
1776 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1777 writeBundle((Bundle) parcelable, serializer);
1778 serializer.endTag(null, TAG_ENTRY);
1779 }
1780 } else {
1781 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1782 String[] values = (String[]) value;
1783 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1784 for (String choice : values) {
1785 serializer.startTag(null, TAG_VALUE);
1786 serializer.text(choice != null ? choice : "");
1787 serializer.endTag(null, TAG_VALUE);
1788 }
1789 }
1790 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001791 }
1792 }
1793
1794 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001795 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001796 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001797 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001798 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001799 }
1800 }
1801
1802 @Override
1803 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001804 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001805 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001806 UserInfo info = getUserInfoLocked(userId);
1807 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001808 }
1809 // Not found
1810 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001811 }
1812 }
1813
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001814 @Override
1815 public long getUserCreationTime(int userHandle) {
1816 int callingUserId = UserHandle.getCallingUserId();
1817 UserInfo userInfo = null;
1818 synchronized (mPackagesLock) {
1819 if (callingUserId == userHandle) {
1820 userInfo = getUserInfoLocked(userHandle);
1821 } else {
1822 UserInfo parent = getProfileParentLocked(userHandle);
1823 if (parent != null && parent.id == callingUserId) {
1824 userInfo = getUserInfoLocked(userHandle);
1825 }
1826 }
1827 }
1828 if (userInfo == null) {
1829 throw new SecurityException("userHandle can only be the calling user or a managed "
1830 + "profile associated with this user");
1831 }
1832 return userInfo.creationTime;
1833 }
1834
Amith Yamasani0b285492011-04-14 17:35:23 -07001835 /**
1836 * Caches the list of user ids in an array, adjusting the array size when necessary.
1837 */
Amith Yamasani13593602012-03-22 16:16:17 -07001838 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001839 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001840 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001841 if (!mUsers.valueAt(i).partial) {
1842 num++;
1843 }
1844 }
Amith Yamasani16389312012-10-17 21:20:14 -07001845 final int[] newUsers = new int[num];
1846 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001847 for (int i = 0; i < mUsers.size(); i++) {
1848 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001849 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001850 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001851 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001852 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001853 }
1854
1855 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001856 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001857 * @param userId the user that was just foregrounded
1858 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001859 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001860 synchronized (mPackagesLock) {
1861 UserInfo user = mUsers.get(userId);
1862 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001863 if (user == null || user.partial) {
1864 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1865 return;
1866 }
1867 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001868 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001869 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001870 }
1871 }
1872 }
1873
1874 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001875 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001876 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1877 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001878 * @return
1879 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001880 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001881 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001882 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001883 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001884 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001885 break;
1886 }
1887 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001888 }
Amith Yamasani195263742012-08-21 15:40:12 -07001889 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001890 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001891 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001892
Amith Yamasanifc95e702013-09-26 13:20:17 -07001893 private String packageToRestrictionsFileName(String packageName) {
1894 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1895 }
1896
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001897 /**
1898 * Create new {@code /data/user/[id]} directory and sets default
1899 * permissions.
1900 */
1901 public static void prepareUserDirectory(File file) throws IOException {
1902 if (!file.exists()) {
1903 if (!file.mkdir()) {
1904 throw new IOException("Failed to create " + file);
1905 }
1906 }
1907 if (FileUtils.setPermissions(file.getAbsolutePath(), 0771, Process.SYSTEM_UID,
1908 Process.SYSTEM_UID) != 0) {
1909 throw new IOException("Failed to prepare " + file);
1910 }
1911 }
1912
1913 /**
1914 * Enforce that serial number stored in user directory inode matches the
1915 * given expected value. Gracefully sets the serial number if currently
1916 * undefined.
1917 *
1918 * @throws IOException when problem extracting serial number, or serial
1919 * number is mismatched.
1920 */
1921 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1922 final int foundSerial = getSerialNumber(file);
1923 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1924
1925 if (foundSerial == -1) {
1926 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1927 try {
1928 setSerialNumber(file, serialNumber);
1929 } catch (IOException e) {
1930 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1931 }
1932
1933 } else if (foundSerial != serialNumber) {
1934 throw new IOException("Found serial number " + foundSerial
1935 + " doesn't match expected " + serialNumber);
1936 }
1937 }
1938
1939 /**
1940 * Set serial number stored in user directory inode.
1941 *
1942 * @throws IOException if serial number was already set
1943 */
1944 private static void setSerialNumber(File file, int serialNumber)
1945 throws IOException {
1946 try {
1947 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1948 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1949 } catch (ErrnoException e) {
1950 throw e.rethrowAsIOException();
1951 }
1952 }
1953
1954 /**
1955 * Return serial number stored in user directory inode.
1956 *
1957 * @return parsed serial number, or -1 if not set
1958 */
1959 private static int getSerialNumber(File file) throws IOException {
1960 try {
1961 final byte[] buf = new byte[256];
1962 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1963 final String serial = new String(buf, 0, len);
1964 try {
1965 return Integer.parseInt(serial);
1966 } catch (NumberFormatException e) {
1967 throw new IOException("Bad serial number: " + serial);
1968 }
1969 } catch (ErrnoException e) {
1970 if (e.errno == OsConstants.ENODATA) {
1971 return -1;
1972 } else {
1973 throw e.rethrowAsIOException();
1974 }
1975 }
1976 }
1977
Amith Yamasani920ace02012-09-20 22:15:37 -07001978 @Override
1979 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1980 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1981 != PackageManager.PERMISSION_GRANTED) {
1982 pw.println("Permission Denial: can't dump UserManager from from pid="
1983 + Binder.getCallingPid()
1984 + ", uid=" + Binder.getCallingUid()
1985 + " without permission "
1986 + android.Manifest.permission.DUMP);
1987 return;
1988 }
1989
1990 long now = System.currentTimeMillis();
1991 StringBuilder sb = new StringBuilder();
1992 synchronized (mPackagesLock) {
1993 pw.println("Users:");
1994 for (int i = 0; i < mUsers.size(); i++) {
1995 UserInfo user = mUsers.valueAt(i);
1996 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001997 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001998 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001999 if (user.partial) pw.print(" <partial>");
2000 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002001 pw.print(" Created: ");
2002 if (user.creationTime == 0) {
2003 pw.println("<unknown>");
2004 } else {
2005 sb.setLength(0);
2006 TimeUtils.formatDuration(now - user.creationTime, sb);
2007 sb.append(" ago");
2008 pw.println(sb);
2009 }
2010 pw.print(" Last logged in: ");
2011 if (user.lastLoggedInTime == 0) {
2012 pw.println("<unknown>");
2013 } else {
2014 sb.setLength(0);
2015 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2016 sb.append(" ago");
2017 pw.println(sb);
2018 }
2019 }
2020 }
2021 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002022
2023 final class MainHandler extends Handler {
2024
2025 @Override
2026 public void handleMessage(Message msg) {
2027 switch (msg.what) {
2028 case WRITE_USER_MSG:
2029 removeMessages(WRITE_USER_MSG, msg.obj);
2030 synchronized (mPackagesLock) {
2031 int userId = ((UserInfo) msg.obj).id;
2032 UserInfo userInfo = mUsers.get(userId);
2033 if (userInfo != null) {
2034 writeUserLocked(userInfo);
2035 }
2036 }
2037 }
2038 }
2039 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002040
2041 /**
2042 * @param userId
2043 * @return whether the user has been initialized yet
2044 */
2045 boolean isInitialized(int userId) {
2046 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2047 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002048}