blob: 8dccfdfb22715e7d6caf606dc0911e937d0564c8 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080032import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.os.Environment;
34import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080035import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080037import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010038import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070039import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Fyodor Kupolovb5013302015-04-17 17:59:14 -070053import com.google.android.collect.Sets;
54
Fyodor Kupolov262f9952015-03-23 18:55:11 -070055import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040056import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import com.android.internal.util.ArrayUtils;
58import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070059import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080060
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63import org.xmlpull.v1.XmlSerializer;
64
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.BufferedOutputStream;
66import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070067import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070069import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import java.io.FileOutputStream;
71import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070072import java.io.PrintWriter;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070075import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076
Fyodor Kupolov262f9952015-03-23 18:55:11 -070077import libcore.io.IoUtils;
78
Amith Yamasani258848d2012-08-10 17:06:33 -070079public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani2a003292012-08-14 18:25:45 -070081 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082
Amith Yamasani16389312012-10-17 21:20:14 -070083 private static final boolean DBG = false;
84
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070089 private static final String ATTR_CREATION_TIME = "created";
90 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070094 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070095 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010096 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053097 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700110 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700111 private static final String ATTR_TYPE_BUNDLE = "B";
112 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700113
Amith Yamasani0b285492011-04-14 17:35:23 -0700114 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700116 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100117 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800119 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700120 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800121
Amith Yamasani634cf312012-10-04 17:34:21 -0700122 private static final int MIN_USER_ID = 10;
123
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700124 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700125
Amith Yamasani920ace02012-09-20 22:15:37 -0700126 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
127
Amith Yamasani95ab7842014-08-11 17:09:26 -0700128 // Maximum number of managed profiles permitted is 1. This cannot be increased
129 // without first making sure that the rest of the framework is prepared for it.
130 private static final int MAX_MANAGED_PROFILES = 1;
131
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700132 // Set of user restrictions, which can only be enforced by the system
133 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
134 UserManager.DISALLOW_RECORD_AUDIO);
135
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800136 static final int WRITE_USER_MSG = 1;
137 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530138
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final Context mContext;
140 private final PackageManagerService mPm;
141 private final Object mInstallLock;
142 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800144 private final Handler mHandler;
145
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private final File mUsersDir;
147 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700148 private final File mBaseUserPath;
149
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800150 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800151 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530152 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800153
154 /**
155 * Set of user IDs being actively removed. Removed IDs linger in this set
156 * for several seconds to work around a VFS caching issue.
157 */
158 // @GuardedBy("mPackagesLock")
159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700162 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700164
Jason Monk62062992014-05-06 09:55:28 -0400165 private IAppOpsService mAppOpsService;
166
Amith Yamasani258848d2012-08-10 17:06:33 -0700167 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700168
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169 public static UserManagerService getInstance() {
170 synchronized (UserManagerService.class) {
171 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700173 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174
175 /**
176 * Available for testing purposes.
177 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180 }
181
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 /**
183 * Called by package manager to create the service. This is closely
184 * associated with the package manager, and the given lock is the
185 * package manager's own lock.
186 */
187 UserManagerService(Context context, PackageManagerService pm,
188 Object installLock, Object packagesLock) {
189 this(context, pm, installLock, packagesLock,
190 Environment.getDataDirectory(),
191 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 }
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 /**
195 * Available for testing purposes.
196 */
197 private UserManagerService(Context context, PackageManagerService pm,
198 Object installLock, Object packagesLock,
199 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700200 mContext = context;
201 mPm = pm;
202 mInstallLock = installLock;
203 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800204 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700205 synchronized (mInstallLock) {
206 synchronized (mPackagesLock) {
207 mUsersDir = new File(dataDir, USER_INFO_DIR);
208 mUsersDir.mkdirs();
209 // Make zeroth user directory, for services to migrate their files to that location
210 File userZeroDir = new File(mUsersDir, "0");
211 userZeroDir.mkdirs();
212 mBaseUserPath = baseUserPath;
213 FileUtils.setPermissions(mUsersDir.toString(),
214 FileUtils.S_IRWXU|FileUtils.S_IRWXG
215 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
216 -1, -1);
217 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800218 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700220 sInstance = this;
221 }
222 }
223 }
224
225 void systemReady() {
226 synchronized (mInstallLock) {
227 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700228 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
230 for (int i = 0; i < mUsers.size(); i++) {
231 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700232 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700233 partials.add(ui);
234 }
235 }
236 for (int i = 0; i < partials.size(); i++) {
237 UserInfo ui = partials.get(i);
238 Slog.w(LOG_TAG, "Removing partially created user #" + i
239 + " (name=" + ui.name + ")");
240 removeUserStateLocked(ui.id);
241 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700244 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400245 mAppOpsService = IAppOpsService.Stub.asInterface(
246 ServiceManager.getService(Context.APP_OPS_SERVICE));
247 for (int i = 0; i < mUserIds.length; ++i) {
248 try {
249 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
250 } catch (RemoteException e) {
251 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
252 }
253 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700254 }
255
256 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700257 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700258 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700259 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700260 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
261 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700262 UserInfo ui = mUsers.valueAt(i);
263 if (ui.partial) {
264 continue;
265 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800266 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700268 }
Amith Yamasani13593602012-03-22 16:16:17 -0700269 }
270 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700271 }
Amith Yamasani13593602012-03-22 16:16:17 -0700272 }
273
Amith Yamasani258848d2012-08-10 17:06:33 -0700274 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100275 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800276 if (userId != UserHandle.getCallingUserId()) {
277 checkManageUsersPermission("getting profiles related to user " + userId);
278 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700279 final long ident = Binder.clearCallingIdentity();
280 try {
281 synchronized (mPackagesLock) {
282 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100283 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700284 } finally {
285 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000286 }
287 }
288
Amith Yamasanibe465322014-04-24 13:45:17 -0700289 /** Assume permissions already checked and caller's identity cleared */
290 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700291 UserInfo user = getUserInfoLocked(userId);
292 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700293 if (user == null) {
294 // Probably a dying user
295 return users;
296 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700297 for (int i = 0; i < mUsers.size(); i++) {
298 UserInfo profile = mUsers.valueAt(i);
299 if (!isProfileOf(user, profile)) {
300 continue;
301 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100302 if (enabledOnly && !profile.isEnabled()) {
303 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700304 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700305 if (mRemovingUserIds.get(profile.id)) {
306 continue;
307 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 users.add(profile);
309 }
310 return users;
311 }
312
Jessica Hummelbe81c802014-04-22 15:49:22 +0100313 @Override
314 public UserInfo getProfileParent(int userHandle) {
315 checkManageUsersPermission("get the profile parent");
316 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700317 return getProfileParentLocked(userHandle);
318 }
319 }
320
321 private UserInfo getProfileParentLocked(int userHandle) {
322 UserInfo profile = getUserInfoLocked(userHandle);
323 if (profile == null) {
324 return null;
325 }
326 int parentUserId = profile.profileGroupId;
327 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
328 return null;
329 } else {
330 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100331 }
332 }
333
Kenny Guy2a764942014-04-02 13:29:20 +0100334 private boolean isProfileOf(UserInfo user, UserInfo profile) {
335 return user.id == profile.id ||
336 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
337 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000338 }
339
340 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100341 public void setUserEnabled(int userId) {
342 checkManageUsersPermission("enable user");
343 synchronized (mPackagesLock) {
344 UserInfo info = getUserInfoLocked(userId);
345 if (info != null && !info.isEnabled()) {
346 info.flags ^= UserInfo.FLAG_DISABLED;
347 writeUserLocked(info);
348 }
349 }
350 }
351
352 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700353 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700354 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700355 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700356 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700357 }
358 }
359
Amith Yamasani71e6c692013-03-24 17:39:28 -0700360 @Override
361 public boolean isRestricted() {
362 synchronized (mPackagesLock) {
363 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
364 }
365 }
366
Amith Yamasani195263742012-08-21 15:40:12 -0700367 /*
368 * Should be locked on mUsers before calling this.
369 */
370 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700372 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800373 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700374 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
375 return null;
376 }
377 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700378 }
379
Amith Yamasani13593602012-03-22 16:16:17 -0700380 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700382 return ArrayUtils.contains(mUserIds, userId);
383 }
384 }
385
Amith Yamasani258848d2012-08-10 17:06:33 -0700386 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700387 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700388 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700389 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700390 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700391 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700392 if (info == null || info.partial) {
393 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
394 return;
395 }
Amith Yamasani13593602012-03-22 16:16:17 -0700396 if (name != null && !name.equals(info.name)) {
397 info.name = name;
398 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700399 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700400 }
401 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700402 if (changed) {
403 sendUserInfoChangedBroadcast(userId);
404 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700405 }
406
Amith Yamasani258848d2012-08-10 17:06:33 -0700407 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700408 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700409 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400410 long ident = Binder.clearCallingIdentity();
411 try {
412 synchronized (mPackagesLock) {
413 UserInfo info = mUsers.get(userId);
414 if (info == null || info.partial) {
415 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
416 return;
417 }
418 writeBitmapLocked(info, bitmap);
419 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 }
Jason Monk9a944532014-07-08 09:31:21 -0400421 sendUserInfoChangedBroadcast(userId);
422 } finally {
423 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700424 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700425 }
426
427 private void sendUserInfoChangedBroadcast(int userId) {
428 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
429 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
430 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700431 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700432 }
433
Amith Yamasani258848d2012-08-10 17:06:33 -0700434 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100435 public ParcelFileDescriptor getUserIcon(int userId) {
436 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700437 synchronized (mPackagesLock) {
438 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 if (info == null || info.partial) {
440 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
441 return null;
442 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100443 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
444 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
445 || callingGroupId != info.profileGroupId) {
446 checkManageUsersPermission("get the icon of a user who is not related");
447 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700448 if (info.iconPath == null) {
449 return null;
450 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100451 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700452 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100453
454 try {
455 return ParcelFileDescriptor.open(
456 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
457 } catch (FileNotFoundException e) {
458 Log.e(LOG_TAG, "Couldn't find icon file", e);
459 }
460 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700461 }
462
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700463 public void makeInitialized(int userId) {
464 checkManageUsersPermission("makeInitialized");
465 synchronized (mPackagesLock) {
466 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700467 if (info == null || info.partial) {
468 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
469 }
470 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700471 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800472 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700473 }
474 }
475 }
476
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700477 /**
478 * If default guest restrictions haven't been initialized yet, add the basic
479 * restrictions.
480 */
481 private void initDefaultGuestRestrictions() {
482 if (mGuestRestrictions.isEmpty()) {
483 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800484 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700485 }
486 }
487
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800488 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530489 public Bundle getDefaultGuestRestrictions() {
490 checkManageUsersPermission("getDefaultGuestRestrictions");
491 synchronized (mPackagesLock) {
492 return new Bundle(mGuestRestrictions);
493 }
494 }
495
496 @Override
497 public void setDefaultGuestRestrictions(Bundle restrictions) {
498 checkManageUsersPermission("setDefaultGuestRestrictions");
499 synchronized (mPackagesLock) {
500 mGuestRestrictions.clear();
501 mGuestRestrictions.putAll(restrictions);
502 writeUserListLocked();
503 }
504 }
505
506 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700507 public boolean hasUserRestriction(String restrictionKey, int userId) {
508 synchronized (mPackagesLock) {
509 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700510 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700511 }
512 }
513
514 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800515 public Bundle getUserRestrictions(int userId) {
516 // checkManageUsersPermission("getUserRestrictions");
517
518 synchronized (mPackagesLock) {
519 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700520 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800521 }
522 }
523
524 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700525 public void setUserRestriction(String key, boolean value, int userId) {
526 synchronized (mPackagesLock) {
527 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
528 Bundle restrictions = getUserRestrictions(userId);
529 restrictions.putBoolean(key, value);
530 setUserRestrictionsInternalLocked(restrictions, userId);
531 }
532 }
533 }
534
535 @Override
536 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
537 checkSystemOrRoot("setSystemControlledUserRestriction");
538 synchronized (mPackagesLock) {
539 Bundle restrictions = getUserRestrictions(userId);
540 restrictions.putBoolean(key, value);
541 setUserRestrictionsInternalLocked(restrictions, userId);
542 }
543 }
544
545 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800546 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700547 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700548 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800549
550 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700551 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
552 // Restore the original state of system controlled restrictions from oldUserRestrictions
553 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
554 restrictions.remove(key);
555 if (oldUserRestrictions.containsKey(key)) {
556 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
557 }
Jason Monk62062992014-05-06 09:55:28 -0400558 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700559 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800560 }
561 }
562
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700563 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
564 final Bundle userRestrictions = mUserRestrictions.get(userId);
565 userRestrictions.clear();
566 userRestrictions.putAll(restrictions);
567 long token = Binder.clearCallingIdentity();
568 try {
569 mAppOpsService.setUserRestrictions(userRestrictions, userId);
570 } catch (RemoteException e) {
571 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
572 } finally {
573 Binder.restoreCallingIdentity(token);
574 }
575 scheduleWriteUserLocked(mUsers.get(userId));
576 }
577
Amith Yamasani258848d2012-08-10 17:06:33 -0700578 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700579 * Check if we've hit the limit of how many users can be created.
580 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700581 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700582 int aliveUserCount = 0;
583 final int totalUserCount = mUsers.size();
584 // Skip over users being removed
585 for (int i = 0; i < totalUserCount; i++) {
586 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700587 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700588 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700589 aliveUserCount++;
590 }
591 }
592 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700593 }
594
595 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700596 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700597 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700598 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 *
600 * @param message used as message if SecurityException is thrown
601 * @throws SecurityException if the caller is not system or root
602 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700603 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700604 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700605 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400606 && ActivityManager.checkComponentPermission(
607 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700608 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
609 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
610 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400611 }
612
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700613 private static void checkSystemOrRoot(String message) {
614 final int uid = Binder.getCallingUid();
615 if (uid != Process.SYSTEM_UID && uid != 0) {
616 throw new SecurityException("Only system may call: " + message);
617 }
618 }
619
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700620 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700621 try {
622 File dir = new File(mUsersDir, Integer.toString(info.id));
623 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100624 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700625 if (!dir.exists()) {
626 dir.mkdir();
627 FileUtils.setPermissions(
628 dir.getPath(),
629 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
630 -1, -1);
631 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700632 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100633 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
634 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700635 info.iconPath = file.getAbsolutePath();
636 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700637 try {
638 os.close();
639 } catch (IOException ioe) {
640 // What the ... !
641 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100642 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700643 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700644 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700645 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700646 }
647
Amith Yamasani0b285492011-04-14 17:35:23 -0700648 /**
649 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
650 * cache it elsewhere.
651 * @return the array of user ids.
652 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700653 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700654 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700655 return mUserIds;
656 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700657 }
658
Dianne Hackborn4428e172012-08-24 17:43:05 -0700659 int[] getUserIdsLPr() {
660 return mUserIds;
661 }
662
Amith Yamasani13593602012-03-22 16:16:17 -0700663 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700664 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700665 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700666 return;
667 }
668 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700669 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700670 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700671 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700672 XmlPullParser parser = Xml.newPullParser();
673 parser.setInput(fis, null);
674 int type;
675 while ((type = parser.next()) != XmlPullParser.START_TAG
676 && type != XmlPullParser.END_DOCUMENT) {
677 ;
678 }
679
680 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700681 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700682 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700683 return;
684 }
685
Amith Yamasani2a003292012-08-14 18:25:45 -0700686 mNextSerialNumber = -1;
687 if (parser.getName().equals(TAG_USERS)) {
688 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
689 if (lastSerialNumber != null) {
690 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
691 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700692 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
693 if (versionNumber != null) {
694 mUserVersion = Integer.parseInt(versionNumber);
695 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700696 }
697
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530699 if (type == XmlPullParser.START_TAG) {
700 final String name = parser.getName();
701 if (name.equals(TAG_USER)) {
702 String id = parser.getAttributeValue(null, ATTR_ID);
703 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700704
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530705 if (user != null) {
706 mUsers.put(user.id, user);
707 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
708 mNextSerialNumber = user.id + 1;
709 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700710 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530711 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800712 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
713 && type != XmlPullParser.END_TAG) {
714 if (type == XmlPullParser.START_TAG) {
715 if (parser.getName().equals(TAG_RESTRICTIONS)) {
716 readRestrictionsLocked(parser, mGuestRestrictions);
717 }
718 break;
719 }
720 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700721 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 }
723 }
Amith Yamasani13593602012-03-22 16:16:17 -0700724 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700725 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700727 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700728 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700729 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800730 } finally {
731 if (fis != null) {
732 try {
733 fis.close();
734 } catch (IOException e) {
735 }
736 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700737 }
738 }
739
Amith Yamasani6f34b412012-10-22 18:19:27 -0700740 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800741 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700742 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700743 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700744 int userVersion = mUserVersion;
745 if (userVersion < 1) {
746 // Assign a proper name for the owner, if not initialized correctly before
747 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
748 if ("Primary".equals(user.name)) {
749 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800750 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700751 }
752 userVersion = 1;
753 }
754
Amith Yamasanibc9625052012-11-15 14:39:18 -0800755 if (userVersion < 2) {
756 // Owner should be marked as initialized
757 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
758 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
759 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800760 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800761 }
762 userVersion = 2;
763 }
764
Amith Yamasani350962c2013-08-06 11:18:53 -0700765
Amith Yamasani5e486f52013-08-07 11:06:44 -0700766 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700767 userVersion = 4;
768 }
769
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700770 if (userVersion < 5) {
771 initDefaultGuestRestrictions();
772 userVersion = 5;
773 }
774
Amith Yamasani6f34b412012-10-22 18:19:27 -0700775 if (userVersion < USER_VERSION) {
776 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
777 + USER_VERSION);
778 } else {
779 mUserVersion = userVersion;
780 writeUserListLocked();
781 }
782 }
783
Amith Yamasani13593602012-03-22 16:16:17 -0700784 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700785 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800786 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700787 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700788 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700789 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700790 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400791 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800792
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500793 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800794 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
795
Amith Yamasani13593602012-03-22 16:16:17 -0700796 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700797 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798
Amith Yamasani13593602012-03-22 16:16:17 -0700799 writeUserListLocked();
800 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700801 }
802
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800803 private void scheduleWriteUserLocked(UserInfo userInfo) {
804 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
805 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
806 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
807 }
808 }
809
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 /*
811 * Writes the user file in this format:
812 *
813 * <user flags="20039023" id="0">
814 * <name>Primary</name>
815 * </user>
816 */
Amith Yamasani13593602012-03-22 16:16:17 -0700817 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700818 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700819 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700820 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700821 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 final BufferedOutputStream bos = new BufferedOutputStream(fos);
823
824 // XmlSerializer serializer = XmlUtils.serializerInstance();
825 final XmlSerializer serializer = new FastXmlSerializer();
826 serializer.setOutput(bos, "utf-8");
827 serializer.startDocument(null, true);
828 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
829
830 serializer.startTag(null, TAG_USER);
831 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700832 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700834 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
835 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
836 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700837 if (userInfo.iconPath != null) {
838 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
839 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700840 if (userInfo.partial) {
841 serializer.attribute(null, ATTR_PARTIAL, "true");
842 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700843 if (userInfo.guestToRemove) {
844 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
845 }
Kenny Guy2a764942014-04-02 13:29:20 +0100846 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
847 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
848 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000849 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700850
851 serializer.startTag(null, TAG_NAME);
852 serializer.text(userInfo.name);
853 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800854 Bundle restrictions = mUserRestrictions.get(userInfo.id);
855 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530856 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800857 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700858 serializer.endTag(null, TAG_USER);
859
860 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700861 userFile.finishWrite(fos);
862 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700863 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700864 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865 }
866 }
867
868 /*
869 * Writes the user list file in this format:
870 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700871 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700872 * <user id="0"></user>
873 * <user id="2"></user>
874 * </users>
875 */
Amith Yamasani13593602012-03-22 16:16:17 -0700876 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700877 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700878 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700880 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700881 final BufferedOutputStream bos = new BufferedOutputStream(fos);
882
883 // XmlSerializer serializer = XmlUtils.serializerInstance();
884 final XmlSerializer serializer = new FastXmlSerializer();
885 serializer.setOutput(bos, "utf-8");
886 serializer.startDocument(null, true);
887 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
888
889 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700890 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700891 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700892
Adam Lesinskieddeb492014-09-08 17:50:03 -0700893 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530894 writeRestrictionsLocked(serializer, mGuestRestrictions);
895 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700896 for (int i = 0; i < mUsers.size(); i++) {
897 UserInfo user = mUsers.valueAt(i);
898 serializer.startTag(null, TAG_USER);
899 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
900 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700901 }
902
903 serializer.endTag(null, TAG_USERS);
904
905 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700906 userListFile.finishWrite(fos);
907 } catch (Exception e) {
908 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700909 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700910 }
911 }
912
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530913 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
914 throws IOException {
915 serializer.startTag(null, TAG_RESTRICTIONS);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
921 writeBoolean(serializer, restrictions,
922 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
923 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
929 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
930 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
931 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
932 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
933 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
934 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
935 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
936 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
937 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
938 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700939 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
940 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400941 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700942 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
943 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000944 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000945 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530946 serializer.endTag(null, TAG_RESTRICTIONS);
947 }
948
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800949 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700951 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700952 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700953 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700954 long creationTime = 0L;
955 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +0100956 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700957 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700958 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800959 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700960
961 FileInputStream fis = null;
962 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700963 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700964 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700965 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 XmlPullParser parser = Xml.newPullParser();
967 parser.setInput(fis, null);
968 int type;
969 while ((type = parser.next()) != XmlPullParser.START_TAG
970 && type != XmlPullParser.END_DOCUMENT) {
971 ;
972 }
973
974 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700975 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700976 return null;
977 }
978
979 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700980 int storedId = readIntAttribute(parser, ATTR_ID, -1);
981 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700982 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700983 return null;
984 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700985 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
986 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700987 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700988 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
989 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +0100990 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
991 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700992 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
993 if ("true".equals(valueString)) {
994 partial = true;
995 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700996 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
997 if ("true".equals(valueString)) {
998 guestToRemove = true;
999 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001000
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001001 int outerDepth = parser.getDepth();
1002 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1003 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1004 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1005 continue;
1006 }
1007 String tag = parser.getName();
1008 if (TAG_NAME.equals(tag)) {
1009 type = parser.next();
1010 if (type == XmlPullParser.TEXT) {
1011 name = parser.getText();
1012 }
1013 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301014 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001015 }
1016 }
1017 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001019 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001020 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001021 userInfo.creationTime = creationTime;
1022 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001023 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001024 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001025 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001026 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001027 return userInfo;
1028
1029 } catch (IOException ioe) {
1030 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001031 } finally {
1032 if (fis != null) {
1033 try {
1034 fis.close();
1035 } catch (IOException e) {
1036 }
1037 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001038 }
1039 return null;
1040 }
1041
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301042 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1043 throws IOException {
1044 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1045 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1047 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1048 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1049 readBoolean(parser, restrictions,
1050 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1051 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1059 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1060 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1061 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1064 readBoolean(parser, restrictions,
1065 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1066 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001068 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1069 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001070 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001071 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1072 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001073 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001074 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301075 }
1076
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001077 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1078 String restrictionKey) {
1079 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001080 if (value != null) {
1081 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1082 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001083 }
1084
1085 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1086 throws IOException {
1087 if (restrictions.containsKey(restrictionKey)) {
1088 xml.attribute(null, restrictionKey,
1089 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1090 }
1091 }
1092
Amith Yamasani920ace02012-09-20 22:15:37 -07001093 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1094 String valueString = parser.getAttributeValue(null, attr);
1095 if (valueString == null) return defaultValue;
1096 try {
1097 return Integer.parseInt(valueString);
1098 } catch (NumberFormatException nfe) {
1099 return defaultValue;
1100 }
1101 }
1102
1103 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1104 String valueString = parser.getAttributeValue(null, attr);
1105 if (valueString == null) return defaultValue;
1106 try {
1107 return Long.parseLong(valueString);
1108 } catch (NumberFormatException nfe) {
1109 return defaultValue;
1110 }
1111 }
1112
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001113 private boolean isPackageInstalled(String pkg, int userId) {
1114 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1115 PackageManager.GET_UNINSTALLED_PACKAGES,
1116 userId);
1117 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1118 return false;
1119 }
1120 return true;
1121 }
1122
Amith Yamasanib82add22013-07-09 11:24:44 -07001123 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001124 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001125 * Does not do any permissions checking.
1126 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001127 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001128 synchronized (mPackagesLock) {
1129 File dir = Environment.getUserSystemDirectory(userId);
1130 String[] files = dir.list();
1131 if (files == null) return;
1132 for (String fileName : files) {
1133 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1134 File resFile = new File(dir, fileName);
1135 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001136 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001137 }
1138 }
1139 }
1140 }
1141 }
1142
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001143 /**
1144 * Removes the app restrictions file for a specific package and user id, if it exists.
1145 */
1146 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1147 synchronized (mPackagesLock) {
1148 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001149 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001150 if (resFile.exists()) {
1151 resFile.delete();
1152 }
1153 }
1154 }
1155
Kenny Guya52dc3e2014-02-11 15:33:14 +00001156 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001157 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001158 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001159 if (userId != UserHandle.USER_OWNER) {
1160 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001161 return null;
1162 }
Kenny Guy2a764942014-04-02 13:29:20 +01001163 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001164 }
1165
Amith Yamasani258848d2012-08-10 17:06:33 -07001166 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001167 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001168 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001169 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001170 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001171
Jessica Hummelbe81c802014-04-22 15:49:22 +01001172 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001173 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1174 UserManager.DISALLOW_ADD_USER, false)) {
1175 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1176 return null;
1177 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001178 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001179 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001180 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001181 try {
1182 synchronized (mInstallLock) {
1183 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001184 UserInfo parent = null;
1185 if (parentId != UserHandle.USER_NULL) {
1186 parent = getUserInfoLocked(parentId);
1187 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001188 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001189 // If we're not adding a guest user and the limit has been reached,
1190 // cannot add a user.
1191 if (!isGuest && isUserLimitReachedLocked()) {
1192 return null;
1193 }
1194 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001195 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001196 return null;
1197 }
1198 // Limit number of managed profiles that can be created
1199 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1200 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1201 >= MAX_MANAGED_PROFILES) {
1202 return null;
1203 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001204 int userId = getNextAvailableIdLocked();
1205 userInfo = new UserInfo(userId, name, null, flags);
1206 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1207 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001208 long now = System.currentTimeMillis();
1209 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001210 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001211 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001212 mUsers.put(userId, userInfo);
1213 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001214 if (parent != null) {
1215 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1216 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001217 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001218 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001219 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001220 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001221 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001222 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001223 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001224 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001225 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001226 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001227 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001228 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001229 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001230 if (userInfo != null) {
1231 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1232 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1233 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1234 android.Manifest.permission.MANAGE_USERS);
1235 }
1236 } finally {
1237 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001238 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 return userInfo;
1240 }
1241
Amith Yamasani95ab7842014-08-11 17:09:26 -07001242 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1243 int count = 0;
1244 for (int i = mUsers.size() - 1; i >= 0; i--) {
1245 UserInfo user = mUsers.valueAt(i);
1246 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1247 if ((user.flags & flags) != 0) {
1248 count++;
1249 }
1250 }
1251 }
1252 return count;
1253 }
1254
Amith Yamasani0b285492011-04-14 17:35:23 -07001255 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001256 * Find the current guest user. If the Guest user is partial,
1257 * then do not include it in the results as it is about to die.
1258 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1259 * the special handling of Guests being removed.
1260 */
1261 private UserInfo findCurrentGuestUserLocked() {
1262 final int size = mUsers.size();
1263 for (int i = 0; i < size; i++) {
1264 final UserInfo user = mUsers.valueAt(i);
1265 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1266 return user;
1267 }
1268 }
1269 return null;
1270 }
1271
1272 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001273 * Mark this guest user for deletion to allow us to create another guest
1274 * and switch to that user before actually removing this guest.
1275 * @param userHandle the userid of the current guest
1276 * @return whether the user could be marked for deletion
1277 */
1278 public boolean markGuestForDeletion(int userHandle) {
1279 checkManageUsersPermission("Only the system can remove users");
1280 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1281 UserManager.DISALLOW_REMOVE_USER, false)) {
1282 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1283 return false;
1284 }
1285
1286 long ident = Binder.clearCallingIdentity();
1287 try {
1288 final UserInfo user;
1289 synchronized (mPackagesLock) {
1290 user = mUsers.get(userHandle);
1291 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1292 return false;
1293 }
1294 if (!user.isGuest()) {
1295 return false;
1296 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001297 // We set this to a guest user that is to be removed. This is a temporary state
1298 // where we are allowed to add new Guest users, even if this one is still not
1299 // removed. This user will still show up in getUserInfo() calls.
1300 // If we don't get around to removing this Guest user, it will be purged on next
1301 // startup.
1302 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001303 // Mark it as disabled, so that it isn't returned any more when
1304 // profiles are queried.
1305 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001306 writeUserLocked(user);
1307 }
1308 } finally {
1309 Binder.restoreCallingIdentity(ident);
1310 }
1311 return true;
1312 }
1313
1314 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001315 * Removes a user and all data directories created for that user. This method should be called
1316 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001317 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001318 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001319 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001320 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001321 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1322 UserManager.DISALLOW_REMOVE_USER, false)) {
1323 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1324 return false;
1325 }
1326
Kenny Guyee58b4f2014-05-23 15:19:53 +01001327 long ident = Binder.clearCallingIdentity();
1328 try {
1329 final UserInfo user;
1330 synchronized (mPackagesLock) {
1331 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001332 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001333 return false;
1334 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001335
1336 // We remember deleted user IDs to prevent them from being
1337 // reused during the current boot; they can still be reused
1338 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001339 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001340
Kenny Guyee58b4f2014-05-23 15:19:53 +01001341 try {
1342 mAppOpsService.removeUser(userHandle);
1343 } catch (RemoteException e) {
1344 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1345 }
1346 // Set this to a partially created user, so that the user will be purged
1347 // on next startup, in case the runtime stops now before stopping and
1348 // removing the user completely.
1349 user.partial = true;
1350 // Mark it as disabled, so that it isn't returned any more when
1351 // profiles are queried.
1352 user.flags |= UserInfo.FLAG_DISABLED;
1353 writeUserLocked(user);
1354 }
1355
1356 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1357 && user.isManagedProfile()) {
1358 // Send broadcast to notify system that the user removed was a
1359 // managed user.
1360 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1361 }
1362
1363 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1364 int res;
1365 try {
1366 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1367 new IStopUserCallback.Stub() {
1368 @Override
1369 public void userStopped(int userId) {
1370 finishRemoveUser(userId);
1371 }
1372 @Override
1373 public void userStopAborted(int userId) {
1374 }
1375 });
1376 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001377 return false;
1378 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001379 return res == ActivityManager.USER_OP_SUCCESS;
1380 } finally {
1381 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001382 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001383 }
1384
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001385 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001386 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001387 // Let other services shutdown any activity and clean up their state before completely
1388 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001389 long ident = Binder.clearCallingIdentity();
1390 try {
1391 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1392 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001393 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1394 android.Manifest.permission.MANAGE_USERS,
1395
1396 new BroadcastReceiver() {
1397 @Override
1398 public void onReceive(Context context, Intent intent) {
1399 if (DBG) {
1400 Slog.i(LOG_TAG,
1401 "USER_REMOVED broadcast sent, cleaning up user data "
1402 + userHandle);
1403 }
1404 new Thread() {
1405 public void run() {
1406 synchronized (mInstallLock) {
1407 synchronized (mPackagesLock) {
1408 removeUserStateLocked(userHandle);
1409 }
1410 }
1411 }
1412 }.start();
1413 }
1414 },
1415
1416 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001417 } finally {
1418 Binder.restoreCallingIdentity(ident);
1419 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001420 }
1421
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001422 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001423 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001424 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001425
1426 // Remove this user from the list
1427 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001428 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001429 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001430 userFile.delete();
1431 // Update the user list
1432 writeUserListLocked();
1433 updateUserIdsLocked();
1434 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1435 }
1436
Amith Yamasani61f57372012-08-31 12:12:28 -07001437 private void removeDirectoryRecursive(File parent) {
1438 if (parent.isDirectory()) {
1439 String[] files = parent.list();
1440 for (String filename : files) {
1441 File child = new File(parent, filename);
1442 removeDirectoryRecursive(child);
1443 }
1444 }
1445 parent.delete();
1446 }
1447
Kenny Guyf8d3a232014-05-15 16:09:52 +01001448 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001449 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001450 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1451 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001452 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1453 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001454 }
1455
Amith Yamasani2a003292012-08-14 18:25:45 -07001456 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001457 public Bundle getApplicationRestrictions(String packageName) {
1458 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1459 }
1460
1461 @Override
1462 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001463 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001464 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001465 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001466 }
1467 synchronized (mPackagesLock) {
1468 // Read the restrictions from XML
1469 return readApplicationRestrictionsLocked(packageName, userId);
1470 }
1471 }
1472
1473 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001474 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001475 int userId) {
1476 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001477 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001478 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001479 }
1480 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001481 if (restrictions == null || restrictions.isEmpty()) {
1482 cleanAppRestrictionsForPackage(packageName, userId);
1483 } else {
1484 // Write the restrictions to XML
1485 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1486 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001487 }
Robin Lee66e5d962014-04-09 16:44:21 +01001488
Kenny Guyd21b2182014-07-17 16:38:55 +01001489 if (isPackageInstalled(packageName, userId)) {
1490 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1491 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1492 changeIntent.setPackage(packageName);
1493 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1494 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1495 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001496 }
1497
Amith Yamasani655d0e22013-06-12 14:19:10 -07001498 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001499 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001500 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001501 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001502 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001503 }
1504
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001505 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001506 synchronized (mPackagesLock) {
1507 // Remove all user restrictions
1508 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001509 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001510 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001511 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001512 if (unhideApps) {
1513 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001514 }
1515 }
1516
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001517 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001518 mHandler.post(new Runnable() {
1519 @Override
1520 public void run() {
1521 List<ApplicationInfo> apps =
1522 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1523 userHandle).getList();
1524 final long ident = Binder.clearCallingIdentity();
1525 try {
1526 for (ApplicationInfo appInfo : apps) {
1527 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001528 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1529 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001530 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001531 userHandle);
1532 }
1533 }
1534 } finally {
1535 Binder.restoreCallingIdentity(ident);
1536 }
1537 }
1538 });
1539 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001540 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001541 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001542 try {
1543 return mContext.getPackageManager().getApplicationInfo(packageName,
1544 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1545 } catch (NameNotFoundException nnfe) {
1546 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001547 } finally {
1548 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001549 }
1550 }
1551
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001552 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001553 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001554 AtomicFile restrictionsFile =
1555 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1556 packageToRestrictionsFileName(packageName)));
1557 return readApplicationRestrictionsLocked(restrictionsFile);
1558 }
1559
1560 @VisibleForTesting
1561 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001562 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001563 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001564 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001565 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001566 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001567
1568 FileInputStream fis = null;
1569 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001570 fis = restrictionsFile.openRead();
1571 XmlPullParser parser = Xml.newPullParser();
1572 parser.setInput(fis, null);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001573 XmlUtils.nextElement(parser);
1574 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001575 Slog.e(LOG_TAG, "Unable to read restrictions file "
1576 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001577 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001578 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001579 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1580 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001581 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001582 } catch (IOException|XmlPullParserException e) {
1583 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001584 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001585 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001586 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001587 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001588 }
1589
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001590 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1591 XmlPullParser parser) throws XmlPullParserException, IOException {
1592 int type = parser.getEventType();
1593 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1594 String key = parser.getAttributeValue(null, ATTR_KEY);
1595 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1596 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1597 if (multiple != null) {
1598 values.clear();
1599 int count = Integer.parseInt(multiple);
1600 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1601 if (type == XmlPullParser.START_TAG
1602 && parser.getName().equals(TAG_VALUE)) {
1603 values.add(parser.nextText().trim());
1604 count--;
1605 }
1606 }
1607 String [] valueStrings = new String[values.size()];
1608 values.toArray(valueStrings);
1609 restrictions.putStringArray(key, valueStrings);
1610 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1611 restrictions.putBundle(key, readBundleEntry(parser, values));
1612 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1613 final int outerDepth = parser.getDepth();
1614 ArrayList<Bundle> bundleList = new ArrayList<>();
1615 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1616 Bundle childBundle = readBundleEntry(parser, values);
1617 bundleList.add(childBundle);
1618 }
1619 restrictions.putParcelableArray(key,
1620 bundleList.toArray(new Bundle[bundleList.size()]));
1621 } else {
1622 String value = parser.nextText().trim();
1623 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1624 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1625 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1626 restrictions.putInt(key, Integer.parseInt(value));
1627 } else {
1628 restrictions.putString(key, value);
1629 }
1630 }
1631 }
1632 }
1633
1634 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1635 throws IOException, XmlPullParserException {
1636 Bundle childBundle = new Bundle();
1637 final int outerDepth = parser.getDepth();
1638 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1639 readEntry(childBundle, values, parser);
1640 }
1641 return childBundle;
1642 }
1643
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001644 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001645 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001646 AtomicFile restrictionsFile = new AtomicFile(
1647 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001648 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001649 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1650 }
1651
1652 @VisibleForTesting
1653 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1654 AtomicFile restrictionsFile) {
1655 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001656 try {
1657 fos = restrictionsFile.startWrite();
1658 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1659
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 final XmlSerializer serializer = new FastXmlSerializer();
1661 serializer.setOutput(bos, "utf-8");
1662 serializer.startDocument(null, true);
1663 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1664
1665 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001666 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001667 serializer.endTag(null, TAG_RESTRICTIONS);
1668
1669 serializer.endDocument();
1670 restrictionsFile.finishWrite(fos);
1671 } catch (Exception e) {
1672 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001673 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1674 }
1675 }
1676
1677 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1678 throws IOException {
1679 for (String key : restrictions.keySet()) {
1680 Object value = restrictions.get(key);
1681 serializer.startTag(null, TAG_ENTRY);
1682 serializer.attribute(null, ATTR_KEY, key);
1683
1684 if (value instanceof Boolean) {
1685 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1686 serializer.text(value.toString());
1687 } else if (value instanceof Integer) {
1688 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1689 serializer.text(value.toString());
1690 } else if (value == null || value instanceof String) {
1691 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1692 serializer.text(value != null ? (String) value : "");
1693 } else if (value instanceof Bundle) {
1694 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1695 writeBundle((Bundle) value, serializer);
1696 } else if (value instanceof Parcelable[]) {
1697 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1698 Parcelable[] array = (Parcelable[]) value;
1699 for (Parcelable parcelable : array) {
1700 if (!(parcelable instanceof Bundle)) {
1701 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1702 }
1703 serializer.startTag(null, TAG_ENTRY);
1704 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1705 writeBundle((Bundle) parcelable, serializer);
1706 serializer.endTag(null, TAG_ENTRY);
1707 }
1708 } else {
1709 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1710 String[] values = (String[]) value;
1711 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1712 for (String choice : values) {
1713 serializer.startTag(null, TAG_VALUE);
1714 serializer.text(choice != null ? choice : "");
1715 serializer.endTag(null, TAG_VALUE);
1716 }
1717 }
1718 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001719 }
1720 }
1721
1722 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001723 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001724 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001725 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001726 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001727 }
1728 }
1729
1730 @Override
1731 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001732 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001733 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001734 UserInfo info = getUserInfoLocked(userId);
1735 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001736 }
1737 // Not found
1738 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001739 }
1740 }
1741
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001742 @Override
1743 public long getUserCreationTime(int userHandle) {
1744 int callingUserId = UserHandle.getCallingUserId();
1745 UserInfo userInfo = null;
1746 synchronized (mPackagesLock) {
1747 if (callingUserId == userHandle) {
1748 userInfo = getUserInfoLocked(userHandle);
1749 } else {
1750 UserInfo parent = getProfileParentLocked(userHandle);
1751 if (parent != null && parent.id == callingUserId) {
1752 userInfo = getUserInfoLocked(userHandle);
1753 }
1754 }
1755 }
1756 if (userInfo == null) {
1757 throw new SecurityException("userHandle can only be the calling user or a managed "
1758 + "profile associated with this user");
1759 }
1760 return userInfo.creationTime;
1761 }
1762
Amith Yamasani0b285492011-04-14 17:35:23 -07001763 /**
1764 * Caches the list of user ids in an array, adjusting the array size when necessary.
1765 */
Amith Yamasani13593602012-03-22 16:16:17 -07001766 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001767 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001768 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001769 if (!mUsers.valueAt(i).partial) {
1770 num++;
1771 }
1772 }
Amith Yamasani16389312012-10-17 21:20:14 -07001773 final int[] newUsers = new int[num];
1774 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001775 for (int i = 0; i < mUsers.size(); i++) {
1776 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001777 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001778 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001779 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001780 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001781 }
1782
1783 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001784 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001785 * @param userId the user that was just foregrounded
1786 */
1787 public void userForeground(int userId) {
1788 synchronized (mPackagesLock) {
1789 UserInfo user = mUsers.get(userId);
1790 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001791 if (user == null || user.partial) {
1792 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1793 return;
1794 }
1795 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001796 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001797 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001798 }
1799 }
1800 }
1801
1802 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001803 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001804 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1805 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001806 * @return
1807 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001808 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001809 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001810 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001811 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001812 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001813 break;
1814 }
1815 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001816 }
Amith Yamasani195263742012-08-21 15:40:12 -07001817 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001818 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001819 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001820
Amith Yamasanifc95e702013-09-26 13:20:17 -07001821 private String packageToRestrictionsFileName(String packageName) {
1822 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1823 }
1824
Amith Yamasani920ace02012-09-20 22:15:37 -07001825 @Override
1826 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1827 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1828 != PackageManager.PERMISSION_GRANTED) {
1829 pw.println("Permission Denial: can't dump UserManager from from pid="
1830 + Binder.getCallingPid()
1831 + ", uid=" + Binder.getCallingUid()
1832 + " without permission "
1833 + android.Manifest.permission.DUMP);
1834 return;
1835 }
1836
1837 long now = System.currentTimeMillis();
1838 StringBuilder sb = new StringBuilder();
1839 synchronized (mPackagesLock) {
1840 pw.println("Users:");
1841 for (int i = 0; i < mUsers.size(); i++) {
1842 UserInfo user = mUsers.valueAt(i);
1843 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001844 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001845 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001846 if (user.partial) pw.print(" <partial>");
1847 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001848 pw.print(" Created: ");
1849 if (user.creationTime == 0) {
1850 pw.println("<unknown>");
1851 } else {
1852 sb.setLength(0);
1853 TimeUtils.formatDuration(now - user.creationTime, sb);
1854 sb.append(" ago");
1855 pw.println(sb);
1856 }
1857 pw.print(" Last logged in: ");
1858 if (user.lastLoggedInTime == 0) {
1859 pw.println("<unknown>");
1860 } else {
1861 sb.setLength(0);
1862 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1863 sb.append(" ago");
1864 pw.println(sb);
1865 }
1866 }
1867 }
1868 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001869
1870 final class MainHandler extends Handler {
1871
1872 @Override
1873 public void handleMessage(Message msg) {
1874 switch (msg.what) {
1875 case WRITE_USER_MSG:
1876 removeMessages(WRITE_USER_MSG, msg.obj);
1877 synchronized (mPackagesLock) {
1878 int userId = ((UserInfo) msg.obj).id;
1879 UserInfo userInfo = mUsers.get(userId);
1880 if (userInfo != null) {
1881 writeUserLocked(userInfo);
1882 }
1883 }
1884 }
1885 }
1886 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001887}