blob: 40c8ca32d205f66c707d333da0cc961b111bcef7 [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;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010073import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070076import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077
Fyodor Kupolov262f9952015-03-23 18:55:11 -070078import libcore.io.IoUtils;
79
Amith Yamasani258848d2012-08-10 17:06:33 -070080public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070081
Amith Yamasani2a003292012-08-14 18:25:45 -070082 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083
Amith Yamasani16389312012-10-17 21:20:14 -070084 private static final boolean DBG = false;
85
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070090 private static final String ATTR_CREATION_TIME = "created";
91 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070095 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053098 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800101 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String TAG_ENTRY = "entry";
103 private static final String TAG_VALUE = "value";
104 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800106 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
109 private static final String ATTR_TYPE_STRING = "s";
110 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700111 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700112 private static final String ATTR_TYPE_BUNDLE = "B";
113 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114
Amith Yamasani0b285492011-04-14 17:35:23 -0700115 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700117 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100118 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800120 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700121 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800122
Amith Yamasani634cf312012-10-04 17:34:21 -0700123 private static final int MIN_USER_ID = 10;
124
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700125 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700126
Amith Yamasani920ace02012-09-20 22:15:37 -0700127 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
128
Amith Yamasani95ab7842014-08-11 17:09:26 -0700129 // Maximum number of managed profiles permitted is 1. This cannot be increased
130 // without first making sure that the rest of the framework is prepared for it.
131 private static final int MAX_MANAGED_PROFILES = 1;
132
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700133 // Set of user restrictions, which can only be enforced by the system
134 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
135 UserManager.DISALLOW_RECORD_AUDIO);
136
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800137 static final int WRITE_USER_MSG = 1;
138 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530139
Dianne Hackborn4428e172012-08-24 17:43:05 -0700140 private final Context mContext;
141 private final PackageManagerService mPm;
142 private final Object mInstallLock;
143 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800145 private final Handler mHandler;
146
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private final File mUsersDir;
148 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700149 private final File mBaseUserPath;
150
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800152 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530153 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800154
155 /**
156 * Set of user IDs being actively removed. Removed IDs linger in this set
157 * for several seconds to work around a VFS caching issue.
158 */
159 // @GuardedBy("mPackagesLock")
160 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161
Amith Yamasani0b285492011-04-14 17:35:23 -0700162 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700163 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700165
Jason Monk62062992014-05-06 09:55:28 -0400166 private IAppOpsService mAppOpsService;
167
Amith Yamasani258848d2012-08-10 17:06:33 -0700168 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700169
Dianne Hackborn4428e172012-08-24 17:43:05 -0700170 public static UserManagerService getInstance() {
171 synchronized (UserManagerService.class) {
172 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700173 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
176 /**
177 * Available for testing purposes.
178 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700179 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700181 }
182
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 /**
184 * Called by package manager to create the service. This is closely
185 * associated with the package manager, and the given lock is the
186 * package manager's own lock.
187 */
188 UserManagerService(Context context, PackageManagerService pm,
189 Object installLock, Object packagesLock) {
190 this(context, pm, installLock, packagesLock,
191 Environment.getDataDirectory(),
192 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193 }
194
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195 /**
196 * Available for testing purposes.
197 */
198 private UserManagerService(Context context, PackageManagerService pm,
199 Object installLock, Object packagesLock,
200 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700201 mContext = context;
202 mPm = pm;
203 mInstallLock = installLock;
204 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800205 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700206 synchronized (mInstallLock) {
207 synchronized (mPackagesLock) {
208 mUsersDir = new File(dataDir, USER_INFO_DIR);
209 mUsersDir.mkdirs();
210 // Make zeroth user directory, for services to migrate their files to that location
211 File userZeroDir = new File(mUsersDir, "0");
212 userZeroDir.mkdirs();
213 mBaseUserPath = baseUserPath;
214 FileUtils.setPermissions(mUsersDir.toString(),
215 FileUtils.S_IRWXU|FileUtils.S_IRWXG
216 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
217 -1, -1);
218 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800219 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700220 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700221 sInstance = this;
222 }
223 }
224 }
225
226 void systemReady() {
227 synchronized (mInstallLock) {
228 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700229 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
231 for (int i = 0; i < mUsers.size(); i++) {
232 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700233 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700234 partials.add(ui);
235 }
236 }
237 for (int i = 0; i < partials.size(); i++) {
238 UserInfo ui = partials.get(i);
239 Slog.w(LOG_TAG, "Removing partially created user #" + i
240 + " (name=" + ui.name + ")");
241 removeUserStateLocked(ui.id);
242 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700243 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 }
Amith Yamasani06bf8242015-05-08 16:36:21 -0700245 onUserForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400246 mAppOpsService = IAppOpsService.Stub.asInterface(
247 ServiceManager.getService(Context.APP_OPS_SERVICE));
248 for (int i = 0; i < mUserIds.length; ++i) {
249 try {
250 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
251 } catch (RemoteException e) {
252 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
253 }
254 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 }
256
257 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700258 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700259 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700260 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700261 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
262 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700263 UserInfo ui = mUsers.valueAt(i);
264 if (ui.partial) {
265 continue;
266 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800267 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700269 }
Amith Yamasani13593602012-03-22 16:16:17 -0700270 }
271 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700272 }
Amith Yamasani13593602012-03-22 16:16:17 -0700273 }
274
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100276 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800277 if (userId != UserHandle.getCallingUserId()) {
278 checkManageUsersPermission("getting profiles related to user " + userId);
279 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700280 final long ident = Binder.clearCallingIdentity();
281 try {
282 synchronized (mPackagesLock) {
283 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100284 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 } finally {
286 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000287 }
288 }
289
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 /** Assume permissions already checked and caller's identity cleared */
291 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700292 UserInfo user = getUserInfoLocked(userId);
293 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700294 if (user == null) {
295 // Probably a dying user
296 return users;
297 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700298 for (int i = 0; i < mUsers.size(); i++) {
299 UserInfo profile = mUsers.valueAt(i);
300 if (!isProfileOf(user, profile)) {
301 continue;
302 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100303 if (enabledOnly && !profile.isEnabled()) {
304 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700305 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700306 if (mRemovingUserIds.get(profile.id)) {
307 continue;
308 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700309 users.add(profile);
310 }
311 return users;
312 }
313
Jessica Hummelbe81c802014-04-22 15:49:22 +0100314 @Override
315 public UserInfo getProfileParent(int userHandle) {
316 checkManageUsersPermission("get the profile parent");
317 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700318 return getProfileParentLocked(userHandle);
319 }
320 }
321
322 private UserInfo getProfileParentLocked(int userHandle) {
323 UserInfo profile = getUserInfoLocked(userHandle);
324 if (profile == null) {
325 return null;
326 }
327 int parentUserId = profile.profileGroupId;
328 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
329 return null;
330 } else {
331 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100332 }
333 }
334
Kenny Guy2a764942014-04-02 13:29:20 +0100335 private boolean isProfileOf(UserInfo user, UserInfo profile) {
336 return user.id == profile.id ||
337 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
338 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000339 }
340
341 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100342 public void setUserEnabled(int userId) {
343 checkManageUsersPermission("enable user");
344 synchronized (mPackagesLock) {
345 UserInfo info = getUserInfoLocked(userId);
346 if (info != null && !info.isEnabled()) {
347 info.flags ^= UserInfo.FLAG_DISABLED;
348 writeUserLocked(info);
349 }
350 }
351 }
352
353 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700354 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700355 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700356 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700357 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700358 }
359 }
360
Amith Yamasani71e6c692013-03-24 17:39:28 -0700361 @Override
362 public boolean isRestricted() {
363 synchronized (mPackagesLock) {
364 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
365 }
366 }
367
Amith Yamasani195263742012-08-21 15:40:12 -0700368 /*
369 * Should be locked on mUsers before calling this.
370 */
371 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700373 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800374 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700375 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
376 return null;
377 }
378 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700379 }
380
Amith Yamasani13593602012-03-22 16:16:17 -0700381 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700382 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700383 return ArrayUtils.contains(mUserIds, userId);
384 }
385 }
386
Amith Yamasani258848d2012-08-10 17:06:33 -0700387 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700388 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700389 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700390 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700391 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700392 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700393 if (info == null || info.partial) {
394 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
395 return;
396 }
Amith Yamasani13593602012-03-22 16:16:17 -0700397 if (name != null && !name.equals(info.name)) {
398 info.name = name;
399 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700400 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700401 }
402 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700403 if (changed) {
404 sendUserInfoChangedBroadcast(userId);
405 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700406 }
407
Amith Yamasani258848d2012-08-10 17:06:33 -0700408 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700409 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700410 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400411 long ident = Binder.clearCallingIdentity();
412 try {
413 synchronized (mPackagesLock) {
414 UserInfo info = mUsers.get(userId);
415 if (info == null || info.partial) {
416 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
417 return;
418 }
419 writeBitmapLocked(info, bitmap);
420 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700421 }
Jason Monk9a944532014-07-08 09:31:21 -0400422 sendUserInfoChangedBroadcast(userId);
423 } finally {
424 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700425 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700426 }
427
428 private void sendUserInfoChangedBroadcast(int userId) {
429 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
430 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
431 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700432 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700433 }
434
Amith Yamasani258848d2012-08-10 17:06:33 -0700435 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100436 public ParcelFileDescriptor getUserIcon(int userId) {
437 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700438 synchronized (mPackagesLock) {
439 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 if (info == null || info.partial) {
441 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
442 return null;
443 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100444 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
445 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
446 || callingGroupId != info.profileGroupId) {
447 checkManageUsersPermission("get the icon of a user who is not related");
448 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700449 if (info.iconPath == null) {
450 return null;
451 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100452 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700453 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100454
455 try {
456 return ParcelFileDescriptor.open(
457 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
458 } catch (FileNotFoundException e) {
459 Log.e(LOG_TAG, "Couldn't find icon file", e);
460 }
461 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700462 }
463
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700464 public void makeInitialized(int userId) {
465 checkManageUsersPermission("makeInitialized");
466 synchronized (mPackagesLock) {
467 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700468 if (info == null || info.partial) {
469 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
470 }
471 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700472 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800473 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700474 }
475 }
476 }
477
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700478 /**
479 * If default guest restrictions haven't been initialized yet, add the basic
480 * restrictions.
481 */
482 private void initDefaultGuestRestrictions() {
483 if (mGuestRestrictions.isEmpty()) {
484 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800485 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700486 }
487 }
488
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800489 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530490 public Bundle getDefaultGuestRestrictions() {
491 checkManageUsersPermission("getDefaultGuestRestrictions");
492 synchronized (mPackagesLock) {
493 return new Bundle(mGuestRestrictions);
494 }
495 }
496
497 @Override
498 public void setDefaultGuestRestrictions(Bundle restrictions) {
499 checkManageUsersPermission("setDefaultGuestRestrictions");
500 synchronized (mPackagesLock) {
501 mGuestRestrictions.clear();
502 mGuestRestrictions.putAll(restrictions);
503 writeUserListLocked();
504 }
505 }
506
507 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700508 public boolean hasUserRestriction(String restrictionKey, int userId) {
509 synchronized (mPackagesLock) {
510 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700511 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700512 }
513 }
514
515 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800516 public Bundle getUserRestrictions(int userId) {
517 // checkManageUsersPermission("getUserRestrictions");
518
519 synchronized (mPackagesLock) {
520 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700521 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800522 }
523 }
524
525 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700526 public void setUserRestriction(String key, boolean value, int userId) {
527 synchronized (mPackagesLock) {
528 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
529 Bundle restrictions = getUserRestrictions(userId);
530 restrictions.putBoolean(key, value);
531 setUserRestrictionsInternalLocked(restrictions, userId);
532 }
533 }
534 }
535
536 @Override
537 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
538 checkSystemOrRoot("setSystemControlledUserRestriction");
539 synchronized (mPackagesLock) {
540 Bundle restrictions = getUserRestrictions(userId);
541 restrictions.putBoolean(key, value);
542 setUserRestrictionsInternalLocked(restrictions, userId);
543 }
544 }
545
546 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800547 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700548 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700549 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800550
551 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700552 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
553 // Restore the original state of system controlled restrictions from oldUserRestrictions
554 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
555 restrictions.remove(key);
556 if (oldUserRestrictions.containsKey(key)) {
557 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
558 }
Jason Monk62062992014-05-06 09:55:28 -0400559 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700560 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800561 }
562 }
563
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700564 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
565 final Bundle userRestrictions = mUserRestrictions.get(userId);
566 userRestrictions.clear();
567 userRestrictions.putAll(restrictions);
568 long token = Binder.clearCallingIdentity();
569 try {
570 mAppOpsService.setUserRestrictions(userRestrictions, userId);
571 } catch (RemoteException e) {
572 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
573 } finally {
574 Binder.restoreCallingIdentity(token);
575 }
576 scheduleWriteUserLocked(mUsers.get(userId));
577 }
578
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700580 * Check if we've hit the limit of how many users can be created.
581 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700582 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700583 int aliveUserCount = 0;
584 final int totalUserCount = mUsers.size();
585 // Skip over users being removed
586 for (int i = 0; i < totalUserCount; i++) {
587 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700588 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700589 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700590 aliveUserCount++;
591 }
592 }
593 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700594 }
595
596 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700597 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700598 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700599 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700600 *
601 * @param message used as message if SecurityException is thrown
602 * @throws SecurityException if the caller is not system or root
603 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700604 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700605 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700606 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400607 && ActivityManager.checkComponentPermission(
608 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700609 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
610 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
611 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400612 }
613
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700614 private static void checkSystemOrRoot(String message) {
615 final int uid = Binder.getCallingUid();
616 if (uid != Process.SYSTEM_UID && uid != 0) {
617 throw new SecurityException("Only system may call: " + message);
618 }
619 }
620
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700621 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700622 try {
623 File dir = new File(mUsersDir, Integer.toString(info.id));
624 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100625 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700626 if (!dir.exists()) {
627 dir.mkdir();
628 FileUtils.setPermissions(
629 dir.getPath(),
630 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
631 -1, -1);
632 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700633 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100634 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
635 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700636 info.iconPath = file.getAbsolutePath();
637 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700638 try {
639 os.close();
640 } catch (IOException ioe) {
641 // What the ... !
642 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100643 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700644 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700645 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700646 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700647 }
648
Amith Yamasani0b285492011-04-14 17:35:23 -0700649 /**
650 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
651 * cache it elsewhere.
652 * @return the array of user ids.
653 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700654 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700655 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700656 return mUserIds;
657 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700658 }
659
Dianne Hackborn4428e172012-08-24 17:43:05 -0700660 int[] getUserIdsLPr() {
661 return mUserIds;
662 }
663
Amith Yamasani13593602012-03-22 16:16:17 -0700664 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700666 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700667 return;
668 }
669 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700670 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700671 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700672 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700673 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100674 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700675 int type;
676 while ((type = parser.next()) != XmlPullParser.START_TAG
677 && type != XmlPullParser.END_DOCUMENT) {
678 ;
679 }
680
681 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700682 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700683 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700684 return;
685 }
686
Amith Yamasani2a003292012-08-14 18:25:45 -0700687 mNextSerialNumber = -1;
688 if (parser.getName().equals(TAG_USERS)) {
689 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
690 if (lastSerialNumber != null) {
691 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
692 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700693 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
694 if (versionNumber != null) {
695 mUserVersion = Integer.parseInt(versionNumber);
696 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700697 }
698
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700699 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530700 if (type == XmlPullParser.START_TAG) {
701 final String name = parser.getName();
702 if (name.equals(TAG_USER)) {
703 String id = parser.getAttributeValue(null, ATTR_ID);
704 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700705
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530706 if (user != null) {
707 mUsers.put(user.id, user);
708 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
709 mNextSerialNumber = user.id + 1;
710 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700711 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530712 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800713 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
714 && type != XmlPullParser.END_TAG) {
715 if (type == XmlPullParser.START_TAG) {
716 if (parser.getName().equals(TAG_RESTRICTIONS)) {
717 readRestrictionsLocked(parser, mGuestRestrictions);
718 }
719 break;
720 }
721 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700722 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700723 }
724 }
Amith Yamasani13593602012-03-22 16:16:17 -0700725 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700726 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700727 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700728 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700729 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700730 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800731 } finally {
732 if (fis != null) {
733 try {
734 fis.close();
735 } catch (IOException e) {
736 }
737 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 }
739 }
740
Amith Yamasani6f34b412012-10-22 18:19:27 -0700741 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800742 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700743 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700744 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700745 int userVersion = mUserVersion;
746 if (userVersion < 1) {
747 // Assign a proper name for the owner, if not initialized correctly before
748 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
749 if ("Primary".equals(user.name)) {
750 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800751 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700752 }
753 userVersion = 1;
754 }
755
Amith Yamasanibc9625052012-11-15 14:39:18 -0800756 if (userVersion < 2) {
757 // Owner should be marked as initialized
758 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
759 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
760 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800761 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800762 }
763 userVersion = 2;
764 }
765
Amith Yamasani350962c2013-08-06 11:18:53 -0700766
Amith Yamasani5e486f52013-08-07 11:06:44 -0700767 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700768 userVersion = 4;
769 }
770
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700771 if (userVersion < 5) {
772 initDefaultGuestRestrictions();
773 userVersion = 5;
774 }
775
Amith Yamasani6f34b412012-10-22 18:19:27 -0700776 if (userVersion < USER_VERSION) {
777 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
778 + USER_VERSION);
779 } else {
780 mUserVersion = userVersion;
781 writeUserListLocked();
782 }
783 }
784
Amith Yamasani13593602012-03-22 16:16:17 -0700785 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800787 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700788 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700789 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700791 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400792 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800793
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500794 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800795 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
796
Amith Yamasani13593602012-03-22 16:16:17 -0700797 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700798 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700799
Amith Yamasani13593602012-03-22 16:16:17 -0700800 writeUserListLocked();
801 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 }
803
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800804 private void scheduleWriteUserLocked(UserInfo userInfo) {
805 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
806 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
807 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
808 }
809 }
810
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811 /*
812 * Writes the user file in this format:
813 *
814 * <user flags="20039023" id="0">
815 * <name>Primary</name>
816 * </user>
817 */
Amith Yamasani13593602012-03-22 16:16:17 -0700818 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700819 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700820 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700821 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700822 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700823 final BufferedOutputStream bos = new BufferedOutputStream(fos);
824
825 // XmlSerializer serializer = XmlUtils.serializerInstance();
826 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100827 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700828 serializer.startDocument(null, true);
829 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
830
831 serializer.startTag(null, TAG_USER);
832 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700833 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700834 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700835 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
836 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
837 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700838 if (userInfo.iconPath != null) {
839 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
840 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700841 if (userInfo.partial) {
842 serializer.attribute(null, ATTR_PARTIAL, "true");
843 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700844 if (userInfo.guestToRemove) {
845 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
846 }
Kenny Guy2a764942014-04-02 13:29:20 +0100847 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
848 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
849 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000850 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700851
852 serializer.startTag(null, TAG_NAME);
853 serializer.text(userInfo.name);
854 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800855 Bundle restrictions = mUserRestrictions.get(userInfo.id);
856 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530857 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800858 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700859 serializer.endTag(null, TAG_USER);
860
861 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700862 userFile.finishWrite(fos);
863 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700864 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700865 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700866 }
867 }
868
869 /*
870 * Writes the user list file in this format:
871 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700872 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873 * <user id="0"></user>
874 * <user id="2"></user>
875 * </users>
876 */
Amith Yamasani13593602012-03-22 16:16:17 -0700877 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700878 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700879 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700880 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700881 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700882 final BufferedOutputStream bos = new BufferedOutputStream(fos);
883
884 // XmlSerializer serializer = XmlUtils.serializerInstance();
885 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100886 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700887 serializer.startDocument(null, true);
888 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
889
890 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700891 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700892 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700893
Adam Lesinskieddeb492014-09-08 17:50:03 -0700894 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530895 writeRestrictionsLocked(serializer, mGuestRestrictions);
896 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700897 for (int i = 0; i < mUsers.size(); i++) {
898 UserInfo user = mUsers.valueAt(i);
899 serializer.startTag(null, TAG_USER);
900 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
901 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 }
903
904 serializer.endTag(null, TAG_USERS);
905
906 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700907 userListFile.finishWrite(fos);
908 } catch (Exception e) {
909 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700910 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 }
912 }
913
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530914 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
915 throws IOException {
916 serializer.startTag(null, TAG_RESTRICTIONS);
917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
922 writeBoolean(serializer, restrictions,
923 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
929 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
930 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
931 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
932 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
933 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
934 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
935 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
936 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
937 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
938 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
939 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700940 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
941 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400942 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700943 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
944 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000945 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000946 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530947 serializer.endTag(null, TAG_RESTRICTIONS);
948 }
949
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800950 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700951 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700953 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700954 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700955 long creationTime = 0L;
956 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +0100957 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700958 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700959 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800960 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700961
962 FileInputStream fis = null;
963 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700964 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700965 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700966 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100968 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700969 int type;
970 while ((type = parser.next()) != XmlPullParser.START_TAG
971 && type != XmlPullParser.END_DOCUMENT) {
972 ;
973 }
974
975 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700976 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 return null;
978 }
979
980 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700981 int storedId = readIntAttribute(parser, ATTR_ID, -1);
982 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700983 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984 return null;
985 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700986 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
987 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700988 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700989 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
990 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +0100991 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
992 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700993 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
994 if ("true".equals(valueString)) {
995 partial = true;
996 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700997 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
998 if ("true".equals(valueString)) {
999 guestToRemove = true;
1000 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001001
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001002 int outerDepth = parser.getDepth();
1003 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1004 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1005 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1006 continue;
1007 }
1008 String tag = parser.getName();
1009 if (TAG_NAME.equals(tag)) {
1010 type = parser.next();
1011 if (type == XmlPullParser.TEXT) {
1012 name = parser.getText();
1013 }
1014 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301015 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001016 }
1017 }
1018 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001019
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001020 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001021 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001022 userInfo.creationTime = creationTime;
1023 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001024 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001025 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001026 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001027 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001028 return userInfo;
1029
1030 } catch (IOException ioe) {
1031 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001032 } finally {
1033 if (fis != null) {
1034 try {
1035 fis.close();
1036 } catch (IOException e) {
1037 }
1038 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 }
1040 return null;
1041 }
1042
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301043 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1044 throws IOException {
1045 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1047 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1048 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1049 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1050 readBoolean(parser, restrictions,
1051 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1059 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1060 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1061 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1065 readBoolean(parser, restrictions,
1066 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1068 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001069 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1070 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001071 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001072 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1073 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001074 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001075 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301076 }
1077
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001078 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1079 String restrictionKey) {
1080 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001081 if (value != null) {
1082 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1083 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001084 }
1085
1086 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1087 throws IOException {
1088 if (restrictions.containsKey(restrictionKey)) {
1089 xml.attribute(null, restrictionKey,
1090 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1091 }
1092 }
1093
Amith Yamasani920ace02012-09-20 22:15:37 -07001094 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1095 String valueString = parser.getAttributeValue(null, attr);
1096 if (valueString == null) return defaultValue;
1097 try {
1098 return Integer.parseInt(valueString);
1099 } catch (NumberFormatException nfe) {
1100 return defaultValue;
1101 }
1102 }
1103
1104 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1105 String valueString = parser.getAttributeValue(null, attr);
1106 if (valueString == null) return defaultValue;
1107 try {
1108 return Long.parseLong(valueString);
1109 } catch (NumberFormatException nfe) {
1110 return defaultValue;
1111 }
1112 }
1113
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001114 private boolean isPackageInstalled(String pkg, int userId) {
1115 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1116 PackageManager.GET_UNINSTALLED_PACKAGES,
1117 userId);
1118 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1119 return false;
1120 }
1121 return true;
1122 }
1123
Amith Yamasanib82add22013-07-09 11:24:44 -07001124 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001125 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001126 * Does not do any permissions checking.
1127 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001128 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001129 synchronized (mPackagesLock) {
1130 File dir = Environment.getUserSystemDirectory(userId);
1131 String[] files = dir.list();
1132 if (files == null) return;
1133 for (String fileName : files) {
1134 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1135 File resFile = new File(dir, fileName);
1136 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001137 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001138 }
1139 }
1140 }
1141 }
1142 }
1143
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001144 /**
1145 * Removes the app restrictions file for a specific package and user id, if it exists.
1146 */
1147 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1148 synchronized (mPackagesLock) {
1149 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001150 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001151 if (resFile.exists()) {
1152 resFile.delete();
1153 }
1154 }
1155 }
1156
Kenny Guya52dc3e2014-02-11 15:33:14 +00001157 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001158 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001159 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001160 if (userId != UserHandle.USER_OWNER) {
1161 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001162 return null;
1163 }
Kenny Guy2a764942014-04-02 13:29:20 +01001164 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001165 }
1166
Amith Yamasani258848d2012-08-10 17:06:33 -07001167 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001168 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001169 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001170 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001171 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001172
Jessica Hummelbe81c802014-04-22 15:49:22 +01001173 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001174 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1175 UserManager.DISALLOW_ADD_USER, false)) {
1176 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1177 return null;
1178 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001179 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001180 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001181 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001182 try {
1183 synchronized (mInstallLock) {
1184 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001185 UserInfo parent = null;
1186 if (parentId != UserHandle.USER_NULL) {
1187 parent = getUserInfoLocked(parentId);
1188 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001189 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001190 // If we're not adding a guest user and the limit has been reached,
1191 // cannot add a user.
1192 if (!isGuest && isUserLimitReachedLocked()) {
1193 return null;
1194 }
1195 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001196 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001197 return null;
1198 }
1199 // Limit number of managed profiles that can be created
1200 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1201 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1202 >= MAX_MANAGED_PROFILES) {
1203 return null;
1204 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001205 int userId = getNextAvailableIdLocked();
1206 userInfo = new UserInfo(userId, name, null, flags);
1207 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1208 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001209 long now = System.currentTimeMillis();
1210 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001211 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001212 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001213 mUsers.put(userId, userInfo);
1214 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001215 if (parent != null) {
1216 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1217 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001218 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001219 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001220 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001221 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001222 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001223 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001224 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001225 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001226 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001227 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001228 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001229 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001230 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001231 if (userInfo != null) {
1232 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1233 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1234 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1235 android.Manifest.permission.MANAGE_USERS);
1236 }
1237 } finally {
1238 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001239 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001240 return userInfo;
1241 }
1242
Amith Yamasani95ab7842014-08-11 17:09:26 -07001243 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1244 int count = 0;
1245 for (int i = mUsers.size() - 1; i >= 0; i--) {
1246 UserInfo user = mUsers.valueAt(i);
1247 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1248 if ((user.flags & flags) != 0) {
1249 count++;
1250 }
1251 }
1252 }
1253 return count;
1254 }
1255
Amith Yamasani0b285492011-04-14 17:35:23 -07001256 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001257 * Find the current guest user. If the Guest user is partial,
1258 * then do not include it in the results as it is about to die.
1259 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1260 * the special handling of Guests being removed.
1261 */
1262 private UserInfo findCurrentGuestUserLocked() {
1263 final int size = mUsers.size();
1264 for (int i = 0; i < size; i++) {
1265 final UserInfo user = mUsers.valueAt(i);
1266 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1267 return user;
1268 }
1269 }
1270 return null;
1271 }
1272
1273 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001274 * Mark this guest user for deletion to allow us to create another guest
1275 * and switch to that user before actually removing this guest.
1276 * @param userHandle the userid of the current guest
1277 * @return whether the user could be marked for deletion
1278 */
1279 public boolean markGuestForDeletion(int userHandle) {
1280 checkManageUsersPermission("Only the system can remove users");
1281 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1282 UserManager.DISALLOW_REMOVE_USER, false)) {
1283 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1284 return false;
1285 }
1286
1287 long ident = Binder.clearCallingIdentity();
1288 try {
1289 final UserInfo user;
1290 synchronized (mPackagesLock) {
1291 user = mUsers.get(userHandle);
1292 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1293 return false;
1294 }
1295 if (!user.isGuest()) {
1296 return false;
1297 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001298 // We set this to a guest user that is to be removed. This is a temporary state
1299 // where we are allowed to add new Guest users, even if this one is still not
1300 // removed. This user will still show up in getUserInfo() calls.
1301 // If we don't get around to removing this Guest user, it will be purged on next
1302 // startup.
1303 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001304 // Mark it as disabled, so that it isn't returned any more when
1305 // profiles are queried.
1306 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001307 writeUserLocked(user);
1308 }
1309 } finally {
1310 Binder.restoreCallingIdentity(ident);
1311 }
1312 return true;
1313 }
1314
1315 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001316 * Removes a user and all data directories created for that user. This method should be called
1317 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001318 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001319 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001320 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001321 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001322 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1323 UserManager.DISALLOW_REMOVE_USER, false)) {
1324 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1325 return false;
1326 }
1327
Kenny Guyee58b4f2014-05-23 15:19:53 +01001328 long ident = Binder.clearCallingIdentity();
1329 try {
1330 final UserInfo user;
1331 synchronized (mPackagesLock) {
1332 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001333 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001334 return false;
1335 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001336
1337 // We remember deleted user IDs to prevent them from being
1338 // reused during the current boot; they can still be reused
1339 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001340 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001341
Kenny Guyee58b4f2014-05-23 15:19:53 +01001342 try {
1343 mAppOpsService.removeUser(userHandle);
1344 } catch (RemoteException e) {
1345 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1346 }
1347 // Set this to a partially created user, so that the user will be purged
1348 // on next startup, in case the runtime stops now before stopping and
1349 // removing the user completely.
1350 user.partial = true;
1351 // Mark it as disabled, so that it isn't returned any more when
1352 // profiles are queried.
1353 user.flags |= UserInfo.FLAG_DISABLED;
1354 writeUserLocked(user);
1355 }
1356
1357 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1358 && user.isManagedProfile()) {
1359 // Send broadcast to notify system that the user removed was a
1360 // managed user.
1361 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1362 }
1363
1364 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1365 int res;
1366 try {
1367 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1368 new IStopUserCallback.Stub() {
1369 @Override
1370 public void userStopped(int userId) {
1371 finishRemoveUser(userId);
1372 }
1373 @Override
1374 public void userStopAborted(int userId) {
1375 }
1376 });
1377 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001378 return false;
1379 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001380 return res == ActivityManager.USER_OP_SUCCESS;
1381 } finally {
1382 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001383 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001384 }
1385
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001386 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001387 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001388 // Let other services shutdown any activity and clean up their state before completely
1389 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001390 long ident = Binder.clearCallingIdentity();
1391 try {
1392 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1393 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001394 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1395 android.Manifest.permission.MANAGE_USERS,
1396
1397 new BroadcastReceiver() {
1398 @Override
1399 public void onReceive(Context context, Intent intent) {
1400 if (DBG) {
1401 Slog.i(LOG_TAG,
1402 "USER_REMOVED broadcast sent, cleaning up user data "
1403 + userHandle);
1404 }
1405 new Thread() {
1406 public void run() {
1407 synchronized (mInstallLock) {
1408 synchronized (mPackagesLock) {
1409 removeUserStateLocked(userHandle);
1410 }
1411 }
1412 }
1413 }.start();
1414 }
1415 },
1416
1417 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001418 } finally {
1419 Binder.restoreCallingIdentity(ident);
1420 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001421 }
1422
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001423 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001424 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001425 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001426
1427 // Remove this user from the list
1428 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001429 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001430 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001431 userFile.delete();
1432 // Update the user list
1433 writeUserListLocked();
1434 updateUserIdsLocked();
1435 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1436 }
1437
Amith Yamasani61f57372012-08-31 12:12:28 -07001438 private void removeDirectoryRecursive(File parent) {
1439 if (parent.isDirectory()) {
1440 String[] files = parent.list();
1441 for (String filename : files) {
1442 File child = new File(parent, filename);
1443 removeDirectoryRecursive(child);
1444 }
1445 }
1446 parent.delete();
1447 }
1448
Kenny Guyf8d3a232014-05-15 16:09:52 +01001449 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001450 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001451 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1452 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001453 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1454 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001455 }
1456
Amith Yamasani2a003292012-08-14 18:25:45 -07001457 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001458 public Bundle getApplicationRestrictions(String packageName) {
1459 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1460 }
1461
1462 @Override
1463 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001464 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001465 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001466 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001467 }
1468 synchronized (mPackagesLock) {
1469 // Read the restrictions from XML
1470 return readApplicationRestrictionsLocked(packageName, userId);
1471 }
1472 }
1473
1474 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001475 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001476 int userId) {
1477 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001478 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001479 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001480 }
1481 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001482 if (restrictions == null || restrictions.isEmpty()) {
1483 cleanAppRestrictionsForPackage(packageName, userId);
1484 } else {
1485 // Write the restrictions to XML
1486 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1487 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001488 }
Robin Lee66e5d962014-04-09 16:44:21 +01001489
Kenny Guyd21b2182014-07-17 16:38:55 +01001490 if (isPackageInstalled(packageName, userId)) {
1491 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1492 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1493 changeIntent.setPackage(packageName);
1494 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1495 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1496 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001497 }
1498
Amith Yamasani655d0e22013-06-12 14:19:10 -07001499 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001500 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001501 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001502 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001503 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001504 }
1505
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001506 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001507 synchronized (mPackagesLock) {
1508 // Remove all user restrictions
1509 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001510 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001511 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001512 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001513 if (unhideApps) {
1514 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001515 }
1516 }
1517
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001518 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001519 mHandler.post(new Runnable() {
1520 @Override
1521 public void run() {
1522 List<ApplicationInfo> apps =
1523 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1524 userHandle).getList();
1525 final long ident = Binder.clearCallingIdentity();
1526 try {
1527 for (ApplicationInfo appInfo : apps) {
1528 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001529 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1530 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001531 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001532 userHandle);
1533 }
1534 }
1535 } finally {
1536 Binder.restoreCallingIdentity(ident);
1537 }
1538 }
1539 });
1540 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001541 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001542 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001543 try {
1544 return mContext.getPackageManager().getApplicationInfo(packageName,
1545 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1546 } catch (NameNotFoundException nnfe) {
1547 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001548 } finally {
1549 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001550 }
1551 }
1552
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001553 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001554 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001555 AtomicFile restrictionsFile =
1556 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1557 packageToRestrictionsFileName(packageName)));
1558 return readApplicationRestrictionsLocked(restrictionsFile);
1559 }
1560
1561 @VisibleForTesting
1562 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001563 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001564 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001565 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001566 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001567 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568
1569 FileInputStream fis = null;
1570 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001571 fis = restrictionsFile.openRead();
1572 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001573 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001574 XmlUtils.nextElement(parser);
1575 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001576 Slog.e(LOG_TAG, "Unable to read restrictions file "
1577 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001578 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001579 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001580 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1581 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001583 } catch (IOException|XmlPullParserException e) {
1584 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001585 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001586 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001587 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001588 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001589 }
1590
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001591 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1592 XmlPullParser parser) throws XmlPullParserException, IOException {
1593 int type = parser.getEventType();
1594 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1595 String key = parser.getAttributeValue(null, ATTR_KEY);
1596 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1597 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1598 if (multiple != null) {
1599 values.clear();
1600 int count = Integer.parseInt(multiple);
1601 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1602 if (type == XmlPullParser.START_TAG
1603 && parser.getName().equals(TAG_VALUE)) {
1604 values.add(parser.nextText().trim());
1605 count--;
1606 }
1607 }
1608 String [] valueStrings = new String[values.size()];
1609 values.toArray(valueStrings);
1610 restrictions.putStringArray(key, valueStrings);
1611 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1612 restrictions.putBundle(key, readBundleEntry(parser, values));
1613 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1614 final int outerDepth = parser.getDepth();
1615 ArrayList<Bundle> bundleList = new ArrayList<>();
1616 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1617 Bundle childBundle = readBundleEntry(parser, values);
1618 bundleList.add(childBundle);
1619 }
1620 restrictions.putParcelableArray(key,
1621 bundleList.toArray(new Bundle[bundleList.size()]));
1622 } else {
1623 String value = parser.nextText().trim();
1624 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1625 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1626 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1627 restrictions.putInt(key, Integer.parseInt(value));
1628 } else {
1629 restrictions.putString(key, value);
1630 }
1631 }
1632 }
1633 }
1634
1635 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1636 throws IOException, XmlPullParserException {
1637 Bundle childBundle = new Bundle();
1638 final int outerDepth = parser.getDepth();
1639 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1640 readEntry(childBundle, values, parser);
1641 }
1642 return childBundle;
1643 }
1644
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001645 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001646 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 AtomicFile restrictionsFile = new AtomicFile(
1648 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001649 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001650 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1651 }
1652
1653 @VisibleForTesting
1654 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1655 AtomicFile restrictionsFile) {
1656 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001657 try {
1658 fos = restrictionsFile.startWrite();
1659 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1660
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001662 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 serializer.startDocument(null, true);
1664 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1665
1666 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001667 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 serializer.endTag(null, TAG_RESTRICTIONS);
1669
1670 serializer.endDocument();
1671 restrictionsFile.finishWrite(fos);
1672 } catch (Exception e) {
1673 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001674 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1675 }
1676 }
1677
1678 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1679 throws IOException {
1680 for (String key : restrictions.keySet()) {
1681 Object value = restrictions.get(key);
1682 serializer.startTag(null, TAG_ENTRY);
1683 serializer.attribute(null, ATTR_KEY, key);
1684
1685 if (value instanceof Boolean) {
1686 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1687 serializer.text(value.toString());
1688 } else if (value instanceof Integer) {
1689 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1690 serializer.text(value.toString());
1691 } else if (value == null || value instanceof String) {
1692 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1693 serializer.text(value != null ? (String) value : "");
1694 } else if (value instanceof Bundle) {
1695 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1696 writeBundle((Bundle) value, serializer);
1697 } else if (value instanceof Parcelable[]) {
1698 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1699 Parcelable[] array = (Parcelable[]) value;
1700 for (Parcelable parcelable : array) {
1701 if (!(parcelable instanceof Bundle)) {
1702 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1703 }
1704 serializer.startTag(null, TAG_ENTRY);
1705 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1706 writeBundle((Bundle) parcelable, serializer);
1707 serializer.endTag(null, TAG_ENTRY);
1708 }
1709 } else {
1710 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1711 String[] values = (String[]) value;
1712 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1713 for (String choice : values) {
1714 serializer.startTag(null, TAG_VALUE);
1715 serializer.text(choice != null ? choice : "");
1716 serializer.endTag(null, TAG_VALUE);
1717 }
1718 }
1719 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001720 }
1721 }
1722
1723 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001724 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001725 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001726 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001727 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001728 }
1729 }
1730
1731 @Override
1732 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001733 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001734 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001735 UserInfo info = getUserInfoLocked(userId);
1736 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001737 }
1738 // Not found
1739 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001740 }
1741 }
1742
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001743 @Override
1744 public long getUserCreationTime(int userHandle) {
1745 int callingUserId = UserHandle.getCallingUserId();
1746 UserInfo userInfo = null;
1747 synchronized (mPackagesLock) {
1748 if (callingUserId == userHandle) {
1749 userInfo = getUserInfoLocked(userHandle);
1750 } else {
1751 UserInfo parent = getProfileParentLocked(userHandle);
1752 if (parent != null && parent.id == callingUserId) {
1753 userInfo = getUserInfoLocked(userHandle);
1754 }
1755 }
1756 }
1757 if (userInfo == null) {
1758 throw new SecurityException("userHandle can only be the calling user or a managed "
1759 + "profile associated with this user");
1760 }
1761 return userInfo.creationTime;
1762 }
1763
Amith Yamasani0b285492011-04-14 17:35:23 -07001764 /**
1765 * Caches the list of user ids in an array, adjusting the array size when necessary.
1766 */
Amith Yamasani13593602012-03-22 16:16:17 -07001767 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001768 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001769 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001770 if (!mUsers.valueAt(i).partial) {
1771 num++;
1772 }
1773 }
Amith Yamasani16389312012-10-17 21:20:14 -07001774 final int[] newUsers = new int[num];
1775 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001776 for (int i = 0; i < mUsers.size(); i++) {
1777 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001778 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001779 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001780 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001781 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001782 }
1783
1784 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001785 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001786 * @param userId the user that was just foregrounded
1787 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001788 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001789 synchronized (mPackagesLock) {
1790 UserInfo user = mUsers.get(userId);
1791 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001792 if (user == null || user.partial) {
1793 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1794 return;
1795 }
1796 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001797 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001798 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001799 }
1800 }
1801 }
1802
1803 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001804 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001805 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1806 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001807 * @return
1808 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001809 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001810 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001811 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001812 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001813 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001814 break;
1815 }
1816 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001817 }
Amith Yamasani195263742012-08-21 15:40:12 -07001818 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001819 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001820 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001821
Amith Yamasanifc95e702013-09-26 13:20:17 -07001822 private String packageToRestrictionsFileName(String packageName) {
1823 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1824 }
1825
Amith Yamasani920ace02012-09-20 22:15:37 -07001826 @Override
1827 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1828 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1829 != PackageManager.PERMISSION_GRANTED) {
1830 pw.println("Permission Denial: can't dump UserManager from from pid="
1831 + Binder.getCallingPid()
1832 + ", uid=" + Binder.getCallingUid()
1833 + " without permission "
1834 + android.Manifest.permission.DUMP);
1835 return;
1836 }
1837
1838 long now = System.currentTimeMillis();
1839 StringBuilder sb = new StringBuilder();
1840 synchronized (mPackagesLock) {
1841 pw.println("Users:");
1842 for (int i = 0; i < mUsers.size(); i++) {
1843 UserInfo user = mUsers.valueAt(i);
1844 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001845 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001846 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001847 if (user.partial) pw.print(" <partial>");
1848 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001849 pw.print(" Created: ");
1850 if (user.creationTime == 0) {
1851 pw.println("<unknown>");
1852 } else {
1853 sb.setLength(0);
1854 TimeUtils.formatDuration(now - user.creationTime, sb);
1855 sb.append(" ago");
1856 pw.println(sb);
1857 }
1858 pw.print(" Last logged in: ");
1859 if (user.lastLoggedInTime == 0) {
1860 pw.println("<unknown>");
1861 } else {
1862 sb.setLength(0);
1863 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1864 sb.append(" ago");
1865 pw.println(sb);
1866 }
1867 }
1868 }
1869 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001870
1871 final class MainHandler extends Handler {
1872
1873 @Override
1874 public void handleMessage(Message msg) {
1875 switch (msg.what) {
1876 case WRITE_USER_MSG:
1877 removeMessages(WRITE_USER_MSG, msg.obj);
1878 synchronized (mPackagesLock) {
1879 int userId = ((UserInfo) msg.obj).id;
1880 UserInfo userInfo = mUsers.get(userId);
1881 if (userInfo != null) {
1882 writeUserLocked(userInfo);
1883 }
1884 }
1885 }
1886 }
1887 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001888}