blob: 23cb76771b5875688df37fc5042a98401004de7b [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080032import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.os.Environment;
34import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080035import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080037import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010038import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070039import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070045import android.os.storage.StorageManager;
46import android.os.storage.VolumeInfo;
47import android.system.ErrnoException;
48import android.system.Os;
49import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070050import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070051import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Slog;
53import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070055import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import android.util.Xml;
57
Fyodor Kupolovb5013302015-04-17 17:59:14 -070058import com.google.android.collect.Sets;
59
Fyodor Kupolov262f9952015-03-23 18:55:11 -070060import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040061import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080062import com.android.internal.util.ArrayUtils;
63import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070064import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68import org.xmlpull.v1.XmlSerializer;
69
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import java.io.BufferedOutputStream;
71import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070072import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070074import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.io.FileOutputStream;
76import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070077import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010078import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.util.ArrayList;
80import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070081import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082
Fyodor Kupolov262f9952015-03-23 18:55:11 -070083import libcore.io.IoUtils;
84
Amith Yamasani258848d2012-08-10 17:06:33 -070085public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070086
Amith Yamasani2a003292012-08-14 18:25:45 -070087 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088
Amith Yamasani16389312012-10-17 21:20:14 -070089 private static final boolean DBG = false;
90
Amith Yamasani4b2e9342011-03-31 12:38:53 -070091 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070093 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070095 private static final String ATTR_CREATION_TIME = "created";
96 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070097 private static final String ATTR_SERIAL_NO = "serialNumber";
98 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070099 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700100 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700101 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100102 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530103 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800106 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800107 private static final String TAG_ENTRY = "entry";
108 private static final String TAG_VALUE = "value";
109 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700110 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800111 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700113 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
114 private static final String ATTR_TYPE_STRING = "s";
115 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700116 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700117 private static final String ATTR_TYPE_BUNDLE = "B";
118 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700119
Amith Yamasani0b285492011-04-14 17:35:23 -0700120 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700122 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100123 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800125 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700126 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127
Amith Yamasani634cf312012-10-04 17:34:21 -0700128 private static final int MIN_USER_ID = 10;
129
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700130 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700131
Amith Yamasani920ace02012-09-20 22:15:37 -0700132 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
133
Amith Yamasani95ab7842014-08-11 17:09:26 -0700134 // Maximum number of managed profiles permitted is 1. This cannot be increased
135 // without first making sure that the rest of the framework is prepared for it.
136 private static final int MAX_MANAGED_PROFILES = 1;
137
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700138 // Set of user restrictions, which can only be enforced by the system
139 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
140 UserManager.DISALLOW_RECORD_AUDIO);
141
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800142 static final int WRITE_USER_MSG = 1;
143 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530144
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700145 private static final String XATTR_SERIAL = "user.serial";
146
Dianne Hackborn4428e172012-08-24 17:43:05 -0700147 private final Context mContext;
148 private final PackageManagerService mPm;
149 private final Object mInstallLock;
150 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800152 private final Handler mHandler;
153
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private final File mUsersDir;
155 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700156
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800157 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800158 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800160
161 /**
162 * Set of user IDs being actively removed. Removed IDs linger in this set
163 * for several seconds to work around a VFS caching issue.
164 */
165 // @GuardedBy("mPackagesLock")
166 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167
Amith Yamasani0b285492011-04-14 17:35:23 -0700168 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700169 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700170 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700171
Jason Monk62062992014-05-06 09:55:28 -0400172 private IAppOpsService mAppOpsService;
173
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700175
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176 public static UserManagerService getInstance() {
177 synchronized (UserManagerService.class) {
178 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700179 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700180 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700181
182 /**
183 * Available for testing purposes.
184 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700185 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187 }
188
Dianne Hackborn4428e172012-08-24 17:43:05 -0700189 /**
190 * Called by package manager to create the service. This is closely
191 * associated with the package manager, and the given lock is the
192 * package manager's own lock.
193 */
194 UserManagerService(Context context, PackageManagerService pm,
195 Object installLock, Object packagesLock) {
196 this(context, pm, installLock, packagesLock,
197 Environment.getDataDirectory(),
198 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700199 }
200
Dianne Hackborn4428e172012-08-24 17:43:05 -0700201 /**
202 * Available for testing purposes.
203 */
204 private UserManagerService(Context context, PackageManagerService pm,
205 Object installLock, Object packagesLock,
206 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700207 mContext = context;
208 mPm = pm;
209 mInstallLock = installLock;
210 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800211 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700212 synchronized (mInstallLock) {
213 synchronized (mPackagesLock) {
214 mUsersDir = new File(dataDir, USER_INFO_DIR);
215 mUsersDir.mkdirs();
216 // Make zeroth user directory, for services to migrate their files to that location
217 File userZeroDir = new File(mUsersDir, "0");
218 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 FileUtils.setPermissions(mUsersDir.toString(),
220 FileUtils.S_IRWXU|FileUtils.S_IRWXG
221 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
222 -1, -1);
223 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800224 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700226 sInstance = this;
227 }
228 }
229 }
230
231 void systemReady() {
232 synchronized (mInstallLock) {
233 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700234 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700235 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
236 for (int i = 0; i < mUsers.size(); i++) {
237 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700238 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700239 partials.add(ui);
240 }
241 }
242 for (int i = 0; i < partials.size(); i++) {
243 UserInfo ui = partials.get(i);
244 Slog.w(LOG_TAG, "Removing partially created user #" + i
245 + " (name=" + ui.name + ")");
246 removeUserStateLocked(ui.id);
247 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700249 }
Amith Yamasani06bf8242015-05-08 16:36:21 -0700250 onUserForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400251 mAppOpsService = IAppOpsService.Stub.asInterface(
252 ServiceManager.getService(Context.APP_OPS_SERVICE));
253 for (int i = 0; i < mUserIds.length; ++i) {
254 try {
255 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
256 } catch (RemoteException e) {
257 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
258 }
259 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 }
261
262 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700263 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700264 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700265 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700266 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
267 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 UserInfo ui = mUsers.valueAt(i);
269 if (ui.partial) {
270 continue;
271 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800272 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700274 }
Amith Yamasani13593602012-03-22 16:16:17 -0700275 }
276 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700277 }
Amith Yamasani13593602012-03-22 16:16:17 -0700278 }
279
Amith Yamasani258848d2012-08-10 17:06:33 -0700280 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100281 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800282 if (userId != UserHandle.getCallingUserId()) {
283 checkManageUsersPermission("getting profiles related to user " + userId);
284 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 final long ident = Binder.clearCallingIdentity();
286 try {
287 synchronized (mPackagesLock) {
288 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100289 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 } finally {
291 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000292 }
293 }
294
Amith Yamasanibe465322014-04-24 13:45:17 -0700295 /** Assume permissions already checked and caller's identity cleared */
296 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700297 UserInfo user = getUserInfoLocked(userId);
298 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700299 if (user == null) {
300 // Probably a dying user
301 return users;
302 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700303 for (int i = 0; i < mUsers.size(); i++) {
304 UserInfo profile = mUsers.valueAt(i);
305 if (!isProfileOf(user, profile)) {
306 continue;
307 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100308 if (enabledOnly && !profile.isEnabled()) {
309 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700311 if (mRemovingUserIds.get(profile.id)) {
312 continue;
313 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700314 users.add(profile);
315 }
316 return users;
317 }
318
Jessica Hummelbe81c802014-04-22 15:49:22 +0100319 @Override
320 public UserInfo getProfileParent(int userHandle) {
321 checkManageUsersPermission("get the profile parent");
322 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700323 return getProfileParentLocked(userHandle);
324 }
325 }
326
327 private UserInfo getProfileParentLocked(int userHandle) {
328 UserInfo profile = getUserInfoLocked(userHandle);
329 if (profile == null) {
330 return null;
331 }
332 int parentUserId = profile.profileGroupId;
333 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
334 return null;
335 } else {
336 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100337 }
338 }
339
Kenny Guy2a764942014-04-02 13:29:20 +0100340 private boolean isProfileOf(UserInfo user, UserInfo profile) {
341 return user.id == profile.id ||
342 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
343 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000344 }
345
346 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100347 public void setUserEnabled(int userId) {
348 checkManageUsersPermission("enable user");
349 synchronized (mPackagesLock) {
350 UserInfo info = getUserInfoLocked(userId);
351 if (info != null && !info.isEnabled()) {
352 info.flags ^= UserInfo.FLAG_DISABLED;
353 writeUserLocked(info);
354 }
355 }
356 }
357
358 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700359 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700360 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700361 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700362 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700363 }
364 }
365
Amith Yamasani71e6c692013-03-24 17:39:28 -0700366 @Override
367 public boolean isRestricted() {
368 synchronized (mPackagesLock) {
369 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
370 }
371 }
372
Amith Yamasani195263742012-08-21 15:40:12 -0700373 /*
374 * Should be locked on mUsers before calling this.
375 */
376 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700377 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700378 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800379 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700380 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
381 return null;
382 }
383 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700384 }
385
Amith Yamasani13593602012-03-22 16:16:17 -0700386 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700387 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700388 return ArrayUtils.contains(mUserIds, userId);
389 }
390 }
391
Amith Yamasani258848d2012-08-10 17:06:33 -0700392 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700393 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700394 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700395 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700396 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700397 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700398 if (info == null || info.partial) {
399 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
400 return;
401 }
Amith Yamasani13593602012-03-22 16:16:17 -0700402 if (name != null && !name.equals(info.name)) {
403 info.name = name;
404 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700405 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700406 }
407 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700408 if (changed) {
409 sendUserInfoChangedBroadcast(userId);
410 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700411 }
412
Amith Yamasani258848d2012-08-10 17:06:33 -0700413 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700414 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700415 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400416 long ident = Binder.clearCallingIdentity();
417 try {
418 synchronized (mPackagesLock) {
419 UserInfo info = mUsers.get(userId);
420 if (info == null || info.partial) {
421 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
422 return;
423 }
424 writeBitmapLocked(info, bitmap);
425 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700426 }
Jason Monk9a944532014-07-08 09:31:21 -0400427 sendUserInfoChangedBroadcast(userId);
428 } finally {
429 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700430 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700431 }
432
433 private void sendUserInfoChangedBroadcast(int userId) {
434 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
435 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
436 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700437 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700438 }
439
Amith Yamasani258848d2012-08-10 17:06:33 -0700440 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100441 public ParcelFileDescriptor getUserIcon(int userId) {
442 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700443 synchronized (mPackagesLock) {
444 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 if (info == null || info.partial) {
446 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
447 return null;
448 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100449 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
450 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
451 || callingGroupId != info.profileGroupId) {
452 checkManageUsersPermission("get the icon of a user who is not related");
453 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700454 if (info.iconPath == null) {
455 return null;
456 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100457 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700458 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100459
460 try {
461 return ParcelFileDescriptor.open(
462 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
463 } catch (FileNotFoundException e) {
464 Log.e(LOG_TAG, "Couldn't find icon file", e);
465 }
466 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700467 }
468
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700469 public void makeInitialized(int userId) {
470 checkManageUsersPermission("makeInitialized");
471 synchronized (mPackagesLock) {
472 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700473 if (info == null || info.partial) {
474 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
475 }
476 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700477 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800478 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700479 }
480 }
481 }
482
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700483 /**
484 * If default guest restrictions haven't been initialized yet, add the basic
485 * restrictions.
486 */
487 private void initDefaultGuestRestrictions() {
488 if (mGuestRestrictions.isEmpty()) {
489 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800490 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700491 }
492 }
493
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800494 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530495 public Bundle getDefaultGuestRestrictions() {
496 checkManageUsersPermission("getDefaultGuestRestrictions");
497 synchronized (mPackagesLock) {
498 return new Bundle(mGuestRestrictions);
499 }
500 }
501
502 @Override
503 public void setDefaultGuestRestrictions(Bundle restrictions) {
504 checkManageUsersPermission("setDefaultGuestRestrictions");
505 synchronized (mPackagesLock) {
506 mGuestRestrictions.clear();
507 mGuestRestrictions.putAll(restrictions);
508 writeUserListLocked();
509 }
510 }
511
512 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700513 public boolean hasUserRestriction(String restrictionKey, int userId) {
514 synchronized (mPackagesLock) {
515 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700516 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700517 }
518 }
519
520 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800521 public Bundle getUserRestrictions(int userId) {
522 // checkManageUsersPermission("getUserRestrictions");
523
524 synchronized (mPackagesLock) {
525 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700526 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800527 }
528 }
529
530 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700531 public void setUserRestriction(String key, boolean value, int userId) {
532 synchronized (mPackagesLock) {
533 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
534 Bundle restrictions = getUserRestrictions(userId);
535 restrictions.putBoolean(key, value);
536 setUserRestrictionsInternalLocked(restrictions, userId);
537 }
538 }
539 }
540
541 @Override
542 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
543 checkSystemOrRoot("setSystemControlledUserRestriction");
544 synchronized (mPackagesLock) {
545 Bundle restrictions = getUserRestrictions(userId);
546 restrictions.putBoolean(key, value);
547 setUserRestrictionsInternalLocked(restrictions, userId);
548 }
549 }
550
551 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800552 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700553 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700554 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800555
556 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700557 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
558 // Restore the original state of system controlled restrictions from oldUserRestrictions
559 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
560 restrictions.remove(key);
561 if (oldUserRestrictions.containsKey(key)) {
562 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
563 }
Jason Monk62062992014-05-06 09:55:28 -0400564 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700565 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800566 }
567 }
568
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700569 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
570 final Bundle userRestrictions = mUserRestrictions.get(userId);
571 userRestrictions.clear();
572 userRestrictions.putAll(restrictions);
573 long token = Binder.clearCallingIdentity();
574 try {
575 mAppOpsService.setUserRestrictions(userRestrictions, userId);
576 } catch (RemoteException e) {
577 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
578 } finally {
579 Binder.restoreCallingIdentity(token);
580 }
581 scheduleWriteUserLocked(mUsers.get(userId));
582 }
583
Amith Yamasani258848d2012-08-10 17:06:33 -0700584 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700585 * Check if we've hit the limit of how many users can be created.
586 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700587 private boolean isUserLimitReachedLocked() {
Nicolas Prevot72434b72015-05-13 12:15:03 -0700588 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
589 }
590
591 @Override
592 public boolean canAddMoreManagedProfiles() {
593 checkManageUsersPermission("check if more managed profiles can be added.");
594 if (ActivityManager.isLowRamDeviceStatic()) {
595 return false;
596 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700597 if (!mContext.getPackageManager().hasSystemFeature(
598 PackageManager.FEATURE_MANAGED_USERS)) {
599 return false;
600 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700601 synchronized(mPackagesLock) {
602 // Limit number of managed profiles that can be created
603 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
604 >= MAX_MANAGED_PROFILES) {
605 return false;
606 }
607 int usersCount = getAliveUsersExcludingGuestsCountLocked();
608 // We allow creating a managed profile in the special case where there is only one user.
609 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
610 }
611 }
612
613 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700614 int aliveUserCount = 0;
615 final int totalUserCount = mUsers.size();
616 // Skip over users being removed
617 for (int i = 0; i < totalUserCount; i++) {
618 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700619 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700620 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700621 aliveUserCount++;
622 }
623 }
Nicolas Prevot72434b72015-05-13 12:15:03 -0700624 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700625 }
626
627 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700628 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700629 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700630 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700631 *
632 * @param message used as message if SecurityException is thrown
633 * @throws SecurityException if the caller is not system or root
634 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700635 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700636 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700637 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400638 && ActivityManager.checkComponentPermission(
639 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700640 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
641 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
642 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400643 }
644
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700645 private static void checkSystemOrRoot(String message) {
646 final int uid = Binder.getCallingUid();
647 if (uid != Process.SYSTEM_UID && uid != 0) {
648 throw new SecurityException("Only system may call: " + message);
649 }
650 }
651
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700652 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700653 try {
654 File dir = new File(mUsersDir, Integer.toString(info.id));
655 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100656 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700657 if (!dir.exists()) {
658 dir.mkdir();
659 FileUtils.setPermissions(
660 dir.getPath(),
661 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
662 -1, -1);
663 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700664 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100665 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
666 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700667 info.iconPath = file.getAbsolutePath();
668 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700669 try {
670 os.close();
671 } catch (IOException ioe) {
672 // What the ... !
673 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100674 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700675 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700676 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700677 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700678 }
679
Amith Yamasani0b285492011-04-14 17:35:23 -0700680 /**
681 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
682 * cache it elsewhere.
683 * @return the array of user ids.
684 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700685 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700686 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700687 return mUserIds;
688 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700689 }
690
Dianne Hackborn4428e172012-08-24 17:43:05 -0700691 int[] getUserIdsLPr() {
692 return mUserIds;
693 }
694
Amith Yamasani13593602012-03-22 16:16:17 -0700695 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700697 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 return;
699 }
700 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700701 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700702 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700703 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700704 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100705 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700706 int type;
707 while ((type = parser.next()) != XmlPullParser.START_TAG
708 && type != XmlPullParser.END_DOCUMENT) {
709 ;
710 }
711
712 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700713 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700714 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700715 return;
716 }
717
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 mNextSerialNumber = -1;
719 if (parser.getName().equals(TAG_USERS)) {
720 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
721 if (lastSerialNumber != null) {
722 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
723 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700724 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
725 if (versionNumber != null) {
726 mUserVersion = Integer.parseInt(versionNumber);
727 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700728 }
729
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530731 if (type == XmlPullParser.START_TAG) {
732 final String name = parser.getName();
733 if (name.equals(TAG_USER)) {
734 String id = parser.getAttributeValue(null, ATTR_ID);
735 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700736
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530737 if (user != null) {
738 mUsers.put(user.id, user);
739 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
740 mNextSerialNumber = user.id + 1;
741 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700742 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530743 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800744 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
745 && type != XmlPullParser.END_TAG) {
746 if (type == XmlPullParser.START_TAG) {
747 if (parser.getName().equals(TAG_RESTRICTIONS)) {
748 readRestrictionsLocked(parser, mGuestRestrictions);
749 }
750 break;
751 }
752 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700753 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700754 }
755 }
Amith Yamasani13593602012-03-22 16:16:17 -0700756 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700757 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700759 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700760 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700761 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800762 } finally {
763 if (fis != null) {
764 try {
765 fis.close();
766 } catch (IOException e) {
767 }
768 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700769 }
770 }
771
Amith Yamasani6f34b412012-10-22 18:19:27 -0700772 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800773 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700774 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700775 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700776 int userVersion = mUserVersion;
777 if (userVersion < 1) {
778 // Assign a proper name for the owner, if not initialized correctly before
779 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
780 if ("Primary".equals(user.name)) {
781 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800782 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700783 }
784 userVersion = 1;
785 }
786
Amith Yamasanibc9625052012-11-15 14:39:18 -0800787 if (userVersion < 2) {
788 // Owner should be marked as initialized
789 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
790 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
791 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800792 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800793 }
794 userVersion = 2;
795 }
796
Amith Yamasani350962c2013-08-06 11:18:53 -0700797
Amith Yamasani5e486f52013-08-07 11:06:44 -0700798 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700799 userVersion = 4;
800 }
801
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700802 if (userVersion < 5) {
803 initDefaultGuestRestrictions();
804 userVersion = 5;
805 }
806
Amith Yamasani6f34b412012-10-22 18:19:27 -0700807 if (userVersion < USER_VERSION) {
808 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
809 + USER_VERSION);
810 } else {
811 mUserVersion = userVersion;
812 writeUserListLocked();
813 }
814 }
815
Amith Yamasani13593602012-03-22 16:16:17 -0700816 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800818 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700819 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700820 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700821 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700822 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400823 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800824
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500825 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800826 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
827
Amith Yamasani13593602012-03-22 16:16:17 -0700828 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700829 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700830
Amith Yamasani13593602012-03-22 16:16:17 -0700831 writeUserListLocked();
832 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 }
834
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800835 private void scheduleWriteUserLocked(UserInfo userInfo) {
836 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
837 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
838 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
839 }
840 }
841
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700842 /*
843 * Writes the user file in this format:
844 *
845 * <user flags="20039023" id="0">
846 * <name>Primary</name>
847 * </user>
848 */
Amith Yamasani13593602012-03-22 16:16:17 -0700849 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700850 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700851 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700853 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 final BufferedOutputStream bos = new BufferedOutputStream(fos);
855
856 // XmlSerializer serializer = XmlUtils.serializerInstance();
857 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100858 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700859 serializer.startDocument(null, true);
860 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
861
862 serializer.startTag(null, TAG_USER);
863 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700864 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700866 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
867 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
868 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700869 if (userInfo.iconPath != null) {
870 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
871 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700872 if (userInfo.partial) {
873 serializer.attribute(null, ATTR_PARTIAL, "true");
874 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700875 if (userInfo.guestToRemove) {
876 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
877 }
Kenny Guy2a764942014-04-02 13:29:20 +0100878 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
879 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
880 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000881 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700882
883 serializer.startTag(null, TAG_NAME);
884 serializer.text(userInfo.name);
885 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800886 Bundle restrictions = mUserRestrictions.get(userInfo.id);
887 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530888 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800889 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700890 serializer.endTag(null, TAG_USER);
891
892 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700893 userFile.finishWrite(fos);
894 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700895 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700896 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700897 }
898 }
899
900 /*
901 * Writes the user list file in this format:
902 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700903 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700904 * <user id="0"></user>
905 * <user id="2"></user>
906 * </users>
907 */
Amith Yamasani13593602012-03-22 16:16:17 -0700908 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700909 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700910 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700912 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913 final BufferedOutputStream bos = new BufferedOutputStream(fos);
914
915 // XmlSerializer serializer = XmlUtils.serializerInstance();
916 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100917 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918 serializer.startDocument(null, true);
919 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
920
921 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700922 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700923 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700924
Adam Lesinskieddeb492014-09-08 17:50:03 -0700925 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530926 writeRestrictionsLocked(serializer, mGuestRestrictions);
927 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 for (int i = 0; i < mUsers.size(); i++) {
929 UserInfo user = mUsers.valueAt(i);
930 serializer.startTag(null, TAG_USER);
931 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
932 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700933 }
934
935 serializer.endTag(null, TAG_USERS);
936
937 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700938 userListFile.finishWrite(fos);
939 } catch (Exception e) {
940 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700941 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700942 }
943 }
944
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530945 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
946 throws IOException {
947 serializer.startTag(null, TAG_RESTRICTIONS);
948 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
949 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
950 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
951 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
952 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
953 writeBoolean(serializer, restrictions,
954 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
955 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
956 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
957 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
958 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
959 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
960 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
961 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -0700962 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530963 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
964 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
965 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
966 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
967 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
968 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
969 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
970 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
971 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700972 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
973 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -0700974 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -0400975 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700976 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
977 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000978 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +0000979 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -0700980 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530981 serializer.endTag(null, TAG_RESTRICTIONS);
982 }
983
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800984 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700985 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700986 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700987 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700988 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700989 long creationTime = 0L;
990 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +0100991 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700992 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700993 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800994 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995
996 FileInputStream fis = null;
997 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700998 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700999 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001000 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001001 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001002 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001003 int type;
1004 while ((type = parser.next()) != XmlPullParser.START_TAG
1005 && type != XmlPullParser.END_DOCUMENT) {
1006 ;
1007 }
1008
1009 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001010 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001011 return null;
1012 }
1013
1014 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001015 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1016 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001017 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018 return null;
1019 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001020 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1021 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001022 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001023 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1024 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001025 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1026 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001027 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1028 if ("true".equals(valueString)) {
1029 partial = true;
1030 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001031 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1032 if ("true".equals(valueString)) {
1033 guestToRemove = true;
1034 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001035
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001036 int outerDepth = parser.getDepth();
1037 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1038 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1039 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1040 continue;
1041 }
1042 String tag = parser.getName();
1043 if (TAG_NAME.equals(tag)) {
1044 type = parser.next();
1045 if (type == XmlPullParser.TEXT) {
1046 name = parser.getText();
1047 }
1048 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301049 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001050 }
1051 }
1052 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001053
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001054 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001055 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001056 userInfo.creationTime = creationTime;
1057 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001058 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001059 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001060 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001061 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001062 return userInfo;
1063
1064 } catch (IOException ioe) {
1065 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001066 } finally {
1067 if (fis != null) {
1068 try {
1069 fis.close();
1070 } catch (IOException e) {
1071 }
1072 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001073 }
1074 return null;
1075 }
1076
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301077 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1078 throws IOException {
1079 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1080 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1081 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1082 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1083 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1084 readBoolean(parser, restrictions,
1085 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1086 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1087 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1088 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1089 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1090 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1091 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1092 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scotte3e314d2015-04-20 14:07:45 -07001093 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301094 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1095 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1096 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1097 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1098 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1099 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1100 readBoolean(parser, restrictions,
1101 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1102 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1103 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001104 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1105 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001106 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001107 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001108 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1109 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001110 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001111 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001112 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301113 }
1114
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001115 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1116 String restrictionKey) {
1117 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001118 if (value != null) {
1119 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1120 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001121 }
1122
1123 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1124 throws IOException {
1125 if (restrictions.containsKey(restrictionKey)) {
1126 xml.attribute(null, restrictionKey,
1127 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1128 }
1129 }
1130
Amith Yamasani920ace02012-09-20 22:15:37 -07001131 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1132 String valueString = parser.getAttributeValue(null, attr);
1133 if (valueString == null) return defaultValue;
1134 try {
1135 return Integer.parseInt(valueString);
1136 } catch (NumberFormatException nfe) {
1137 return defaultValue;
1138 }
1139 }
1140
1141 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1142 String valueString = parser.getAttributeValue(null, attr);
1143 if (valueString == null) return defaultValue;
1144 try {
1145 return Long.parseLong(valueString);
1146 } catch (NumberFormatException nfe) {
1147 return defaultValue;
1148 }
1149 }
1150
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001151 private boolean isPackageInstalled(String pkg, int userId) {
1152 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1153 PackageManager.GET_UNINSTALLED_PACKAGES,
1154 userId);
1155 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1156 return false;
1157 }
1158 return true;
1159 }
1160
Amith Yamasanib82add22013-07-09 11:24:44 -07001161 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001162 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001163 * Does not do any permissions checking.
1164 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001165 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001166 synchronized (mPackagesLock) {
1167 File dir = Environment.getUserSystemDirectory(userId);
1168 String[] files = dir.list();
1169 if (files == null) return;
1170 for (String fileName : files) {
1171 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1172 File resFile = new File(dir, fileName);
1173 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001174 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001175 }
1176 }
1177 }
1178 }
1179 }
1180
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001181 /**
1182 * Removes the app restrictions file for a specific package and user id, if it exists.
1183 */
1184 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1185 synchronized (mPackagesLock) {
1186 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001187 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001188 if (resFile.exists()) {
1189 resFile.delete();
1190 }
1191 }
1192 }
1193
Kenny Guya52dc3e2014-02-11 15:33:14 +00001194 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001195 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001196 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001197 if (userId != UserHandle.USER_OWNER) {
1198 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001199 return null;
1200 }
Kenny Guy2a764942014-04-02 13:29:20 +01001201 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001202 }
1203
Amith Yamasani258848d2012-08-10 17:06:33 -07001204 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001205 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001206 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001207 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001208 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001209
Jessica Hummelbe81c802014-04-22 15:49:22 +01001210 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001211 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1212 UserManager.DISALLOW_ADD_USER, false)) {
1213 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1214 return null;
1215 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001216 if (ActivityManager.isLowRamDeviceStatic()) {
1217 return null;
1218 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001219 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot72434b72015-05-13 12:15:03 -07001220 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001221 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001222 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001223 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001224 try {
1225 synchronized (mInstallLock) {
1226 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001227 UserInfo parent = null;
1228 if (parentId != UserHandle.USER_NULL) {
1229 parent = getUserInfoLocked(parentId);
1230 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001231 }
Nicolas Prevot72434b72015-05-13 12:15:03 -07001232 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1233 return null;
1234 }
1235 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1236 // If we're not adding a guest user or a managed profile and the limit has
1237 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001238 return null;
1239 }
1240 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001241 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001242 return null;
1243 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001244 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001245 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001246 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001247 long now = System.currentTimeMillis();
1248 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001249 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001250 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001251 mUsers.put(userId, userInfo);
1252 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001253 if (parent != null) {
1254 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1255 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001256 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001257 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001258 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001259 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001260 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1261 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1262 final String volumeUuid = vol.getFsUuid();
1263 try {
1264 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1265 userId);
1266 prepareUserDirectory(userDir);
1267 enforceSerialNumber(userDir, userInfo.serialNumber);
1268 } catch (IOException e) {
1269 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1270 }
1271 }
1272 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001273 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001274 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001275 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001276 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001277 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001278 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001279 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001280 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001281 if (userInfo != null) {
1282 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1283 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1284 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1285 android.Manifest.permission.MANAGE_USERS);
1286 }
1287 } finally {
1288 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001289 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001290 return userInfo;
1291 }
1292
Amith Yamasani95ab7842014-08-11 17:09:26 -07001293 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1294 int count = 0;
1295 for (int i = mUsers.size() - 1; i >= 0; i--) {
1296 UserInfo user = mUsers.valueAt(i);
1297 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1298 if ((user.flags & flags) != 0) {
1299 count++;
1300 }
1301 }
1302 }
1303 return count;
1304 }
1305
Amith Yamasani0b285492011-04-14 17:35:23 -07001306 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001307 * Find the current guest user. If the Guest user is partial,
1308 * then do not include it in the results as it is about to die.
1309 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1310 * the special handling of Guests being removed.
1311 */
1312 private UserInfo findCurrentGuestUserLocked() {
1313 final int size = mUsers.size();
1314 for (int i = 0; i < size; i++) {
1315 final UserInfo user = mUsers.valueAt(i);
1316 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1317 return user;
1318 }
1319 }
1320 return null;
1321 }
1322
1323 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001324 * Mark this guest user for deletion to allow us to create another guest
1325 * and switch to that user before actually removing this guest.
1326 * @param userHandle the userid of the current guest
1327 * @return whether the user could be marked for deletion
1328 */
1329 public boolean markGuestForDeletion(int userHandle) {
1330 checkManageUsersPermission("Only the system can remove users");
1331 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1332 UserManager.DISALLOW_REMOVE_USER, false)) {
1333 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1334 return false;
1335 }
1336
1337 long ident = Binder.clearCallingIdentity();
1338 try {
1339 final UserInfo user;
1340 synchronized (mPackagesLock) {
1341 user = mUsers.get(userHandle);
1342 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1343 return false;
1344 }
1345 if (!user.isGuest()) {
1346 return false;
1347 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001348 // We set this to a guest user that is to be removed. This is a temporary state
1349 // where we are allowed to add new Guest users, even if this one is still not
1350 // removed. This user will still show up in getUserInfo() calls.
1351 // If we don't get around to removing this Guest user, it will be purged on next
1352 // startup.
1353 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001354 // Mark it as disabled, so that it isn't returned any more when
1355 // profiles are queried.
1356 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001357 writeUserLocked(user);
1358 }
1359 } finally {
1360 Binder.restoreCallingIdentity(ident);
1361 }
1362 return true;
1363 }
1364
1365 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001366 * Removes a user and all data directories created for that user. This method should be called
1367 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001368 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001369 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001370 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001371 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001372 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1373 UserManager.DISALLOW_REMOVE_USER, false)) {
1374 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1375 return false;
1376 }
1377
Kenny Guyee58b4f2014-05-23 15:19:53 +01001378 long ident = Binder.clearCallingIdentity();
1379 try {
1380 final UserInfo user;
1381 synchronized (mPackagesLock) {
1382 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001383 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001384 return false;
1385 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001386
1387 // We remember deleted user IDs to prevent them from being
1388 // reused during the current boot; they can still be reused
1389 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001390 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001391
Kenny Guyee58b4f2014-05-23 15:19:53 +01001392 try {
1393 mAppOpsService.removeUser(userHandle);
1394 } catch (RemoteException e) {
1395 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1396 }
1397 // Set this to a partially created user, so that the user will be purged
1398 // on next startup, in case the runtime stops now before stopping and
1399 // removing the user completely.
1400 user.partial = true;
1401 // Mark it as disabled, so that it isn't returned any more when
1402 // profiles are queried.
1403 user.flags |= UserInfo.FLAG_DISABLED;
1404 writeUserLocked(user);
1405 }
1406
1407 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1408 && user.isManagedProfile()) {
1409 // Send broadcast to notify system that the user removed was a
1410 // managed user.
1411 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1412 }
1413
1414 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1415 int res;
1416 try {
1417 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1418 new IStopUserCallback.Stub() {
1419 @Override
1420 public void userStopped(int userId) {
1421 finishRemoveUser(userId);
1422 }
1423 @Override
1424 public void userStopAborted(int userId) {
1425 }
1426 });
1427 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001428 return false;
1429 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001430 return res == ActivityManager.USER_OP_SUCCESS;
1431 } finally {
1432 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001433 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001434 }
1435
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001436 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001437 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001438 // Let other services shutdown any activity and clean up their state before completely
1439 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001440 long ident = Binder.clearCallingIdentity();
1441 try {
1442 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1443 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001444 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1445 android.Manifest.permission.MANAGE_USERS,
1446
1447 new BroadcastReceiver() {
1448 @Override
1449 public void onReceive(Context context, Intent intent) {
1450 if (DBG) {
1451 Slog.i(LOG_TAG,
1452 "USER_REMOVED broadcast sent, cleaning up user data "
1453 + userHandle);
1454 }
1455 new Thread() {
1456 public void run() {
1457 synchronized (mInstallLock) {
1458 synchronized (mPackagesLock) {
1459 removeUserStateLocked(userHandle);
1460 }
1461 }
1462 }
1463 }.start();
1464 }
1465 },
1466
1467 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001468 } finally {
1469 Binder.restoreCallingIdentity(ident);
1470 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001471 }
1472
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001473 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001474 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001475 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001476
1477 // Remove this user from the list
1478 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001479 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001480 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001481 userFile.delete();
1482 // Update the user list
1483 writeUserListLocked();
1484 updateUserIdsLocked();
1485 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1486 }
1487
Amith Yamasani61f57372012-08-31 12:12:28 -07001488 private void removeDirectoryRecursive(File parent) {
1489 if (parent.isDirectory()) {
1490 String[] files = parent.list();
1491 for (String filename : files) {
1492 File child = new File(parent, filename);
1493 removeDirectoryRecursive(child);
1494 }
1495 }
1496 parent.delete();
1497 }
1498
Kenny Guyf8d3a232014-05-15 16:09:52 +01001499 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001500 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001501 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1502 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001503 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1504 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001505 }
1506
Amith Yamasani2a003292012-08-14 18:25:45 -07001507 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001508 public Bundle getApplicationRestrictions(String packageName) {
1509 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1510 }
1511
1512 @Override
1513 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001514 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001515 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001516 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001517 }
1518 synchronized (mPackagesLock) {
1519 // Read the restrictions from XML
1520 return readApplicationRestrictionsLocked(packageName, userId);
1521 }
1522 }
1523
1524 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001525 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001526 int userId) {
1527 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001528 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001529 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001530 }
1531 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001532 if (restrictions == null || restrictions.isEmpty()) {
1533 cleanAppRestrictionsForPackage(packageName, userId);
1534 } else {
1535 // Write the restrictions to XML
1536 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1537 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 }
Robin Lee66e5d962014-04-09 16:44:21 +01001539
Kenny Guyd21b2182014-07-17 16:38:55 +01001540 if (isPackageInstalled(packageName, userId)) {
1541 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1542 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1543 changeIntent.setPackage(packageName);
1544 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1545 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1546 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001547 }
1548
Amith Yamasani655d0e22013-06-12 14:19:10 -07001549 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001550 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001551 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001552 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001553 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001554 }
1555
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001556 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001557 synchronized (mPackagesLock) {
1558 // Remove all user restrictions
1559 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001560 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001561 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001562 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001563 if (unhideApps) {
1564 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001565 }
1566 }
1567
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001568 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001569 mHandler.post(new Runnable() {
1570 @Override
1571 public void run() {
1572 List<ApplicationInfo> apps =
1573 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1574 userHandle).getList();
1575 final long ident = Binder.clearCallingIdentity();
1576 try {
1577 for (ApplicationInfo appInfo : apps) {
1578 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001579 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1580 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001581 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001582 userHandle);
1583 }
1584 }
1585 } finally {
1586 Binder.restoreCallingIdentity(ident);
1587 }
1588 }
1589 });
1590 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001591 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001592 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001593 try {
1594 return mContext.getPackageManager().getApplicationInfo(packageName,
1595 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1596 } catch (NameNotFoundException nnfe) {
1597 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001598 } finally {
1599 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001600 }
1601 }
1602
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001603 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001604 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001605 AtomicFile restrictionsFile =
1606 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1607 packageToRestrictionsFileName(packageName)));
1608 return readApplicationRestrictionsLocked(restrictionsFile);
1609 }
1610
1611 @VisibleForTesting
1612 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001613 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001614 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001615 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001616 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001617 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001618
1619 FileInputStream fis = null;
1620 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001621 fis = restrictionsFile.openRead();
1622 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001623 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001624 XmlUtils.nextElement(parser);
1625 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001626 Slog.e(LOG_TAG, "Unable to read restrictions file "
1627 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001628 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001629 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001630 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1631 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001632 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001633 } catch (IOException|XmlPullParserException e) {
1634 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001635 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001636 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001637 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001638 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001639 }
1640
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001641 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1642 XmlPullParser parser) throws XmlPullParserException, IOException {
1643 int type = parser.getEventType();
1644 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1645 String key = parser.getAttributeValue(null, ATTR_KEY);
1646 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1647 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1648 if (multiple != null) {
1649 values.clear();
1650 int count = Integer.parseInt(multiple);
1651 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1652 if (type == XmlPullParser.START_TAG
1653 && parser.getName().equals(TAG_VALUE)) {
1654 values.add(parser.nextText().trim());
1655 count--;
1656 }
1657 }
1658 String [] valueStrings = new String[values.size()];
1659 values.toArray(valueStrings);
1660 restrictions.putStringArray(key, valueStrings);
1661 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1662 restrictions.putBundle(key, readBundleEntry(parser, values));
1663 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1664 final int outerDepth = parser.getDepth();
1665 ArrayList<Bundle> bundleList = new ArrayList<>();
1666 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1667 Bundle childBundle = readBundleEntry(parser, values);
1668 bundleList.add(childBundle);
1669 }
1670 restrictions.putParcelableArray(key,
1671 bundleList.toArray(new Bundle[bundleList.size()]));
1672 } else {
1673 String value = parser.nextText().trim();
1674 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1675 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1676 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1677 restrictions.putInt(key, Integer.parseInt(value));
1678 } else {
1679 restrictions.putString(key, value);
1680 }
1681 }
1682 }
1683 }
1684
1685 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1686 throws IOException, XmlPullParserException {
1687 Bundle childBundle = new Bundle();
1688 final int outerDepth = parser.getDepth();
1689 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1690 readEntry(childBundle, values, parser);
1691 }
1692 return childBundle;
1693 }
1694
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001696 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001697 AtomicFile restrictionsFile = new AtomicFile(
1698 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001699 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001700 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1701 }
1702
1703 @VisibleForTesting
1704 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1705 AtomicFile restrictionsFile) {
1706 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 try {
1708 fos = restrictionsFile.startWrite();
1709 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1710
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001711 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001712 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 serializer.startDocument(null, true);
1714 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1715
1716 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001717 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001718 serializer.endTag(null, TAG_RESTRICTIONS);
1719
1720 serializer.endDocument();
1721 restrictionsFile.finishWrite(fos);
1722 } catch (Exception e) {
1723 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001724 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1725 }
1726 }
1727
1728 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1729 throws IOException {
1730 for (String key : restrictions.keySet()) {
1731 Object value = restrictions.get(key);
1732 serializer.startTag(null, TAG_ENTRY);
1733 serializer.attribute(null, ATTR_KEY, key);
1734
1735 if (value instanceof Boolean) {
1736 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1737 serializer.text(value.toString());
1738 } else if (value instanceof Integer) {
1739 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1740 serializer.text(value.toString());
1741 } else if (value == null || value instanceof String) {
1742 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1743 serializer.text(value != null ? (String) value : "");
1744 } else if (value instanceof Bundle) {
1745 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1746 writeBundle((Bundle) value, serializer);
1747 } else if (value instanceof Parcelable[]) {
1748 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1749 Parcelable[] array = (Parcelable[]) value;
1750 for (Parcelable parcelable : array) {
1751 if (!(parcelable instanceof Bundle)) {
1752 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1753 }
1754 serializer.startTag(null, TAG_ENTRY);
1755 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1756 writeBundle((Bundle) parcelable, serializer);
1757 serializer.endTag(null, TAG_ENTRY);
1758 }
1759 } else {
1760 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1761 String[] values = (String[]) value;
1762 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1763 for (String choice : values) {
1764 serializer.startTag(null, TAG_VALUE);
1765 serializer.text(choice != null ? choice : "");
1766 serializer.endTag(null, TAG_VALUE);
1767 }
1768 }
1769 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001770 }
1771 }
1772
1773 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001774 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001775 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001776 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001777 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001778 }
1779 }
1780
1781 @Override
1782 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001783 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001784 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001785 UserInfo info = getUserInfoLocked(userId);
1786 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001787 }
1788 // Not found
1789 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001790 }
1791 }
1792
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001793 @Override
1794 public long getUserCreationTime(int userHandle) {
1795 int callingUserId = UserHandle.getCallingUserId();
1796 UserInfo userInfo = null;
1797 synchronized (mPackagesLock) {
1798 if (callingUserId == userHandle) {
1799 userInfo = getUserInfoLocked(userHandle);
1800 } else {
1801 UserInfo parent = getProfileParentLocked(userHandle);
1802 if (parent != null && parent.id == callingUserId) {
1803 userInfo = getUserInfoLocked(userHandle);
1804 }
1805 }
1806 }
1807 if (userInfo == null) {
1808 throw new SecurityException("userHandle can only be the calling user or a managed "
1809 + "profile associated with this user");
1810 }
1811 return userInfo.creationTime;
1812 }
1813
Amith Yamasani0b285492011-04-14 17:35:23 -07001814 /**
1815 * Caches the list of user ids in an array, adjusting the array size when necessary.
1816 */
Amith Yamasani13593602012-03-22 16:16:17 -07001817 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001818 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001819 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001820 if (!mUsers.valueAt(i).partial) {
1821 num++;
1822 }
1823 }
Amith Yamasani16389312012-10-17 21:20:14 -07001824 final int[] newUsers = new int[num];
1825 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001826 for (int i = 0; i < mUsers.size(); i++) {
1827 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001828 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001829 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001830 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001831 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001832 }
1833
1834 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001835 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001836 * @param userId the user that was just foregrounded
1837 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001838 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001839 synchronized (mPackagesLock) {
1840 UserInfo user = mUsers.get(userId);
1841 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001842 if (user == null || user.partial) {
1843 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1844 return;
1845 }
1846 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001847 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001848 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001849 }
1850 }
1851 }
1852
1853 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001854 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001855 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1856 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001857 * @return
1858 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001859 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001860 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001861 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001862 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001863 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001864 break;
1865 }
1866 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001867 }
Amith Yamasani195263742012-08-21 15:40:12 -07001868 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001870 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001871
Amith Yamasanifc95e702013-09-26 13:20:17 -07001872 private String packageToRestrictionsFileName(String packageName) {
1873 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1874 }
1875
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001876 /**
1877 * Create new {@code /data/user/[id]} directory and sets default
1878 * permissions.
1879 */
1880 public static void prepareUserDirectory(File file) throws IOException {
1881 if (!file.exists()) {
1882 if (!file.mkdir()) {
1883 throw new IOException("Failed to create " + file);
1884 }
1885 }
1886 if (FileUtils.setPermissions(file.getAbsolutePath(), 0771, Process.SYSTEM_UID,
1887 Process.SYSTEM_UID) != 0) {
1888 throw new IOException("Failed to prepare " + file);
1889 }
1890 }
1891
1892 /**
1893 * Enforce that serial number stored in user directory inode matches the
1894 * given expected value. Gracefully sets the serial number if currently
1895 * undefined.
1896 *
1897 * @throws IOException when problem extracting serial number, or serial
1898 * number is mismatched.
1899 */
1900 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1901 final int foundSerial = getSerialNumber(file);
1902 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1903
1904 if (foundSerial == -1) {
1905 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1906 try {
1907 setSerialNumber(file, serialNumber);
1908 } catch (IOException e) {
1909 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1910 }
1911
1912 } else if (foundSerial != serialNumber) {
1913 throw new IOException("Found serial number " + foundSerial
1914 + " doesn't match expected " + serialNumber);
1915 }
1916 }
1917
1918 /**
1919 * Set serial number stored in user directory inode.
1920 *
1921 * @throws IOException if serial number was already set
1922 */
1923 private static void setSerialNumber(File file, int serialNumber)
1924 throws IOException {
1925 try {
1926 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1927 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1928 } catch (ErrnoException e) {
1929 throw e.rethrowAsIOException();
1930 }
1931 }
1932
1933 /**
1934 * Return serial number stored in user directory inode.
1935 *
1936 * @return parsed serial number, or -1 if not set
1937 */
1938 private static int getSerialNumber(File file) throws IOException {
1939 try {
1940 final byte[] buf = new byte[256];
1941 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1942 final String serial = new String(buf, 0, len);
1943 try {
1944 return Integer.parseInt(serial);
1945 } catch (NumberFormatException e) {
1946 throw new IOException("Bad serial number: " + serial);
1947 }
1948 } catch (ErrnoException e) {
1949 if (e.errno == OsConstants.ENODATA) {
1950 return -1;
1951 } else {
1952 throw e.rethrowAsIOException();
1953 }
1954 }
1955 }
1956
Amith Yamasani920ace02012-09-20 22:15:37 -07001957 @Override
1958 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1959 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1960 != PackageManager.PERMISSION_GRANTED) {
1961 pw.println("Permission Denial: can't dump UserManager from from pid="
1962 + Binder.getCallingPid()
1963 + ", uid=" + Binder.getCallingUid()
1964 + " without permission "
1965 + android.Manifest.permission.DUMP);
1966 return;
1967 }
1968
1969 long now = System.currentTimeMillis();
1970 StringBuilder sb = new StringBuilder();
1971 synchronized (mPackagesLock) {
1972 pw.println("Users:");
1973 for (int i = 0; i < mUsers.size(); i++) {
1974 UserInfo user = mUsers.valueAt(i);
1975 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001976 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001977 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001978 if (user.partial) pw.print(" <partial>");
1979 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001980 pw.print(" Created: ");
1981 if (user.creationTime == 0) {
1982 pw.println("<unknown>");
1983 } else {
1984 sb.setLength(0);
1985 TimeUtils.formatDuration(now - user.creationTime, sb);
1986 sb.append(" ago");
1987 pw.println(sb);
1988 }
1989 pw.print(" Last logged in: ");
1990 if (user.lastLoggedInTime == 0) {
1991 pw.println("<unknown>");
1992 } else {
1993 sb.setLength(0);
1994 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1995 sb.append(" ago");
1996 pw.println(sb);
1997 }
1998 }
1999 }
2000 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002001
2002 final class MainHandler extends Handler {
2003
2004 @Override
2005 public void handleMessage(Message msg) {
2006 switch (msg.what) {
2007 case WRITE_USER_MSG:
2008 removeMessages(WRITE_USER_MSG, msg.obj);
2009 synchronized (mPackagesLock) {
2010 int userId = ((UserInfo) msg.obj).id;
2011 UserInfo userInfo = mUsers.get(userId);
2012 if (userInfo != null) {
2013 writeUserLocked(userInfo);
2014 }
2015 }
2016 }
2017 }
2018 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002019
2020 /**
2021 * @param userId
2022 * @return whether the user has been initialized yet
2023 */
2024 boolean isInitialized(int userId) {
2025 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2026 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027}