blob: 060752568f2e0b0dc9a3bdf9479348d46161a2af [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);
Amith Yamasania7892482015-08-07 11:09:05 -0700249 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 + " (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 Yamasani236b2b52015-08-18 14:32:14 -0700406 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700407 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700408 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700409 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700410 }
411 }
412
Amith Yamasani258848d2012-08-10 17:06:33 -0700413 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700414 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700415 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700417 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700418 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 if (info == null || info.partial) {
420 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
421 return;
422 }
Amith Yamasani13593602012-03-22 16:16:17 -0700423 if (name != null && !name.equals(info.name)) {
424 info.name = name;
425 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700426 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700427 }
428 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700429 if (changed) {
430 sendUserInfoChangedBroadcast(userId);
431 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700432 }
433
Amith Yamasani258848d2012-08-10 17:06:33 -0700434 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700435 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700436 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400437 long ident = Binder.clearCallingIdentity();
438 try {
439 synchronized (mPackagesLock) {
440 UserInfo info = mUsers.get(userId);
441 if (info == null || info.partial) {
442 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
443 return;
444 }
445 writeBitmapLocked(info, bitmap);
446 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 }
Jason Monk9a944532014-07-08 09:31:21 -0400448 sendUserInfoChangedBroadcast(userId);
449 } finally {
450 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700451 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700452 }
453
454 private void sendUserInfoChangedBroadcast(int userId) {
455 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
456 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
457 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700458 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700459 }
460
Amith Yamasani258848d2012-08-10 17:06:33 -0700461 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100462 public ParcelFileDescriptor getUserIcon(int userId) {
463 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700464 synchronized (mPackagesLock) {
465 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700466 if (info == null || info.partial) {
467 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
468 return null;
469 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100470 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
471 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
472 || callingGroupId != info.profileGroupId) {
473 checkManageUsersPermission("get the icon of a user who is not related");
474 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700475 if (info.iconPath == null) {
476 return null;
477 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100478 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700479 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100480
481 try {
482 return ParcelFileDescriptor.open(
483 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
484 } catch (FileNotFoundException e) {
485 Log.e(LOG_TAG, "Couldn't find icon file", e);
486 }
487 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700488 }
489
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700490 public void makeInitialized(int userId) {
491 checkManageUsersPermission("makeInitialized");
492 synchronized (mPackagesLock) {
493 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700494 if (info == null || info.partial) {
495 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
496 }
497 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700498 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800499 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700500 }
501 }
502 }
503
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700504 /**
505 * If default guest restrictions haven't been initialized yet, add the basic
506 * restrictions.
507 */
508 private void initDefaultGuestRestrictions() {
509 if (mGuestRestrictions.isEmpty()) {
510 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800511 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700512 }
513 }
514
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800515 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530516 public Bundle getDefaultGuestRestrictions() {
517 checkManageUsersPermission("getDefaultGuestRestrictions");
518 synchronized (mPackagesLock) {
519 return new Bundle(mGuestRestrictions);
520 }
521 }
522
523 @Override
524 public void setDefaultGuestRestrictions(Bundle restrictions) {
525 checkManageUsersPermission("setDefaultGuestRestrictions");
526 synchronized (mPackagesLock) {
527 mGuestRestrictions.clear();
528 mGuestRestrictions.putAll(restrictions);
529 writeUserListLocked();
530 }
531 }
532
533 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700534 public boolean hasUserRestriction(String restrictionKey, int userId) {
535 synchronized (mPackagesLock) {
536 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700537 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700538 }
539 }
540
541 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800542 public Bundle getUserRestrictions(int userId) {
543 // checkManageUsersPermission("getUserRestrictions");
544
545 synchronized (mPackagesLock) {
546 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700547 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800548 }
549 }
550
551 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700552 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700553 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700554 synchronized (mPackagesLock) {
555 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
556 Bundle restrictions = getUserRestrictions(userId);
557 restrictions.putBoolean(key, value);
558 setUserRestrictionsInternalLocked(restrictions, userId);
559 }
560 }
561 }
562
563 @Override
564 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
565 checkSystemOrRoot("setSystemControlledUserRestriction");
566 synchronized (mPackagesLock) {
567 Bundle restrictions = getUserRestrictions(userId);
568 restrictions.putBoolean(key, value);
569 setUserRestrictionsInternalLocked(restrictions, userId);
570 }
571 }
572
573 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800574 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700575 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700576 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800577
578 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700579 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
580 // Restore the original state of system controlled restrictions from oldUserRestrictions
581 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
582 restrictions.remove(key);
583 if (oldUserRestrictions.containsKey(key)) {
584 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
585 }
Jason Monk62062992014-05-06 09:55:28 -0400586 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700587 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800588 }
589 }
590
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700591 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
592 final Bundle userRestrictions = mUserRestrictions.get(userId);
593 userRestrictions.clear();
594 userRestrictions.putAll(restrictions);
595 long token = Binder.clearCallingIdentity();
596 try {
597 mAppOpsService.setUserRestrictions(userRestrictions, userId);
598 } catch (RemoteException e) {
599 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
600 } finally {
601 Binder.restoreCallingIdentity(token);
602 }
603 scheduleWriteUserLocked(mUsers.get(userId));
604 }
605
Amith Yamasani258848d2012-08-10 17:06:33 -0700606 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700607 * Check if we've hit the limit of how many users can be created.
608 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700609 private boolean isUserLimitReachedLocked() {
Nicolas Prevot72434b72015-05-13 12:15:03 -0700610 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
611 }
612
613 @Override
614 public boolean canAddMoreManagedProfiles() {
615 checkManageUsersPermission("check if more managed profiles can be added.");
616 if (ActivityManager.isLowRamDeviceStatic()) {
617 return false;
618 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700619 if (!mContext.getPackageManager().hasSystemFeature(
620 PackageManager.FEATURE_MANAGED_USERS)) {
621 return false;
622 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700623 synchronized(mPackagesLock) {
624 // Limit number of managed profiles that can be created
625 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
626 >= MAX_MANAGED_PROFILES) {
627 return false;
628 }
629 int usersCount = getAliveUsersExcludingGuestsCountLocked();
630 // We allow creating a managed profile in the special case where there is only one user.
631 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
632 }
633 }
634
635 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700636 int aliveUserCount = 0;
637 final int totalUserCount = mUsers.size();
638 // Skip over users being removed
639 for (int i = 0; i < totalUserCount; i++) {
640 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700641 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700642 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700643 aliveUserCount++;
644 }
645 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700646 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700647 }
648
649 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700650 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700651 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700652 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700653 *
654 * @param message used as message if SecurityException is thrown
655 * @throws SecurityException if the caller is not system or root
656 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700657 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700658 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700659 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400660 && ActivityManager.checkComponentPermission(
661 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700662 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
663 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
664 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400665 }
666
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700667 private static void checkSystemOrRoot(String message) {
668 final int uid = Binder.getCallingUid();
669 if (uid != Process.SYSTEM_UID && uid != 0) {
670 throw new SecurityException("Only system may call: " + message);
671 }
672 }
673
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700674 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700675 try {
676 File dir = new File(mUsersDir, Integer.toString(info.id));
677 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100678 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700679 if (!dir.exists()) {
680 dir.mkdir();
681 FileUtils.setPermissions(
682 dir.getPath(),
683 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
684 -1, -1);
685 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700686 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100687 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
688 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700689 info.iconPath = file.getAbsolutePath();
690 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700691 try {
692 os.close();
693 } catch (IOException ioe) {
694 // What the ... !
695 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100696 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700697 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700698 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700699 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700700 }
701
Amith Yamasani0b285492011-04-14 17:35:23 -0700702 /**
703 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
704 * cache it elsewhere.
705 * @return the array of user ids.
706 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700707 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700708 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700709 return mUserIds;
710 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700711 }
712
Dianne Hackborn4428e172012-08-24 17:43:05 -0700713 int[] getUserIdsLPr() {
714 return mUserIds;
715 }
716
Amith Yamasani13593602012-03-22 16:16:17 -0700717 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700718 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700719 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720 return;
721 }
722 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700723 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700724 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700725 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100727 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700728 int type;
729 while ((type = parser.next()) != XmlPullParser.START_TAG
730 && type != XmlPullParser.END_DOCUMENT) {
731 ;
732 }
733
734 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700735 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700736 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700737 return;
738 }
739
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 mNextSerialNumber = -1;
741 if (parser.getName().equals(TAG_USERS)) {
742 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
743 if (lastSerialNumber != null) {
744 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
745 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700746 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
747 if (versionNumber != null) {
748 mUserVersion = Integer.parseInt(versionNumber);
749 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700750 }
751
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700752 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530753 if (type == XmlPullParser.START_TAG) {
754 final String name = parser.getName();
755 if (name.equals(TAG_USER)) {
756 String id = parser.getAttributeValue(null, ATTR_ID);
757 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700758
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530759 if (user != null) {
760 mUsers.put(user.id, user);
761 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
762 mNextSerialNumber = user.id + 1;
763 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700764 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530765 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800766 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
767 && type != XmlPullParser.END_TAG) {
768 if (type == XmlPullParser.START_TAG) {
769 if (parser.getName().equals(TAG_RESTRICTIONS)) {
770 readRestrictionsLocked(parser, mGuestRestrictions);
771 }
772 break;
773 }
774 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700775 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700776 }
777 }
Amith Yamasani13593602012-03-22 16:16:17 -0700778 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700779 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700781 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700782 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700783 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800784 } finally {
785 if (fis != null) {
786 try {
787 fis.close();
788 } catch (IOException e) {
789 }
790 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700791 }
792 }
793
Amith Yamasani6f34b412012-10-22 18:19:27 -0700794 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800795 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700796 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700797 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700798 int userVersion = mUserVersion;
799 if (userVersion < 1) {
800 // Assign a proper name for the owner, if not initialized correctly before
801 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
802 if ("Primary".equals(user.name)) {
803 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800804 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700805 }
806 userVersion = 1;
807 }
808
Amith Yamasanibc9625052012-11-15 14:39:18 -0800809 if (userVersion < 2) {
810 // Owner should be marked as initialized
811 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
812 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
813 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800814 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800815 }
816 userVersion = 2;
817 }
818
Amith Yamasani350962c2013-08-06 11:18:53 -0700819
Amith Yamasani5e486f52013-08-07 11:06:44 -0700820 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700821 userVersion = 4;
822 }
823
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700824 if (userVersion < 5) {
825 initDefaultGuestRestrictions();
826 userVersion = 5;
827 }
828
Amith Yamasani6f34b412012-10-22 18:19:27 -0700829 if (userVersion < USER_VERSION) {
830 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
831 + USER_VERSION);
832 } else {
833 mUserVersion = userVersion;
834 writeUserListLocked();
835 }
836 }
837
Amith Yamasani13593602012-03-22 16:16:17 -0700838 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800840 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700841 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700842 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700843 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700844 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400845 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800846
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500847 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800848 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
849
Amith Yamasani13593602012-03-22 16:16:17 -0700850 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700851 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852
Amith Yamasani13593602012-03-22 16:16:17 -0700853 writeUserListLocked();
854 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700855 }
856
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800857 private void scheduleWriteUserLocked(UserInfo userInfo) {
858 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
859 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
860 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
861 }
862 }
863
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700864 /*
865 * Writes the user file in this format:
866 *
867 * <user flags="20039023" id="0">
868 * <name>Primary</name>
869 * </user>
870 */
Amith Yamasani13593602012-03-22 16:16:17 -0700871 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700872 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700873 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700874 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700875 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700876 final BufferedOutputStream bos = new BufferedOutputStream(fos);
877
878 // XmlSerializer serializer = XmlUtils.serializerInstance();
879 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100880 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700881 serializer.startDocument(null, true);
882 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
883
884 serializer.startTag(null, TAG_USER);
885 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700886 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700887 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700888 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
889 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
890 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700891 if (userInfo.iconPath != null) {
892 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
893 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700894 if (userInfo.partial) {
895 serializer.attribute(null, ATTR_PARTIAL, "true");
896 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700897 if (userInfo.guestToRemove) {
898 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
899 }
Kenny Guy2a764942014-04-02 13:29:20 +0100900 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
901 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
902 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000903 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700904
905 serializer.startTag(null, TAG_NAME);
906 serializer.text(userInfo.name);
907 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800908 Bundle restrictions = mUserRestrictions.get(userInfo.id);
909 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530910 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800911 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700912 serializer.endTag(null, TAG_USER);
913
914 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700915 userFile.finishWrite(fos);
916 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700917 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700918 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700919 }
920 }
921
922 /*
923 * Writes the user list file in this format:
924 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700925 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 * <user id="0"></user>
927 * <user id="2"></user>
928 * </users>
929 */
Amith Yamasani13593602012-03-22 16:16:17 -0700930 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700931 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700932 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700933 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700934 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700935 final BufferedOutputStream bos = new BufferedOutputStream(fos);
936
937 // XmlSerializer serializer = XmlUtils.serializerInstance();
938 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100939 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940 serializer.startDocument(null, true);
941 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
942
943 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700945 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700946
Adam Lesinskieddeb492014-09-08 17:50:03 -0700947 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530948 writeRestrictionsLocked(serializer, mGuestRestrictions);
949 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950 for (int i = 0; i < mUsers.size(); i++) {
951 UserInfo user = mUsers.valueAt(i);
952 serializer.startTag(null, TAG_USER);
953 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
954 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700955 }
956
957 serializer.endTag(null, TAG_USERS);
958
959 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700960 userListFile.finishWrite(fos);
961 } catch (Exception e) {
962 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700963 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700964 }
965 }
966
Andres Moralesc5548c02015-08-05 10:23:12 -0700967 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530968 throws IOException {
969 serializer.startTag(null, TAG_RESTRICTIONS);
970 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
971 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
972 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
973 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
974 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
975 writeBoolean(serializer, restrictions,
976 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
977 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
978 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
979 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
980 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
981 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
982 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
983 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -0700984 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530985 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
986 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
987 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
988 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
989 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
990 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
991 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
992 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
993 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700994 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
995 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -0700996 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -0400997 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001001 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001002 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301003 serializer.endTag(null, TAG_RESTRICTIONS);
1004 }
1005
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001006 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001007 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001008 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001009 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001010 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001011 long creationTime = 0L;
1012 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001013 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001014 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001015 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001016 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001017
1018 FileInputStream fis = null;
1019 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001020 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001021 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001022 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001023 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001024 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001025 int type;
1026 while ((type = parser.next()) != XmlPullParser.START_TAG
1027 && type != XmlPullParser.END_DOCUMENT) {
1028 ;
1029 }
1030
1031 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001032 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 return null;
1034 }
1035
1036 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001037 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1038 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001039 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001040 return null;
1041 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001042 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1043 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001044 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001045 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1046 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001047 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1048 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001049 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1050 if ("true".equals(valueString)) {
1051 partial = true;
1052 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001053 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1054 if ("true".equals(valueString)) {
1055 guestToRemove = true;
1056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001058 int outerDepth = parser.getDepth();
1059 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1060 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1061 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1062 continue;
1063 }
1064 String tag = parser.getName();
1065 if (TAG_NAME.equals(tag)) {
1066 type = parser.next();
1067 if (type == XmlPullParser.TEXT) {
1068 name = parser.getText();
1069 }
1070 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301071 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 }
1073 }
1074 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001075
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001076 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001077 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001078 userInfo.creationTime = creationTime;
1079 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001080 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001081 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001082 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001083 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001084 return userInfo;
1085
1086 } catch (IOException ioe) {
1087 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001088 } finally {
1089 if (fis != null) {
1090 try {
1091 fis.close();
1092 } catch (IOException e) {
1093 }
1094 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001095 }
1096 return null;
1097 }
1098
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301099 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1100 throws IOException {
1101 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1102 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1103 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1104 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1105 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1106 readBoolean(parser, restrictions,
1107 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1108 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1109 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1110 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1111 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1112 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1113 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1114 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -07001115 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301116 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1117 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1118 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1119 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1120 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1121 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1122 readBoolean(parser, restrictions,
1123 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1124 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1125 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001126 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1127 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001128 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001129 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001130 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1131 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001132 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001133 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001134 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301135 }
1136
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001137 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1138 String restrictionKey) {
1139 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001140 if (value != null) {
1141 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1142 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001143 }
1144
1145 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1146 throws IOException {
1147 if (restrictions.containsKey(restrictionKey)) {
1148 xml.attribute(null, restrictionKey,
1149 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1150 }
1151 }
1152
Amith Yamasani920ace02012-09-20 22:15:37 -07001153 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1154 String valueString = parser.getAttributeValue(null, attr);
1155 if (valueString == null) return defaultValue;
1156 try {
1157 return Integer.parseInt(valueString);
1158 } catch (NumberFormatException nfe) {
1159 return defaultValue;
1160 }
1161 }
1162
1163 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1164 String valueString = parser.getAttributeValue(null, attr);
1165 if (valueString == null) return defaultValue;
1166 try {
1167 return Long.parseLong(valueString);
1168 } catch (NumberFormatException nfe) {
1169 return defaultValue;
1170 }
1171 }
1172
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001173 private boolean isPackageInstalled(String pkg, int userId) {
1174 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1175 PackageManager.GET_UNINSTALLED_PACKAGES,
1176 userId);
1177 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1178 return false;
1179 }
1180 return true;
1181 }
1182
Amith Yamasanib82add22013-07-09 11:24:44 -07001183 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001184 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001185 * Does not do any permissions checking.
1186 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001187 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001188 synchronized (mPackagesLock) {
1189 File dir = Environment.getUserSystemDirectory(userId);
1190 String[] files = dir.list();
1191 if (files == null) return;
1192 for (String fileName : files) {
1193 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1194 File resFile = new File(dir, fileName);
1195 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001196 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001197 }
1198 }
1199 }
1200 }
1201 }
1202
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001203 /**
1204 * Removes the app restrictions file for a specific package and user id, if it exists.
1205 */
1206 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1207 synchronized (mPackagesLock) {
1208 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001209 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001210 if (resFile.exists()) {
1211 resFile.delete();
1212 }
1213 }
1214 }
1215
Kenny Guya52dc3e2014-02-11 15:33:14 +00001216 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001217 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001218 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001219 if (userId != UserHandle.USER_OWNER) {
1220 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001221 return null;
1222 }
Kenny Guy2a764942014-04-02 13:29:20 +01001223 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001224 }
1225
Amith Yamasani258848d2012-08-10 17:06:33 -07001226 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001227 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001228 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001229 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001230 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001231
Jessica Hummelbe81c802014-04-22 15:49:22 +01001232 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001233 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1234 UserManager.DISALLOW_ADD_USER, false)) {
1235 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1236 return null;
1237 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001238 if (ActivityManager.isLowRamDeviceStatic()) {
1239 return null;
1240 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001241 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot72434b72015-05-13 12:15:03 -07001242 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001243 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001244 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001245 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001246 try {
1247 synchronized (mInstallLock) {
1248 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001249 UserInfo parent = null;
1250 if (parentId != UserHandle.USER_NULL) {
1251 parent = getUserInfoLocked(parentId);
1252 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001253 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001254 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1255 return null;
1256 }
1257 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1258 // If we're not adding a guest user or a managed profile and the limit has
1259 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001260 return null;
1261 }
1262 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001263 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001264 return null;
1265 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001266 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001267 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001268 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001269 long now = System.currentTimeMillis();
1270 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001271 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001272 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001273 mUsers.put(userId, userInfo);
1274 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001275 if (parent != null) {
1276 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1277 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001278 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001279 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001280 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001281 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001282 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1283 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1284 final String volumeUuid = vol.getFsUuid();
1285 try {
1286 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1287 userId);
1288 prepareUserDirectory(userDir);
1289 enforceSerialNumber(userDir, userInfo.serialNumber);
1290 } catch (IOException e) {
1291 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1292 }
1293 }
1294 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001295 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001296 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001297 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001298 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001299 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001300 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001301 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001302 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001303 if (userInfo != null) {
1304 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1305 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1306 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1307 android.Manifest.permission.MANAGE_USERS);
1308 }
1309 } finally {
1310 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001311 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001312 return userInfo;
1313 }
1314
Amith Yamasani95ab7842014-08-11 17:09:26 -07001315 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1316 int count = 0;
1317 for (int i = mUsers.size() - 1; i >= 0; i--) {
1318 UserInfo user = mUsers.valueAt(i);
1319 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1320 if ((user.flags & flags) != 0) {
1321 count++;
1322 }
1323 }
1324 }
1325 return count;
1326 }
1327
Amith Yamasani0b285492011-04-14 17:35:23 -07001328 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001329 * Find the current guest user. If the Guest user is partial,
1330 * then do not include it in the results as it is about to die.
1331 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1332 * the special handling of Guests being removed.
1333 */
1334 private UserInfo findCurrentGuestUserLocked() {
1335 final int size = mUsers.size();
1336 for (int i = 0; i < size; i++) {
1337 final UserInfo user = mUsers.valueAt(i);
1338 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1339 return user;
1340 }
1341 }
1342 return null;
1343 }
1344
1345 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001346 * Mark this guest user for deletion to allow us to create another guest
1347 * and switch to that user before actually removing this guest.
1348 * @param userHandle the userid of the current guest
1349 * @return whether the user could be marked for deletion
1350 */
1351 public boolean markGuestForDeletion(int userHandle) {
1352 checkManageUsersPermission("Only the system can remove users");
1353 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1354 UserManager.DISALLOW_REMOVE_USER, false)) {
1355 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1356 return false;
1357 }
1358
1359 long ident = Binder.clearCallingIdentity();
1360 try {
1361 final UserInfo user;
1362 synchronized (mPackagesLock) {
1363 user = mUsers.get(userHandle);
1364 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1365 return false;
1366 }
1367 if (!user.isGuest()) {
1368 return false;
1369 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001370 // We set this to a guest user that is to be removed. This is a temporary state
1371 // where we are allowed to add new Guest users, even if this one is still not
1372 // removed. This user will still show up in getUserInfo() calls.
1373 // If we don't get around to removing this Guest user, it will be purged on next
1374 // startup.
1375 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001376 // Mark it as disabled, so that it isn't returned any more when
1377 // profiles are queried.
1378 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001379 writeUserLocked(user);
1380 }
1381 } finally {
1382 Binder.restoreCallingIdentity(ident);
1383 }
1384 return true;
1385 }
1386
1387 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001388 * Removes a user and all data directories created for that user. This method should be called
1389 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001390 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001391 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001392 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001393 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001394 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1395 UserManager.DISALLOW_REMOVE_USER, false)) {
1396 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1397 return false;
1398 }
1399
Kenny Guyee58b4f2014-05-23 15:19:53 +01001400 long ident = Binder.clearCallingIdentity();
1401 try {
1402 final UserInfo user;
1403 synchronized (mPackagesLock) {
1404 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001405 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001406 return false;
1407 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001408
1409 // We remember deleted user IDs to prevent them from being
1410 // reused during the current boot; they can still be reused
1411 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001412 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001413
Kenny Guyee58b4f2014-05-23 15:19:53 +01001414 try {
1415 mAppOpsService.removeUser(userHandle);
1416 } catch (RemoteException e) {
1417 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1418 }
1419 // Set this to a partially created user, so that the user will be purged
1420 // on next startup, in case the runtime stops now before stopping and
1421 // removing the user completely.
1422 user.partial = true;
1423 // Mark it as disabled, so that it isn't returned any more when
1424 // profiles are queried.
1425 user.flags |= UserInfo.FLAG_DISABLED;
1426 writeUserLocked(user);
1427 }
1428
1429 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1430 && user.isManagedProfile()) {
1431 // Send broadcast to notify system that the user removed was a
1432 // managed user.
1433 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1434 }
1435
1436 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1437 int res;
1438 try {
1439 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1440 new IStopUserCallback.Stub() {
1441 @Override
1442 public void userStopped(int userId) {
1443 finishRemoveUser(userId);
1444 }
1445 @Override
1446 public void userStopAborted(int userId) {
1447 }
1448 });
1449 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001450 return false;
1451 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001452 return res == ActivityManager.USER_OP_SUCCESS;
1453 } finally {
1454 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001455 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001456 }
1457
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001458 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001459 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001460 // Let other services shutdown any activity and clean up their state before completely
1461 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001462 long ident = Binder.clearCallingIdentity();
1463 try {
1464 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1465 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001466 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1467 android.Manifest.permission.MANAGE_USERS,
1468
1469 new BroadcastReceiver() {
1470 @Override
1471 public void onReceive(Context context, Intent intent) {
1472 if (DBG) {
1473 Slog.i(LOG_TAG,
1474 "USER_REMOVED broadcast sent, cleaning up user data "
1475 + userHandle);
1476 }
1477 new Thread() {
1478 public void run() {
1479 synchronized (mInstallLock) {
1480 synchronized (mPackagesLock) {
1481 removeUserStateLocked(userHandle);
1482 }
1483 }
1484 }
1485 }.start();
1486 }
1487 },
1488
1489 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001490 } finally {
1491 Binder.restoreCallingIdentity(ident);
1492 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001493 }
1494
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001495 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001496 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001497 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001498
1499 // Remove this user from the list
1500 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001501 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001502 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001503 userFile.delete();
1504 // Update the user list
1505 writeUserListLocked();
1506 updateUserIdsLocked();
1507 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1508 }
1509
Amith Yamasani61f57372012-08-31 12:12:28 -07001510 private void removeDirectoryRecursive(File parent) {
1511 if (parent.isDirectory()) {
1512 String[] files = parent.list();
1513 for (String filename : files) {
1514 File child = new File(parent, filename);
1515 removeDirectoryRecursive(child);
1516 }
1517 }
1518 parent.delete();
1519 }
1520
Kenny Guyf8d3a232014-05-15 16:09:52 +01001521 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001522 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001523 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1524 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001525 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1526 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001527 }
1528
Amith Yamasani2a003292012-08-14 18:25:45 -07001529 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001530 public Bundle getApplicationRestrictions(String packageName) {
1531 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1532 }
1533
1534 @Override
1535 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001536 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001537 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001538 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001539 }
1540 synchronized (mPackagesLock) {
1541 // Read the restrictions from XML
1542 return readApplicationRestrictionsLocked(packageName, userId);
1543 }
1544 }
1545
1546 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001547 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001548 int userId) {
1549 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001550 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001551 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001552 }
1553 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001554 if (restrictions == null || restrictions.isEmpty()) {
1555 cleanAppRestrictionsForPackage(packageName, userId);
1556 } else {
1557 // Write the restrictions to XML
1558 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1559 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001560 }
Robin Lee66e5d962014-04-09 16:44:21 +01001561
Kenny Guyd21b2182014-07-17 16:38:55 +01001562 if (isPackageInstalled(packageName, userId)) {
1563 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1564 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1565 changeIntent.setPackage(packageName);
1566 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1567 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1568 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001569 }
1570
Amith Yamasani655d0e22013-06-12 14:19:10 -07001571 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001572 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001573 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001574 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001575 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001576 }
1577
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001578 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001579 synchronized (mPackagesLock) {
1580 // Remove all user restrictions
1581 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001582 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001583 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001584 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001585 if (unhideApps) {
1586 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001587 }
1588 }
1589
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001590 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001591 mHandler.post(new Runnable() {
1592 @Override
1593 public void run() {
1594 List<ApplicationInfo> apps =
1595 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1596 userHandle).getList();
1597 final long ident = Binder.clearCallingIdentity();
1598 try {
1599 for (ApplicationInfo appInfo : apps) {
1600 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001601 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1602 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001603 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001604 userHandle);
1605 }
1606 }
1607 } finally {
1608 Binder.restoreCallingIdentity(ident);
1609 }
1610 }
1611 });
1612 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001613 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001614 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001615 try {
1616 return mContext.getPackageManager().getApplicationInfo(packageName,
1617 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1618 } catch (NameNotFoundException nnfe) {
1619 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001620 } finally {
1621 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001622 }
1623 }
1624
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001625 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001626 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001627 AtomicFile restrictionsFile =
1628 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1629 packageToRestrictionsFileName(packageName)));
1630 return readApplicationRestrictionsLocked(restrictionsFile);
1631 }
1632
1633 @VisibleForTesting
1634 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001635 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001636 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001637 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001638 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001639 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001640
1641 FileInputStream fis = null;
1642 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001643 fis = restrictionsFile.openRead();
1644 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001645 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001646 XmlUtils.nextElement(parser);
1647 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001648 Slog.e(LOG_TAG, "Unable to read restrictions file "
1649 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001650 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001652 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1653 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001655 } catch (IOException|XmlPullParserException e) {
1656 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001657 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001658 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001659 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001660 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 }
1662
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001663 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1664 XmlPullParser parser) throws XmlPullParserException, IOException {
1665 int type = parser.getEventType();
1666 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1667 String key = parser.getAttributeValue(null, ATTR_KEY);
1668 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1669 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1670 if (multiple != null) {
1671 values.clear();
1672 int count = Integer.parseInt(multiple);
1673 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1674 if (type == XmlPullParser.START_TAG
1675 && parser.getName().equals(TAG_VALUE)) {
1676 values.add(parser.nextText().trim());
1677 count--;
1678 }
1679 }
1680 String [] valueStrings = new String[values.size()];
1681 values.toArray(valueStrings);
1682 restrictions.putStringArray(key, valueStrings);
1683 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1684 restrictions.putBundle(key, readBundleEntry(parser, values));
1685 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1686 final int outerDepth = parser.getDepth();
1687 ArrayList<Bundle> bundleList = new ArrayList<>();
1688 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1689 Bundle childBundle = readBundleEntry(parser, values);
1690 bundleList.add(childBundle);
1691 }
1692 restrictions.putParcelableArray(key,
1693 bundleList.toArray(new Bundle[bundleList.size()]));
1694 } else {
1695 String value = parser.nextText().trim();
1696 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1697 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1698 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1699 restrictions.putInt(key, Integer.parseInt(value));
1700 } else {
1701 restrictions.putString(key, value);
1702 }
1703 }
1704 }
1705 }
1706
1707 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1708 throws IOException, XmlPullParserException {
1709 Bundle childBundle = new Bundle();
1710 final int outerDepth = parser.getDepth();
1711 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1712 readEntry(childBundle, values, parser);
1713 }
1714 return childBundle;
1715 }
1716
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001717 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001718 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001719 AtomicFile restrictionsFile = new AtomicFile(
1720 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001721 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001722 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1723 }
1724
1725 @VisibleForTesting
1726 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1727 AtomicFile restrictionsFile) {
1728 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001729 try {
1730 fos = restrictionsFile.startWrite();
1731 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1732
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001733 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001734 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001735 serializer.startDocument(null, true);
1736 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1737
1738 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001739 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001740 serializer.endTag(null, TAG_RESTRICTIONS);
1741
1742 serializer.endDocument();
1743 restrictionsFile.finishWrite(fos);
1744 } catch (Exception e) {
1745 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001746 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1747 }
1748 }
1749
1750 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1751 throws IOException {
1752 for (String key : restrictions.keySet()) {
1753 Object value = restrictions.get(key);
1754 serializer.startTag(null, TAG_ENTRY);
1755 serializer.attribute(null, ATTR_KEY, key);
1756
1757 if (value instanceof Boolean) {
1758 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1759 serializer.text(value.toString());
1760 } else if (value instanceof Integer) {
1761 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1762 serializer.text(value.toString());
1763 } else if (value == null || value instanceof String) {
1764 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1765 serializer.text(value != null ? (String) value : "");
1766 } else if (value instanceof Bundle) {
1767 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1768 writeBundle((Bundle) value, serializer);
1769 } else if (value instanceof Parcelable[]) {
1770 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1771 Parcelable[] array = (Parcelable[]) value;
1772 for (Parcelable parcelable : array) {
1773 if (!(parcelable instanceof Bundle)) {
1774 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1775 }
1776 serializer.startTag(null, TAG_ENTRY);
1777 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1778 writeBundle((Bundle) parcelable, serializer);
1779 serializer.endTag(null, TAG_ENTRY);
1780 }
1781 } else {
1782 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1783 String[] values = (String[]) value;
1784 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1785 for (String choice : values) {
1786 serializer.startTag(null, TAG_VALUE);
1787 serializer.text(choice != null ? choice : "");
1788 serializer.endTag(null, TAG_VALUE);
1789 }
1790 }
1791 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001792 }
1793 }
1794
1795 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001796 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001797 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001798 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001799 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001800 }
1801 }
1802
1803 @Override
1804 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001805 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001806 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001807 UserInfo info = getUserInfoLocked(userId);
1808 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001809 }
1810 // Not found
1811 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001812 }
1813 }
1814
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001815 @Override
1816 public long getUserCreationTime(int userHandle) {
1817 int callingUserId = UserHandle.getCallingUserId();
1818 UserInfo userInfo = null;
1819 synchronized (mPackagesLock) {
1820 if (callingUserId == userHandle) {
1821 userInfo = getUserInfoLocked(userHandle);
1822 } else {
1823 UserInfo parent = getProfileParentLocked(userHandle);
1824 if (parent != null && parent.id == callingUserId) {
1825 userInfo = getUserInfoLocked(userHandle);
1826 }
1827 }
1828 }
1829 if (userInfo == null) {
1830 throw new SecurityException("userHandle can only be the calling user or a managed "
1831 + "profile associated with this user");
1832 }
1833 return userInfo.creationTime;
1834 }
1835
Amith Yamasani0b285492011-04-14 17:35:23 -07001836 /**
1837 * Caches the list of user ids in an array, adjusting the array size when necessary.
1838 */
Amith Yamasani13593602012-03-22 16:16:17 -07001839 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001840 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001841 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001842 if (!mUsers.valueAt(i).partial) {
1843 num++;
1844 }
1845 }
Amith Yamasani16389312012-10-17 21:20:14 -07001846 final int[] newUsers = new int[num];
1847 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001848 for (int i = 0; i < mUsers.size(); i++) {
1849 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001850 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001851 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001852 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001853 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001854 }
1855
1856 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001857 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001858 * @param userId the user that was just foregrounded
1859 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001860 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001861 synchronized (mPackagesLock) {
1862 UserInfo user = mUsers.get(userId);
1863 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001864 if (user == null || user.partial) {
1865 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1866 return;
1867 }
1868 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001869 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001870 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001871 }
1872 }
1873 }
1874
1875 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001876 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001877 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1878 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001879 * @return
1880 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001881 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001882 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001883 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001884 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001885 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001886 break;
1887 }
1888 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001889 }
Amith Yamasani195263742012-08-21 15:40:12 -07001890 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001891 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001892 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001893
Amith Yamasanifc95e702013-09-26 13:20:17 -07001894 private String packageToRestrictionsFileName(String packageName) {
1895 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1896 }
1897
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001898 /**
1899 * Create new {@code /data/user/[id]} directory and sets default
1900 * permissions.
1901 */
1902 public static void prepareUserDirectory(File file) throws IOException {
1903 if (!file.exists()) {
1904 if (!file.mkdir()) {
1905 throw new IOException("Failed to create " + file);
1906 }
1907 }
1908 if (FileUtils.setPermissions(file.getAbsolutePath(), 0771, Process.SYSTEM_UID,
1909 Process.SYSTEM_UID) != 0) {
1910 throw new IOException("Failed to prepare " + file);
1911 }
1912 }
1913
1914 /**
1915 * Enforce that serial number stored in user directory inode matches the
1916 * given expected value. Gracefully sets the serial number if currently
1917 * undefined.
1918 *
1919 * @throws IOException when problem extracting serial number, or serial
1920 * number is mismatched.
1921 */
1922 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1923 final int foundSerial = getSerialNumber(file);
1924 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1925
1926 if (foundSerial == -1) {
1927 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1928 try {
1929 setSerialNumber(file, serialNumber);
1930 } catch (IOException e) {
1931 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1932 }
1933
1934 } else if (foundSerial != serialNumber) {
1935 throw new IOException("Found serial number " + foundSerial
1936 + " doesn't match expected " + serialNumber);
1937 }
1938 }
1939
1940 /**
1941 * Set serial number stored in user directory inode.
1942 *
1943 * @throws IOException if serial number was already set
1944 */
1945 private static void setSerialNumber(File file, int serialNumber)
1946 throws IOException {
1947 try {
1948 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1949 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1950 } catch (ErrnoException e) {
1951 throw e.rethrowAsIOException();
1952 }
1953 }
1954
1955 /**
1956 * Return serial number stored in user directory inode.
1957 *
1958 * @return parsed serial number, or -1 if not set
1959 */
1960 private static int getSerialNumber(File file) throws IOException {
1961 try {
1962 final byte[] buf = new byte[256];
1963 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1964 final String serial = new String(buf, 0, len);
1965 try {
1966 return Integer.parseInt(serial);
1967 } catch (NumberFormatException e) {
1968 throw new IOException("Bad serial number: " + serial);
1969 }
1970 } catch (ErrnoException e) {
1971 if (e.errno == OsConstants.ENODATA) {
1972 return -1;
1973 } else {
1974 throw e.rethrowAsIOException();
1975 }
1976 }
1977 }
1978
Amith Yamasani920ace02012-09-20 22:15:37 -07001979 @Override
1980 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1981 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1982 != PackageManager.PERMISSION_GRANTED) {
1983 pw.println("Permission Denial: can't dump UserManager from from pid="
1984 + Binder.getCallingPid()
1985 + ", uid=" + Binder.getCallingUid()
1986 + " without permission "
1987 + android.Manifest.permission.DUMP);
1988 return;
1989 }
1990
1991 long now = System.currentTimeMillis();
1992 StringBuilder sb = new StringBuilder();
1993 synchronized (mPackagesLock) {
1994 pw.println("Users:");
1995 for (int i = 0; i < mUsers.size(); i++) {
1996 UserInfo user = mUsers.valueAt(i);
1997 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001998 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001999 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002000 if (user.partial) pw.print(" <partial>");
2001 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002002 pw.print(" Created: ");
2003 if (user.creationTime == 0) {
2004 pw.println("<unknown>");
2005 } else {
2006 sb.setLength(0);
2007 TimeUtils.formatDuration(now - user.creationTime, sb);
2008 sb.append(" ago");
2009 pw.println(sb);
2010 }
2011 pw.print(" Last logged in: ");
2012 if (user.lastLoggedInTime == 0) {
2013 pw.println("<unknown>");
2014 } else {
2015 sb.setLength(0);
2016 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2017 sb.append(" ago");
2018 pw.println(sb);
2019 }
2020 }
2021 }
2022 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002023
2024 final class MainHandler extends Handler {
2025
2026 @Override
2027 public void handleMessage(Message msg) {
2028 switch (msg.what) {
2029 case WRITE_USER_MSG:
2030 removeMessages(WRITE_USER_MSG, msg.obj);
2031 synchronized (mPackagesLock) {
2032 int userId = ((UserInfo) msg.obj).id;
2033 UserInfo userInfo = mUsers.get(userId);
2034 if (userInfo != null) {
2035 writeUserLocked(userInfo);
2036 }
2037 }
2038 }
2039 }
2040 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002041
2042 /**
2043 * @param userId
2044 * @return whether the user has been initialized yet
2045 */
2046 boolean isInitialized(int userId) {
2047 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2048 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049}