blob: 51b26a8f3e4e855d16d4cdcb305ce93f3efcb057 [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 Kupolov262f9952015-03-23 18:55:11 -070053import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.util.ArrayList;
72import java.util.List;
73
Fyodor Kupolov262f9952015-03-23 18:55:11 -070074import libcore.io.IoUtils;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070088 private static final String ATTR_SERIAL_NO = "serialNumber";
89 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070090 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070091 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070092 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010093 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053094 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080097 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080098 private static final String TAG_ENTRY = "entry";
99 private static final String TAG_VALUE = "value";
100 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700101 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
105 private static final String ATTR_TYPE_STRING = "s";
106 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700107 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700108 private static final String ATTR_TYPE_BUNDLE = "B";
109 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100114 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700121 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani95ab7842014-08-11 17:09:26 -0700125 // Maximum number of managed profiles permitted is 1. This cannot be increased
126 // without first making sure that the rest of the framework is prepared for it.
127 private static final int MAX_MANAGED_PROFILES = 1;
128
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800129 static final int WRITE_USER_MSG = 1;
130 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530131
Dianne Hackborn4428e172012-08-24 17:43:05 -0700132 private final Context mContext;
133 private final PackageManagerService mPm;
134 private final Object mInstallLock;
135 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800137 private final Handler mHandler;
138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private final File mUsersDir;
140 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700141 private final File mBaseUserPath;
142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800144 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800146
147 /**
148 * Set of user IDs being actively removed. Removed IDs linger in this set
149 * for several seconds to work around a VFS caching issue.
150 */
151 // @GuardedBy("mPackagesLock")
152 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700153
Amith Yamasani0b285492011-04-14 17:35:23 -0700154 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700155 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700156 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700157
Jason Monk62062992014-05-06 09:55:28 -0400158 private IAppOpsService mAppOpsService;
159
Amith Yamasani258848d2012-08-10 17:06:33 -0700160 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700161
Dianne Hackborn4428e172012-08-24 17:43:05 -0700162 public static UserManagerService getInstance() {
163 synchronized (UserManagerService.class) {
164 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700165 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700166 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167
168 /**
169 * Available for testing purposes.
170 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173 }
174
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175 /**
176 * Called by package manager to create the service. This is closely
177 * associated with the package manager, and the given lock is the
178 * package manager's own lock.
179 */
180 UserManagerService(Context context, PackageManagerService pm,
181 Object installLock, Object packagesLock) {
182 this(context, pm, installLock, packagesLock,
183 Environment.getDataDirectory(),
184 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 }
186
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 /**
188 * Available for testing purposes.
189 */
190 private UserManagerService(Context context, PackageManagerService pm,
191 Object installLock, Object packagesLock,
192 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700193 mContext = context;
194 mPm = pm;
195 mInstallLock = installLock;
196 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800197 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700198 synchronized (mInstallLock) {
199 synchronized (mPackagesLock) {
200 mUsersDir = new File(dataDir, USER_INFO_DIR);
201 mUsersDir.mkdirs();
202 // Make zeroth user directory, for services to migrate their files to that location
203 File userZeroDir = new File(mUsersDir, "0");
204 userZeroDir.mkdirs();
205 mBaseUserPath = baseUserPath;
206 FileUtils.setPermissions(mUsersDir.toString(),
207 FileUtils.S_IRWXU|FileUtils.S_IRWXG
208 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
209 -1, -1);
210 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800211 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700212 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700213 sInstance = this;
214 }
215 }
216 }
217
218 void systemReady() {
219 synchronized (mInstallLock) {
220 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700221 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
223 for (int i = 0; i < mUsers.size(); i++) {
224 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700225 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700226 partials.add(ui);
227 }
228 }
229 for (int i = 0; i < partials.size(); i++) {
230 UserInfo ui = partials.get(i);
231 Slog.w(LOG_TAG, "Removing partially created user #" + i
232 + " (name=" + ui.name + ")");
233 removeUserStateLocked(ui.id);
234 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700235 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700236 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700237 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400238 mAppOpsService = IAppOpsService.Stub.asInterface(
239 ServiceManager.getService(Context.APP_OPS_SERVICE));
240 for (int i = 0; i < mUserIds.length; ++i) {
241 try {
242 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
243 } catch (RemoteException e) {
244 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
245 }
246 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700247 }
248
249 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700250 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700251 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700252 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700253 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
254 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 UserInfo ui = mUsers.valueAt(i);
256 if (ui.partial) {
257 continue;
258 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800259 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700260 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700261 }
Amith Yamasani13593602012-03-22 16:16:17 -0700262 }
263 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700264 }
Amith Yamasani13593602012-03-22 16:16:17 -0700265 }
266
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100268 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800269 if (userId != UserHandle.getCallingUserId()) {
270 checkManageUsersPermission("getting profiles related to user " + userId);
271 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700272 final long ident = Binder.clearCallingIdentity();
273 try {
274 synchronized (mPackagesLock) {
275 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100276 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700277 } finally {
278 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000279 }
280 }
281
Amith Yamasanibe465322014-04-24 13:45:17 -0700282 /** Assume permissions already checked and caller's identity cleared */
283 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700284 UserInfo user = getUserInfoLocked(userId);
285 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700286 if (user == null) {
287 // Probably a dying user
288 return users;
289 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 for (int i = 0; i < mUsers.size(); i++) {
291 UserInfo profile = mUsers.valueAt(i);
292 if (!isProfileOf(user, profile)) {
293 continue;
294 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100295 if (enabledOnly && !profile.isEnabled()) {
296 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700297 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700298 if (mRemovingUserIds.get(profile.id)) {
299 continue;
300 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 users.add(profile);
302 }
303 return users;
304 }
305
Jessica Hummelbe81c802014-04-22 15:49:22 +0100306 @Override
307 public UserInfo getProfileParent(int userHandle) {
308 checkManageUsersPermission("get the profile parent");
309 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700310 return getProfileParentLocked(userHandle);
311 }
312 }
313
314 private UserInfo getProfileParentLocked(int userHandle) {
315 UserInfo profile = getUserInfoLocked(userHandle);
316 if (profile == null) {
317 return null;
318 }
319 int parentUserId = profile.profileGroupId;
320 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
321 return null;
322 } else {
323 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100324 }
325 }
326
Kenny Guy2a764942014-04-02 13:29:20 +0100327 private boolean isProfileOf(UserInfo user, UserInfo profile) {
328 return user.id == profile.id ||
329 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
330 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000331 }
332
333 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100334 public void setUserEnabled(int userId) {
335 checkManageUsersPermission("enable user");
336 synchronized (mPackagesLock) {
337 UserInfo info = getUserInfoLocked(userId);
338 if (info != null && !info.isEnabled()) {
339 info.flags ^= UserInfo.FLAG_DISABLED;
340 writeUserLocked(info);
341 }
342 }
343 }
344
345 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700347 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700348 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700349 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700350 }
351 }
352
Amith Yamasani71e6c692013-03-24 17:39:28 -0700353 @Override
354 public boolean isRestricted() {
355 synchronized (mPackagesLock) {
356 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
357 }
358 }
359
Amith Yamasani195263742012-08-21 15:40:12 -0700360 /*
361 * Should be locked on mUsers before calling this.
362 */
363 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700365 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800366 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700367 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
368 return null;
369 }
370 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700371 }
372
Amith Yamasani13593602012-03-22 16:16:17 -0700373 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700374 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700375 return ArrayUtils.contains(mUserIds, userId);
376 }
377 }
378
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700380 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700381 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700382 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700383 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700384 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700385 if (info == null || info.partial) {
386 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
387 return;
388 }
Amith Yamasani13593602012-03-22 16:16:17 -0700389 if (name != null && !name.equals(info.name)) {
390 info.name = name;
391 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700392 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700393 }
394 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700395 if (changed) {
396 sendUserInfoChangedBroadcast(userId);
397 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700398 }
399
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700401 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700402 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400403 long ident = Binder.clearCallingIdentity();
404 try {
405 synchronized (mPackagesLock) {
406 UserInfo info = mUsers.get(userId);
407 if (info == null || info.partial) {
408 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
409 return;
410 }
411 writeBitmapLocked(info, bitmap);
412 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 }
Jason Monk9a944532014-07-08 09:31:21 -0400414 sendUserInfoChangedBroadcast(userId);
415 } finally {
416 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700417 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700418 }
419
420 private void sendUserInfoChangedBroadcast(int userId) {
421 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
422 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
423 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700424 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700425 }
426
Amith Yamasani258848d2012-08-10 17:06:33 -0700427 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100428 public ParcelFileDescriptor getUserIcon(int userId) {
429 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700430 synchronized (mPackagesLock) {
431 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700432 if (info == null || info.partial) {
433 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
434 return null;
435 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100436 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
437 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
438 || callingGroupId != info.profileGroupId) {
439 checkManageUsersPermission("get the icon of a user who is not related");
440 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 if (info.iconPath == null) {
442 return null;
443 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100444 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700445 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100446
447 try {
448 return ParcelFileDescriptor.open(
449 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
450 } catch (FileNotFoundException e) {
451 Log.e(LOG_TAG, "Couldn't find icon file", e);
452 }
453 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700454 }
455
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700456 public void makeInitialized(int userId) {
457 checkManageUsersPermission("makeInitialized");
458 synchronized (mPackagesLock) {
459 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700460 if (info == null || info.partial) {
461 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
462 }
463 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700464 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800465 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700466 }
467 }
468 }
469
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700470 /**
471 * If default guest restrictions haven't been initialized yet, add the basic
472 * restrictions.
473 */
474 private void initDefaultGuestRestrictions() {
475 if (mGuestRestrictions.isEmpty()) {
476 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800477 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700478 }
479 }
480
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800481 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530482 public Bundle getDefaultGuestRestrictions() {
483 checkManageUsersPermission("getDefaultGuestRestrictions");
484 synchronized (mPackagesLock) {
485 return new Bundle(mGuestRestrictions);
486 }
487 }
488
489 @Override
490 public void setDefaultGuestRestrictions(Bundle restrictions) {
491 checkManageUsersPermission("setDefaultGuestRestrictions");
492 synchronized (mPackagesLock) {
493 mGuestRestrictions.clear();
494 mGuestRestrictions.putAll(restrictions);
495 writeUserListLocked();
496 }
497 }
498
499 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700500 public boolean hasUserRestriction(String restrictionKey, int userId) {
501 synchronized (mPackagesLock) {
502 Bundle restrictions = mUserRestrictions.get(userId);
503 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
504 }
505 }
506
507 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800508 public Bundle getUserRestrictions(int userId) {
509 // checkManageUsersPermission("getUserRestrictions");
510
511 synchronized (mPackagesLock) {
512 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700513 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800514 }
515 }
516
517 @Override
518 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700519 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700520 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800521
522 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700523 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800524 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400525 long token = Binder.clearCallingIdentity();
526 try {
527 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
528 } catch (RemoteException e) {
529 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
530 } finally {
531 Binder.restoreCallingIdentity(token);
532 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800533 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800534 }
535 }
536
Amith Yamasani258848d2012-08-10 17:06:33 -0700537 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700538 * Check if we've hit the limit of how many users can be created.
539 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700540 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700541 int aliveUserCount = 0;
542 final int totalUserCount = mUsers.size();
543 // Skip over users being removed
544 for (int i = 0; i < totalUserCount; i++) {
545 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700546 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700547 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700548 aliveUserCount++;
549 }
550 }
551 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700552 }
553
554 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700555 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700556 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700557 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700558 *
559 * @param message used as message if SecurityException is thrown
560 * @throws SecurityException if the caller is not system or root
561 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700563 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700564 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400565 && ActivityManager.checkComponentPermission(
566 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700567 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
568 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
569 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400570 }
571
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700572 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700573 try {
574 File dir = new File(mUsersDir, Integer.toString(info.id));
575 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100576 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700577 if (!dir.exists()) {
578 dir.mkdir();
579 FileUtils.setPermissions(
580 dir.getPath(),
581 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
582 -1, -1);
583 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700584 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100585 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
586 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700587 info.iconPath = file.getAbsolutePath();
588 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700589 try {
590 os.close();
591 } catch (IOException ioe) {
592 // What the ... !
593 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100594 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700595 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700596 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700598 }
599
Amith Yamasani0b285492011-04-14 17:35:23 -0700600 /**
601 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
602 * cache it elsewhere.
603 * @return the array of user ids.
604 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700605 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700606 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700607 return mUserIds;
608 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700609 }
610
Dianne Hackborn4428e172012-08-24 17:43:05 -0700611 int[] getUserIdsLPr() {
612 return mUserIds;
613 }
614
Amith Yamasani13593602012-03-22 16:16:17 -0700615 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700616 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700617 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700618 return;
619 }
620 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700621 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700622 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700623 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700624 XmlPullParser parser = Xml.newPullParser();
625 parser.setInput(fis, null);
626 int type;
627 while ((type = parser.next()) != XmlPullParser.START_TAG
628 && type != XmlPullParser.END_DOCUMENT) {
629 ;
630 }
631
632 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700633 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700634 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700635 return;
636 }
637
Amith Yamasani2a003292012-08-14 18:25:45 -0700638 mNextSerialNumber = -1;
639 if (parser.getName().equals(TAG_USERS)) {
640 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
641 if (lastSerialNumber != null) {
642 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
643 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700644 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
645 if (versionNumber != null) {
646 mUserVersion = Integer.parseInt(versionNumber);
647 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700648 }
649
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700650 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530651 if (type == XmlPullParser.START_TAG) {
652 final String name = parser.getName();
653 if (name.equals(TAG_USER)) {
654 String id = parser.getAttributeValue(null, ATTR_ID);
655 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700656
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530657 if (user != null) {
658 mUsers.put(user.id, user);
659 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
660 mNextSerialNumber = user.id + 1;
661 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700662 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530663 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800664 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
665 && type != XmlPullParser.END_TAG) {
666 if (type == XmlPullParser.START_TAG) {
667 if (parser.getName().equals(TAG_RESTRICTIONS)) {
668 readRestrictionsLocked(parser, mGuestRestrictions);
669 }
670 break;
671 }
672 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700673 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700674 }
675 }
Amith Yamasani13593602012-03-22 16:16:17 -0700676 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700677 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700678 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700679 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700680 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700681 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800682 } finally {
683 if (fis != null) {
684 try {
685 fis.close();
686 } catch (IOException e) {
687 }
688 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 }
690 }
691
Amith Yamasani6f34b412012-10-22 18:19:27 -0700692 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800693 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700694 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700695 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700696 int userVersion = mUserVersion;
697 if (userVersion < 1) {
698 // Assign a proper name for the owner, if not initialized correctly before
699 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
700 if ("Primary".equals(user.name)) {
701 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800702 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700703 }
704 userVersion = 1;
705 }
706
Amith Yamasanibc9625052012-11-15 14:39:18 -0800707 if (userVersion < 2) {
708 // Owner should be marked as initialized
709 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
710 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
711 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800712 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800713 }
714 userVersion = 2;
715 }
716
Amith Yamasani350962c2013-08-06 11:18:53 -0700717
Amith Yamasani5e486f52013-08-07 11:06:44 -0700718 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700719 userVersion = 4;
720 }
721
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700722 if (userVersion < 5) {
723 initDefaultGuestRestrictions();
724 userVersion = 5;
725 }
726
Amith Yamasani6f34b412012-10-22 18:19:27 -0700727 if (userVersion < USER_VERSION) {
728 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
729 + USER_VERSION);
730 } else {
731 mUserVersion = userVersion;
732 writeUserListLocked();
733 }
734 }
735
Amith Yamasani13593602012-03-22 16:16:17 -0700736 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700737 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800738 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700739 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700740 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700742 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400743 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800744
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500745 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800746 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
747
Amith Yamasani13593602012-03-22 16:16:17 -0700748 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700749 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700750
Amith Yamasani13593602012-03-22 16:16:17 -0700751 writeUserListLocked();
752 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700753 }
754
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800755 private void scheduleWriteUserLocked(UserInfo userInfo) {
756 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
757 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
758 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
759 }
760 }
761
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762 /*
763 * Writes the user file in this format:
764 *
765 * <user flags="20039023" id="0">
766 * <name>Primary</name>
767 * </user>
768 */
Amith Yamasani13593602012-03-22 16:16:17 -0700769 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700770 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700771 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700773 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 final BufferedOutputStream bos = new BufferedOutputStream(fos);
775
776 // XmlSerializer serializer = XmlUtils.serializerInstance();
777 final XmlSerializer serializer = new FastXmlSerializer();
778 serializer.setOutput(bos, "utf-8");
779 serializer.startDocument(null, true);
780 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
781
782 serializer.startTag(null, TAG_USER);
783 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700784 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700785 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700786 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
787 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
788 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700789 if (userInfo.iconPath != null) {
790 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
791 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700792 if (userInfo.partial) {
793 serializer.attribute(null, ATTR_PARTIAL, "true");
794 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700795 if (userInfo.guestToRemove) {
796 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
797 }
Kenny Guy2a764942014-04-02 13:29:20 +0100798 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
799 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
800 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000801 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802
803 serializer.startTag(null, TAG_NAME);
804 serializer.text(userInfo.name);
805 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800806 Bundle restrictions = mUserRestrictions.get(userInfo.id);
807 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530808 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800809 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 serializer.endTag(null, TAG_USER);
811
812 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700813 userFile.finishWrite(fos);
814 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700815 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700816 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 }
818 }
819
820 /*
821 * Writes the user list file in this format:
822 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700823 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824 * <user id="0"></user>
825 * <user id="2"></user>
826 * </users>
827 */
Amith Yamasani13593602012-03-22 16:16:17 -0700828 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700829 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700830 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700831 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700832 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 final BufferedOutputStream bos = new BufferedOutputStream(fos);
834
835 // XmlSerializer serializer = XmlUtils.serializerInstance();
836 final XmlSerializer serializer = new FastXmlSerializer();
837 serializer.setOutput(bos, "utf-8");
838 serializer.startDocument(null, true);
839 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
840
841 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700842 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700843 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700844
Adam Lesinskieddeb492014-09-08 17:50:03 -0700845 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530846 writeRestrictionsLocked(serializer, mGuestRestrictions);
847 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700848 for (int i = 0; i < mUsers.size(); i++) {
849 UserInfo user = mUsers.valueAt(i);
850 serializer.startTag(null, TAG_USER);
851 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
852 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700853 }
854
855 serializer.endTag(null, TAG_USERS);
856
857 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700858 userListFile.finishWrite(fos);
859 } catch (Exception e) {
860 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700861 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700862 }
863 }
864
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530865 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
866 throws IOException {
867 serializer.startTag(null, TAG_RESTRICTIONS);
868 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
869 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
870 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
871 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
872 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
873 writeBoolean(serializer, restrictions,
874 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
875 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
876 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
877 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
878 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
879 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
880 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
881 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
882 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
883 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
884 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
885 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
886 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
887 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
888 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
889 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
890 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700891 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
892 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400893 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700894 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
895 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000896 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000897 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530898 serializer.endTag(null, TAG_RESTRICTIONS);
899 }
900
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800901 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700903 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700904 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700905 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700906 long creationTime = 0L;
907 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +0100908 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700909 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700910 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800911 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700912
913 FileInputStream fis = null;
914 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700915 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700916 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700917 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918 XmlPullParser parser = Xml.newPullParser();
919 parser.setInput(fis, null);
920 int type;
921 while ((type = parser.next()) != XmlPullParser.START_TAG
922 && type != XmlPullParser.END_DOCUMENT) {
923 ;
924 }
925
926 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700927 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 return null;
929 }
930
931 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700932 int storedId = readIntAttribute(parser, ATTR_ID, -1);
933 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700934 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700935 return null;
936 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700937 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
938 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700939 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700940 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
941 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +0100942 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
943 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
945 if ("true".equals(valueString)) {
946 partial = true;
947 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700948 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
949 if ("true".equals(valueString)) {
950 guestToRemove = true;
951 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700952
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800953 int outerDepth = parser.getDepth();
954 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
955 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
956 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
957 continue;
958 }
959 String tag = parser.getName();
960 if (TAG_NAME.equals(tag)) {
961 type = parser.next();
962 if (type == XmlPullParser.TEXT) {
963 name = parser.getText();
964 }
965 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530966 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 }
968 }
969 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700971 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700972 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700973 userInfo.creationTime = creationTime;
974 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700975 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700976 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +0100977 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800978 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700979 return userInfo;
980
981 } catch (IOException ioe) {
982 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800983 } finally {
984 if (fis != null) {
985 try {
986 fis.close();
987 } catch (IOException e) {
988 }
989 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700990 }
991 return null;
992 }
993
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530994 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
995 throws IOException {
996 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
997 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
998 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
999 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1000 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1001 readBoolean(parser, restrictions,
1002 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1003 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1004 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1005 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1006 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1007 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1008 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1009 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1010 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1011 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1012 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1013 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1014 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1015 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1016 readBoolean(parser, restrictions,
1017 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1018 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1019 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001020 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1021 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001022 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001023 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1024 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001025 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001026 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301027 }
1028
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001029 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1030 String restrictionKey) {
1031 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001032 if (value != null) {
1033 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1034 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001035 }
1036
1037 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1038 throws IOException {
1039 if (restrictions.containsKey(restrictionKey)) {
1040 xml.attribute(null, restrictionKey,
1041 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1042 }
1043 }
1044
Amith Yamasani920ace02012-09-20 22:15:37 -07001045 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1046 String valueString = parser.getAttributeValue(null, attr);
1047 if (valueString == null) return defaultValue;
1048 try {
1049 return Integer.parseInt(valueString);
1050 } catch (NumberFormatException nfe) {
1051 return defaultValue;
1052 }
1053 }
1054
1055 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1056 String valueString = parser.getAttributeValue(null, attr);
1057 if (valueString == null) return defaultValue;
1058 try {
1059 return Long.parseLong(valueString);
1060 } catch (NumberFormatException nfe) {
1061 return defaultValue;
1062 }
1063 }
1064
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001065 private boolean isPackageInstalled(String pkg, int userId) {
1066 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1067 PackageManager.GET_UNINSTALLED_PACKAGES,
1068 userId);
1069 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1070 return false;
1071 }
1072 return true;
1073 }
1074
Amith Yamasanib82add22013-07-09 11:24:44 -07001075 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001076 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001077 * Does not do any permissions checking.
1078 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001079 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001080 synchronized (mPackagesLock) {
1081 File dir = Environment.getUserSystemDirectory(userId);
1082 String[] files = dir.list();
1083 if (files == null) return;
1084 for (String fileName : files) {
1085 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1086 File resFile = new File(dir, fileName);
1087 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001088 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001089 }
1090 }
1091 }
1092 }
1093 }
1094
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001095 /**
1096 * Removes the app restrictions file for a specific package and user id, if it exists.
1097 */
1098 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1099 synchronized (mPackagesLock) {
1100 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001101 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001102 if (resFile.exists()) {
1103 resFile.delete();
1104 }
1105 }
1106 }
1107
Kenny Guya52dc3e2014-02-11 15:33:14 +00001108 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001109 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001110 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001111 if (userId != UserHandle.USER_OWNER) {
1112 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001113 return null;
1114 }
Kenny Guy2a764942014-04-02 13:29:20 +01001115 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001116 }
1117
Amith Yamasani258848d2012-08-10 17:06:33 -07001118 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001119 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001120 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001121 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001122 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001123
Jessica Hummelbe81c802014-04-22 15:49:22 +01001124 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001125 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1126 UserManager.DISALLOW_ADD_USER, false)) {
1127 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1128 return null;
1129 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001130 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001131 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001132 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001133 try {
1134 synchronized (mInstallLock) {
1135 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001136 UserInfo parent = null;
1137 if (parentId != UserHandle.USER_NULL) {
1138 parent = getUserInfoLocked(parentId);
1139 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001140 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001141 // If we're not adding a guest user and the limit has been reached,
1142 // cannot add a user.
1143 if (!isGuest && isUserLimitReachedLocked()) {
1144 return null;
1145 }
1146 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001147 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001148 return null;
1149 }
1150 // Limit number of managed profiles that can be created
1151 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1152 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1153 >= MAX_MANAGED_PROFILES) {
1154 return null;
1155 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001156 int userId = getNextAvailableIdLocked();
1157 userInfo = new UserInfo(userId, name, null, flags);
1158 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1159 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001160 long now = System.currentTimeMillis();
1161 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001162 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001163 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001164 mUsers.put(userId, userInfo);
1165 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001166 if (parent != null) {
1167 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1168 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001169 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001170 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001171 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001172 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001173 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001174 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001175 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001176 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001177 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001178 mUserRestrictions.append(userId, restrictions);
Svet Ganov78027f32015-03-25 09:10:09 -07001179 mPm.newUserCreatedLILPw(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001180 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001181 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001182 if (userInfo != null) {
1183 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1184 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1185 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1186 android.Manifest.permission.MANAGE_USERS);
1187 }
1188 } finally {
1189 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001190 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001191 return userInfo;
1192 }
1193
Amith Yamasani95ab7842014-08-11 17:09:26 -07001194 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1195 int count = 0;
1196 for (int i = mUsers.size() - 1; i >= 0; i--) {
1197 UserInfo user = mUsers.valueAt(i);
1198 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1199 if ((user.flags & flags) != 0) {
1200 count++;
1201 }
1202 }
1203 }
1204 return count;
1205 }
1206
Amith Yamasani0b285492011-04-14 17:35:23 -07001207 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001208 * Find the current guest user. If the Guest user is partial,
1209 * then do not include it in the results as it is about to die.
1210 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1211 * the special handling of Guests being removed.
1212 */
1213 private UserInfo findCurrentGuestUserLocked() {
1214 final int size = mUsers.size();
1215 for (int i = 0; i < size; i++) {
1216 final UserInfo user = mUsers.valueAt(i);
1217 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1218 return user;
1219 }
1220 }
1221 return null;
1222 }
1223
1224 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001225 * Mark this guest user for deletion to allow us to create another guest
1226 * and switch to that user before actually removing this guest.
1227 * @param userHandle the userid of the current guest
1228 * @return whether the user could be marked for deletion
1229 */
1230 public boolean markGuestForDeletion(int userHandle) {
1231 checkManageUsersPermission("Only the system can remove users");
1232 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1233 UserManager.DISALLOW_REMOVE_USER, false)) {
1234 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1235 return false;
1236 }
1237
1238 long ident = Binder.clearCallingIdentity();
1239 try {
1240 final UserInfo user;
1241 synchronized (mPackagesLock) {
1242 user = mUsers.get(userHandle);
1243 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1244 return false;
1245 }
1246 if (!user.isGuest()) {
1247 return false;
1248 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001249 // We set this to a guest user that is to be removed. This is a temporary state
1250 // where we are allowed to add new Guest users, even if this one is still not
1251 // removed. This user will still show up in getUserInfo() calls.
1252 // If we don't get around to removing this Guest user, it will be purged on next
1253 // startup.
1254 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001255 // Mark it as disabled, so that it isn't returned any more when
1256 // profiles are queried.
1257 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001258 writeUserLocked(user);
1259 }
1260 } finally {
1261 Binder.restoreCallingIdentity(ident);
1262 }
1263 return true;
1264 }
1265
1266 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001267 * Removes a user and all data directories created for that user. This method should be called
1268 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001269 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001270 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001271 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001272 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001273 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1274 UserManager.DISALLOW_REMOVE_USER, false)) {
1275 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1276 return false;
1277 }
1278
Kenny Guyee58b4f2014-05-23 15:19:53 +01001279 long ident = Binder.clearCallingIdentity();
1280 try {
1281 final UserInfo user;
1282 synchronized (mPackagesLock) {
1283 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001284 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001285 return false;
1286 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001287
1288 // We remember deleted user IDs to prevent them from being
1289 // reused during the current boot; they can still be reused
1290 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001291 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001292
Kenny Guyee58b4f2014-05-23 15:19:53 +01001293 try {
1294 mAppOpsService.removeUser(userHandle);
1295 } catch (RemoteException e) {
1296 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1297 }
1298 // Set this to a partially created user, so that the user will be purged
1299 // on next startup, in case the runtime stops now before stopping and
1300 // removing the user completely.
1301 user.partial = true;
1302 // Mark it as disabled, so that it isn't returned any more when
1303 // profiles are queried.
1304 user.flags |= UserInfo.FLAG_DISABLED;
1305 writeUserLocked(user);
1306 }
1307
1308 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1309 && user.isManagedProfile()) {
1310 // Send broadcast to notify system that the user removed was a
1311 // managed user.
1312 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1313 }
1314
1315 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1316 int res;
1317 try {
1318 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1319 new IStopUserCallback.Stub() {
1320 @Override
1321 public void userStopped(int userId) {
1322 finishRemoveUser(userId);
1323 }
1324 @Override
1325 public void userStopAborted(int userId) {
1326 }
1327 });
1328 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001329 return false;
1330 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001331 return res == ActivityManager.USER_OP_SUCCESS;
1332 } finally {
1333 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001334 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001335 }
1336
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001337 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001338 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001339 // Let other services shutdown any activity and clean up their state before completely
1340 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001341 long ident = Binder.clearCallingIdentity();
1342 try {
1343 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1344 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001345 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1346 android.Manifest.permission.MANAGE_USERS,
1347
1348 new BroadcastReceiver() {
1349 @Override
1350 public void onReceive(Context context, Intent intent) {
1351 if (DBG) {
1352 Slog.i(LOG_TAG,
1353 "USER_REMOVED broadcast sent, cleaning up user data "
1354 + userHandle);
1355 }
1356 new Thread() {
1357 public void run() {
1358 synchronized (mInstallLock) {
1359 synchronized (mPackagesLock) {
1360 removeUserStateLocked(userHandle);
1361 }
1362 }
1363 }
1364 }.start();
1365 }
1366 },
1367
1368 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001369 } finally {
1370 Binder.restoreCallingIdentity(ident);
1371 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001372 }
1373
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001374 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001375 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001376 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001377
1378 // Remove this user from the list
1379 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001380 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001381 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001382 userFile.delete();
1383 // Update the user list
1384 writeUserListLocked();
1385 updateUserIdsLocked();
1386 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1387 }
1388
Amith Yamasani61f57372012-08-31 12:12:28 -07001389 private void removeDirectoryRecursive(File parent) {
1390 if (parent.isDirectory()) {
1391 String[] files = parent.list();
1392 for (String filename : files) {
1393 File child = new File(parent, filename);
1394 removeDirectoryRecursive(child);
1395 }
1396 }
1397 parent.delete();
1398 }
1399
Kenny Guyf8d3a232014-05-15 16:09:52 +01001400 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001401 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001402 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1403 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001404 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1405 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001406 }
1407
Amith Yamasani2a003292012-08-14 18:25:45 -07001408 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001409 public Bundle getApplicationRestrictions(String packageName) {
1410 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1411 }
1412
1413 @Override
1414 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001415 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001416 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001417 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001418 }
1419 synchronized (mPackagesLock) {
1420 // Read the restrictions from XML
1421 return readApplicationRestrictionsLocked(packageName, userId);
1422 }
1423 }
1424
1425 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001426 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001427 int userId) {
1428 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001429 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001430 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001431 }
1432 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001433 if (restrictions == null || restrictions.isEmpty()) {
1434 cleanAppRestrictionsForPackage(packageName, userId);
1435 } else {
1436 // Write the restrictions to XML
1437 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1438 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001439 }
Robin Lee66e5d962014-04-09 16:44:21 +01001440
Kenny Guyd21b2182014-07-17 16:38:55 +01001441 if (isPackageInstalled(packageName, userId)) {
1442 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1443 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1444 changeIntent.setPackage(packageName);
1445 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1446 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1447 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001448 }
1449
Amith Yamasani655d0e22013-06-12 14:19:10 -07001450 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001451 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001452 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001453 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001454 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001455 }
1456
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001457 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001458 synchronized (mPackagesLock) {
1459 // Remove all user restrictions
1460 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001461 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001462 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001463 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001464 if (unhideApps) {
1465 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001466 }
1467 }
1468
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001469 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001470 mHandler.post(new Runnable() {
1471 @Override
1472 public void run() {
1473 List<ApplicationInfo> apps =
1474 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1475 userHandle).getList();
1476 final long ident = Binder.clearCallingIdentity();
1477 try {
1478 for (ApplicationInfo appInfo : apps) {
1479 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001480 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1481 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001482 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001483 userHandle);
1484 }
1485 }
1486 } finally {
1487 Binder.restoreCallingIdentity(ident);
1488 }
1489 }
1490 });
1491 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001492 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001493 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001494 try {
1495 return mContext.getPackageManager().getApplicationInfo(packageName,
1496 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1497 } catch (NameNotFoundException nnfe) {
1498 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001499 } finally {
1500 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001501 }
1502 }
1503
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001504 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001505 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001506 AtomicFile restrictionsFile =
1507 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1508 packageToRestrictionsFileName(packageName)));
1509 return readApplicationRestrictionsLocked(restrictionsFile);
1510 }
1511
1512 @VisibleForTesting
1513 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001514 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001515 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001516 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001517 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001518 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001519
1520 FileInputStream fis = null;
1521 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001522 fis = restrictionsFile.openRead();
1523 XmlPullParser parser = Xml.newPullParser();
1524 parser.setInput(fis, null);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001525 XmlUtils.nextElement(parser);
1526 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001527 Slog.e(LOG_TAG, "Unable to read restrictions file "
1528 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001529 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001530 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001531 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1532 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001533 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001534 } catch (IOException|XmlPullParserException e) {
1535 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001536 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001537 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001539 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001540 }
1541
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001542 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1543 XmlPullParser parser) throws XmlPullParserException, IOException {
1544 int type = parser.getEventType();
1545 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1546 String key = parser.getAttributeValue(null, ATTR_KEY);
1547 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1548 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1549 if (multiple != null) {
1550 values.clear();
1551 int count = Integer.parseInt(multiple);
1552 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1553 if (type == XmlPullParser.START_TAG
1554 && parser.getName().equals(TAG_VALUE)) {
1555 values.add(parser.nextText().trim());
1556 count--;
1557 }
1558 }
1559 String [] valueStrings = new String[values.size()];
1560 values.toArray(valueStrings);
1561 restrictions.putStringArray(key, valueStrings);
1562 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1563 restrictions.putBundle(key, readBundleEntry(parser, values));
1564 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1565 final int outerDepth = parser.getDepth();
1566 ArrayList<Bundle> bundleList = new ArrayList<>();
1567 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1568 Bundle childBundle = readBundleEntry(parser, values);
1569 bundleList.add(childBundle);
1570 }
1571 restrictions.putParcelableArray(key,
1572 bundleList.toArray(new Bundle[bundleList.size()]));
1573 } else {
1574 String value = parser.nextText().trim();
1575 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1576 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1577 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1578 restrictions.putInt(key, Integer.parseInt(value));
1579 } else {
1580 restrictions.putString(key, value);
1581 }
1582 }
1583 }
1584 }
1585
1586 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1587 throws IOException, XmlPullParserException {
1588 Bundle childBundle = new Bundle();
1589 final int outerDepth = parser.getDepth();
1590 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1591 readEntry(childBundle, values, parser);
1592 }
1593 return childBundle;
1594 }
1595
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001596 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001597 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001598 AtomicFile restrictionsFile = new AtomicFile(
1599 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001600 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001601 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1602 }
1603
1604 @VisibleForTesting
1605 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1606 AtomicFile restrictionsFile) {
1607 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 try {
1609 fos = restrictionsFile.startWrite();
1610 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1611
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001612 final XmlSerializer serializer = new FastXmlSerializer();
1613 serializer.setOutput(bos, "utf-8");
1614 serializer.startDocument(null, true);
1615 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1616
1617 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001618 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001619 serializer.endTag(null, TAG_RESTRICTIONS);
1620
1621 serializer.endDocument();
1622 restrictionsFile.finishWrite(fos);
1623 } catch (Exception e) {
1624 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001625 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1626 }
1627 }
1628
1629 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1630 throws IOException {
1631 for (String key : restrictions.keySet()) {
1632 Object value = restrictions.get(key);
1633 serializer.startTag(null, TAG_ENTRY);
1634 serializer.attribute(null, ATTR_KEY, key);
1635
1636 if (value instanceof Boolean) {
1637 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1638 serializer.text(value.toString());
1639 } else if (value instanceof Integer) {
1640 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1641 serializer.text(value.toString());
1642 } else if (value == null || value instanceof String) {
1643 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1644 serializer.text(value != null ? (String) value : "");
1645 } else if (value instanceof Bundle) {
1646 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1647 writeBundle((Bundle) value, serializer);
1648 } else if (value instanceof Parcelable[]) {
1649 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1650 Parcelable[] array = (Parcelable[]) value;
1651 for (Parcelable parcelable : array) {
1652 if (!(parcelable instanceof Bundle)) {
1653 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1654 }
1655 serializer.startTag(null, TAG_ENTRY);
1656 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1657 writeBundle((Bundle) parcelable, serializer);
1658 serializer.endTag(null, TAG_ENTRY);
1659 }
1660 } else {
1661 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1662 String[] values = (String[]) value;
1663 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1664 for (String choice : values) {
1665 serializer.startTag(null, TAG_VALUE);
1666 serializer.text(choice != null ? choice : "");
1667 serializer.endTag(null, TAG_VALUE);
1668 }
1669 }
1670 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001671 }
1672 }
1673
1674 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001675 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001676 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001677 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001678 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001679 }
1680 }
1681
1682 @Override
1683 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001684 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001685 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001686 UserInfo info = getUserInfoLocked(userId);
1687 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001688 }
1689 // Not found
1690 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001691 }
1692 }
1693
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001694 @Override
1695 public long getUserCreationTime(int userHandle) {
1696 int callingUserId = UserHandle.getCallingUserId();
1697 UserInfo userInfo = null;
1698 synchronized (mPackagesLock) {
1699 if (callingUserId == userHandle) {
1700 userInfo = getUserInfoLocked(userHandle);
1701 } else {
1702 UserInfo parent = getProfileParentLocked(userHandle);
1703 if (parent != null && parent.id == callingUserId) {
1704 userInfo = getUserInfoLocked(userHandle);
1705 }
1706 }
1707 }
1708 if (userInfo == null) {
1709 throw new SecurityException("userHandle can only be the calling user or a managed "
1710 + "profile associated with this user");
1711 }
1712 return userInfo.creationTime;
1713 }
1714
Amith Yamasani0b285492011-04-14 17:35:23 -07001715 /**
1716 * Caches the list of user ids in an array, adjusting the array size when necessary.
1717 */
Amith Yamasani13593602012-03-22 16:16:17 -07001718 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001719 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001720 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001721 if (!mUsers.valueAt(i).partial) {
1722 num++;
1723 }
1724 }
Amith Yamasani16389312012-10-17 21:20:14 -07001725 final int[] newUsers = new int[num];
1726 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001727 for (int i = 0; i < mUsers.size(); i++) {
1728 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001729 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001730 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001731 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001732 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001733 }
1734
1735 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001736 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001737 * @param userId the user that was just foregrounded
1738 */
1739 public void userForeground(int userId) {
1740 synchronized (mPackagesLock) {
1741 UserInfo user = mUsers.get(userId);
1742 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001743 if (user == null || user.partial) {
1744 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1745 return;
1746 }
1747 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001748 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001749 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001750 }
1751 }
1752 }
1753
1754 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001755 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001756 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1757 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001758 * @return
1759 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001760 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001761 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001762 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001763 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001764 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001765 break;
1766 }
1767 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001768 }
Amith Yamasani195263742012-08-21 15:40:12 -07001769 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001771 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001772
Amith Yamasanifc95e702013-09-26 13:20:17 -07001773 private String packageToRestrictionsFileName(String packageName) {
1774 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1775 }
1776
Amith Yamasani920ace02012-09-20 22:15:37 -07001777 @Override
1778 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1779 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1780 != PackageManager.PERMISSION_GRANTED) {
1781 pw.println("Permission Denial: can't dump UserManager from from pid="
1782 + Binder.getCallingPid()
1783 + ", uid=" + Binder.getCallingUid()
1784 + " without permission "
1785 + android.Manifest.permission.DUMP);
1786 return;
1787 }
1788
1789 long now = System.currentTimeMillis();
1790 StringBuilder sb = new StringBuilder();
1791 synchronized (mPackagesLock) {
1792 pw.println("Users:");
1793 for (int i = 0; i < mUsers.size(); i++) {
1794 UserInfo user = mUsers.valueAt(i);
1795 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001796 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001797 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001798 if (user.partial) pw.print(" <partial>");
1799 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001800 pw.print(" Created: ");
1801 if (user.creationTime == 0) {
1802 pw.println("<unknown>");
1803 } else {
1804 sb.setLength(0);
1805 TimeUtils.formatDuration(now - user.creationTime, sb);
1806 sb.append(" ago");
1807 pw.println(sb);
1808 }
1809 pw.print(" Last logged in: ");
1810 if (user.lastLoggedInTime == 0) {
1811 pw.println("<unknown>");
1812 } else {
1813 sb.setLength(0);
1814 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1815 sb.append(" ago");
1816 pw.println(sb);
1817 }
1818 }
1819 }
1820 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001821
1822 final class MainHandler extends Handler {
1823
1824 @Override
1825 public void handleMessage(Message msg) {
1826 switch (msg.what) {
1827 case WRITE_USER_MSG:
1828 removeMessages(WRITE_USER_MSG, msg.obj);
1829 synchronized (mPackagesLock) {
1830 int userId = ((UserInfo) msg.obj).id;
1831 UserInfo userInfo = mUsers.get(userId);
1832 if (userInfo != null) {
1833 writeUserLocked(userInfo);
1834 }
1835 }
1836 }
1837 }
1838 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001839}