blob: 4dd73889a6637aed0f2719ea709a3d8161a6c556 [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
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070027import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080042import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010043import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070044import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040047import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070049import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070050import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010051import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070052import android.os.storage.VolumeInfo;
53import android.system.ErrnoException;
54import android.system.Os;
55import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070056import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070057import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070058import android.util.Slog;
59import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080060import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070061import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Xml;
63
Makoto Onuki068c54a2015-10-13 14:34:03 -070064import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040066import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070070import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071
72import org.xmlpull.v1.XmlPullParser;
73import org.xmlpull.v1.XmlPullParserException;
74import org.xmlpull.v1.XmlSerializer;
75
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.BufferedOutputStream;
77import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.io.FileOutputStream;
82import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010084import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.util.ArrayList;
86import java.util.List;
87
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import libcore.io.IoUtils;
89
Makoto Onuki068c54a2015-10-13 14:34:03 -070090/**
91 * Service for {@link UserManager}.
92 *
93 * Method naming convention:
94 * - Methods suffixed with "Locked" should be called within the {@code this} lock.
95 * - Methods suffixed with "RL" should be called within the {@link #mRestrictionsLock} lock.
96 */
Amith Yamasani258848d2012-08-10 17:06:33 -070097public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070098
Amith Yamasani2a003292012-08-14 18:25:45 -070099 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700100
Makoto Onuki068c54a2015-10-13 14:34:03 -0700101 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700102
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700105 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700107 private static final String ATTR_CREATION_TIME = "created";
108 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700109 private static final String ATTR_SERIAL_NO = "serialNumber";
110 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700111 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700112 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700113 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100114 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700115 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530116 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800119 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800120 private static final String TAG_ENTRY = "entry";
121 private static final String TAG_VALUE = "value";
122 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700123 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800124 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700126 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
127 private static final String ATTR_TYPE_STRING = "s";
128 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700129 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700130 private static final String ATTR_TYPE_BUNDLE = "B";
131 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132
Amith Yamasani0b285492011-04-14 17:35:23 -0700133 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700135 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100136 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700139 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800140
Amith Yamasani634cf312012-10-04 17:34:21 -0700141 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700142 // We need to keep process uid within Integer.MAX_VALUE.
143 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700144
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700145 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700146
Amith Yamasani920ace02012-09-20 22:15:37 -0700147 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
148
Nicolas Prevotb8186812015-08-06 15:00:03 +0100149 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700150 // without first making sure that the rest of the framework is prepared for it.
151 private static final int MAX_MANAGED_PROFILES = 1;
152
Andres Moralesc5548c02015-08-05 10:23:12 -0700153 /**
154 * Flag indicating whether device credentials are shared among same-user profiles.
155 */
156 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
157
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800158 static final int WRITE_USER_MSG = 1;
159 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700161 private static final String XATTR_SERIAL = "user.serial";
162
Dianne Hackborn4428e172012-08-24 17:43:05 -0700163 private final Context mContext;
164 private final PackageManagerService mPm;
165 private final Object mInstallLock;
166 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800168 private final Handler mHandler;
169
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private final File mUsersDir;
171 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800173 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700174
175 private final Object mRestrictionsLock = new Object();
176
177 /**
178 * User restrictions set via UserManager. This doesn't include restrictions set by
179 * device owner / profile owners.
180 *
181 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
182 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
183 * maybe shared between {@link #mBaseUserRestrictions} and
184 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
185 * (Otherwise we won't be able to detect what restrictions have changed in
186 * {@link #updateUserRestrictionsInternalRL).
187 */
188 @GuardedBy("mRestrictionsLock")
189 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
190
191 /**
192 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
193 * with device / profile owner restrictions. We'll initialize it lazily; use
194 * {@link #getEffectiveUserRestrictions} to access it.
195 *
196 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
197 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
198 * maybe shared between {@link #mBaseUserRestrictions} and
199 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
200 * (Otherwise we won't be able to detect what restrictions have changed in
201 * {@link #updateUserRestrictionsInternalRL).
202 */
203 @GuardedBy("mRestrictionsLock")
204 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
205
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530206 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800207
208 /**
209 * Set of user IDs being actively removed. Removed IDs linger in this set
210 * for several seconds to work around a VFS caching issue.
211 */
212 // @GuardedBy("mPackagesLock")
213 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700214
Amith Yamasani0b285492011-04-14 17:35:23 -0700215 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700216 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700217 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700218
Jason Monk62062992014-05-06 09:55:28 -0400219 private IAppOpsService mAppOpsService;
220
Makoto Onuki068c54a2015-10-13 14:34:03 -0700221 private final LocalService mLocalService;
222
Amith Yamasani258848d2012-08-10 17:06:33 -0700223 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700224
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 public static UserManagerService getInstance() {
226 synchronized (UserManagerService.class) {
227 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700228 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700229 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700230
231 /**
232 * Available for testing purposes.
233 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700234 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700235 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700236 }
237
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238 /**
239 * Called by package manager to create the service. This is closely
240 * associated with the package manager, and the given lock is the
241 * package manager's own lock.
242 */
243 UserManagerService(Context context, PackageManagerService pm,
244 Object installLock, Object packagesLock) {
245 this(context, pm, installLock, packagesLock,
246 Environment.getDataDirectory(),
247 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248 }
249
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250 /**
251 * Available for testing purposes.
252 */
253 private UserManagerService(Context context, PackageManagerService pm,
254 Object installLock, Object packagesLock,
255 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700256 mContext = context;
257 mPm = pm;
258 mInstallLock = installLock;
259 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800260 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 synchronized (mInstallLock) {
262 synchronized (mPackagesLock) {
263 mUsersDir = new File(dataDir, USER_INFO_DIR);
264 mUsersDir.mkdirs();
265 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700266 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 FileUtils.setPermissions(mUsersDir.toString(),
269 FileUtils.S_IRWXU|FileUtils.S_IRWXG
270 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
271 -1, -1);
272 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800273 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700274 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700275 sInstance = this;
276 }
277 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 mLocalService = new LocalService();
279 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700280 }
281
282 void systemReady() {
283 synchronized (mInstallLock) {
284 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700285 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700286 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700287 final int userSize = mUsers.size();
288 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700290 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700291 partials.add(ui);
292 }
293 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700294 final int partialsSize = partials.size();
295 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700297 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700298 + " (name=" + ui.name + ")");
299 removeUserStateLocked(ui.id);
300 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700301 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700302 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700303 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400304 mAppOpsService = IAppOpsService.Stub.asInterface(
305 ServiceManager.getService(Context.APP_OPS_SERVICE));
306 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400308 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400310 } catch (RemoteException e) {
311 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
312 }
313 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700314 }
315
316 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700317 public UserInfo getPrimaryUser() {
318 checkManageUsersPermission("query users");
319 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700320 final int userSize = mUsers.size();
321 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700322 UserInfo ui = mUsers.valueAt(i);
323 if (ui.isPrimary()) {
324 return ui;
325 }
326 }
327 }
328 return null;
329 }
330
331 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700332 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700333 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700334 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700335 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700336 final int userSize = mUsers.size();
337 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700338 UserInfo ui = mUsers.valueAt(i);
339 if (ui.partial) {
340 continue;
341 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800342 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700343 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700344 }
Amith Yamasani13593602012-03-22 16:16:17 -0700345 }
346 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700347 }
Amith Yamasani13593602012-03-22 16:16:17 -0700348 }
349
Amith Yamasani258848d2012-08-10 17:06:33 -0700350 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100351 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800352 if (userId != UserHandle.getCallingUserId()) {
353 checkManageUsersPermission("getting profiles related to user " + userId);
354 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700355 final long ident = Binder.clearCallingIdentity();
356 try {
357 synchronized (mPackagesLock) {
358 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100359 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700360 } finally {
361 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000362 }
363 }
364
Amith Yamasanibe465322014-04-24 13:45:17 -0700365 /** Assume permissions already checked and caller's identity cleared */
366 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700367 UserInfo user = getUserInfoLocked(userId);
368 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700369 if (user == null) {
370 // Probably a dying user
371 return users;
372 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700373 final int userSize = mUsers.size();
374 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700375 UserInfo profile = mUsers.valueAt(i);
376 if (!isProfileOf(user, profile)) {
377 continue;
378 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100379 if (enabledOnly && !profile.isEnabled()) {
380 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700381 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700382 if (mRemovingUserIds.get(profile.id)) {
383 continue;
384 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700385 users.add(profile);
386 }
387 return users;
388 }
389
Jessica Hummelbe81c802014-04-22 15:49:22 +0100390 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700391 public int getCredentialOwnerProfile(int userHandle) {
392 checkManageUsersPermission("get the credential owner");
393 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
394 synchronized (mPackagesLock) {
395 UserInfo profileParent = getProfileParentLocked(userHandle);
396 if (profileParent != null) {
397 return profileParent.id;
398 }
399 }
400 }
401
402 return userHandle;
403 }
404
405 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700406 public boolean isSameProfileGroup(int userId, int otherUserId) {
407 if (userId == otherUserId) return true;
408 checkManageUsersPermission("check if in the same profile group");
409 synchronized (mPackagesLock) {
410 return isSameProfileGroupLocked(userId, otherUserId);
411 }
412 }
413
414 private boolean isSameProfileGroupLocked(int userId, int otherUserId) {
415 UserInfo userInfo = getUserInfoLocked(userId);
416 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
417 return false;
418 }
419 UserInfo otherUserInfo = getUserInfoLocked(otherUserId);
420 if (otherUserInfo == null || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
421 return false;
422 }
423 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
424 }
425
426 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100427 public UserInfo getProfileParent(int userHandle) {
428 checkManageUsersPermission("get the profile parent");
429 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700430 return getProfileParentLocked(userHandle);
431 }
432 }
433
434 private UserInfo getProfileParentLocked(int userHandle) {
435 UserInfo profile = getUserInfoLocked(userHandle);
436 if (profile == null) {
437 return null;
438 }
439 int parentUserId = profile.profileGroupId;
440 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
441 return null;
442 } else {
443 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100444 }
445 }
446
Kenny Guy2a764942014-04-02 13:29:20 +0100447 private boolean isProfileOf(UserInfo user, UserInfo profile) {
448 return user.id == profile.id ||
449 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
450 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000451 }
452
453 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100454 public void setUserEnabled(int userId) {
455 checkManageUsersPermission("enable user");
456 synchronized (mPackagesLock) {
457 UserInfo info = getUserInfoLocked(userId);
458 if (info != null && !info.isEnabled()) {
459 info.flags ^= UserInfo.FLAG_DISABLED;
460 writeUserLocked(info);
461 }
462 }
463 }
464
465 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700466 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700467 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700468 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700469 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700470 }
471 }
472
Amith Yamasani71e6c692013-03-24 17:39:28 -0700473 @Override
474 public boolean isRestricted() {
475 synchronized (mPackagesLock) {
476 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
477 }
478 }
479
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700480 @Override
481 public boolean canHaveRestrictedProfile(int userId) {
482 checkManageUsersPermission("canHaveRestrictedProfile");
483 synchronized (mPackagesLock) {
484 final UserInfo userInfo = getUserInfoLocked(userId);
485 if (userInfo == null || !userInfo.canHaveProfile()) {
486 return false;
487 }
488 if (!userInfo.isAdmin()) {
489 return false;
490 }
491 }
492 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
493 Context.DEVICE_POLICY_SERVICE);
494 // restricted profile can be created if there is no DO set and the admin user has no PO
495 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
496 }
497
Amith Yamasani195263742012-08-21 15:40:12 -0700498 /*
499 * Should be locked on mUsers before calling this.
500 */
501 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700502 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700503 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800504 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700505 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
506 return null;
507 }
508 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700509 }
510
Amith Yamasani236b2b52015-08-18 14:32:14 -0700511 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700512 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700513 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700514 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700515 }
516 }
517
Amith Yamasani258848d2012-08-10 17:06:33 -0700518 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700519 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700520 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700521 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700522 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700523 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700524 if (info == null || info.partial) {
525 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
526 return;
527 }
Amith Yamasani13593602012-03-22 16:16:17 -0700528 if (name != null && !name.equals(info.name)) {
529 info.name = name;
530 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700532 }
533 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700534 if (changed) {
535 sendUserInfoChangedBroadcast(userId);
536 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700537 }
538
Amith Yamasani258848d2012-08-10 17:06:33 -0700539 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700540 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700541 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400542 long ident = Binder.clearCallingIdentity();
543 try {
544 synchronized (mPackagesLock) {
545 UserInfo info = mUsers.get(userId);
546 if (info == null || info.partial) {
547 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
548 return;
549 }
550 writeBitmapLocked(info, bitmap);
551 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700552 }
Jason Monk9a944532014-07-08 09:31:21 -0400553 sendUserInfoChangedBroadcast(userId);
554 } finally {
555 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700556 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700557 }
558
559 private void sendUserInfoChangedBroadcast(int userId) {
560 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
561 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
562 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700563 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700564 }
565
Amith Yamasani258848d2012-08-10 17:06:33 -0700566 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100567 public ParcelFileDescriptor getUserIcon(int userId) {
568 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700569 synchronized (mPackagesLock) {
570 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700571 if (info == null || info.partial) {
572 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
573 return null;
574 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100575 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
576 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
577 || callingGroupId != info.profileGroupId) {
578 checkManageUsersPermission("get the icon of a user who is not related");
579 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700580 if (info.iconPath == null) {
581 return null;
582 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100583 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700584 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100585
586 try {
587 return ParcelFileDescriptor.open(
588 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
589 } catch (FileNotFoundException e) {
590 Log.e(LOG_TAG, "Couldn't find icon file", e);
591 }
592 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700593 }
594
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700595 public void makeInitialized(int userId) {
596 checkManageUsersPermission("makeInitialized");
597 synchronized (mPackagesLock) {
598 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700599 if (info == null || info.partial) {
600 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
601 }
602 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700603 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800604 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700605 }
606 }
607 }
608
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700609 /**
610 * If default guest restrictions haven't been initialized yet, add the basic
611 * restrictions.
612 */
613 private void initDefaultGuestRestrictions() {
614 if (mGuestRestrictions.isEmpty()) {
615 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800616 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700617 }
618 }
619
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800620 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530621 public Bundle getDefaultGuestRestrictions() {
622 checkManageUsersPermission("getDefaultGuestRestrictions");
623 synchronized (mPackagesLock) {
624 return new Bundle(mGuestRestrictions);
625 }
626 }
627
628 @Override
629 public void setDefaultGuestRestrictions(Bundle restrictions) {
630 checkManageUsersPermission("setDefaultGuestRestrictions");
631 synchronized (mPackagesLock) {
632 mGuestRestrictions.clear();
633 mGuestRestrictions.putAll(restrictions);
634 writeUserListLocked();
635 }
636 }
637
Makoto Onuki068c54a2015-10-13 14:34:03 -0700638 @GuardedBy("mRestrictionsLock")
639 private Bundle computeEffectiveUserRestrictionsRL(int userId) {
640 final DevicePolicyManagerInternal dpmi =
641 LocalServices.getService(DevicePolicyManagerInternal.class);
642 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
643
644 final Bundle effective;
645 if (dpmi == null) {
646 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
647 effective = systemRestrictions;
648 } else {
649 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
650 }
651 return effective;
652 }
653
654 @GuardedBy("mRestrictionsLock")
655 private void invalidateEffectiveUserRestrictionsRL(int userId) {
656 if (DBG) {
657 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
658 }
659 mCachedEffectiveUserRestrictions.remove(userId);
660 }
661
662 private Bundle getEffectiveUserRestrictions(int userId) {
663 synchronized (mRestrictionsLock) {
664 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
665 if (restrictions == null) {
666 restrictions = computeEffectiveUserRestrictionsRL(userId);
667 mCachedEffectiveUserRestrictions.put(userId, restrictions);
668 }
669 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700670 }
671 }
672
Makoto Onuki068c54a2015-10-13 14:34:03 -0700673 /** @return a specific user restriction that's in effect currently. */
674 @Override
675 public boolean hasUserRestriction(String restrictionKey, int userId) {
676 Bundle restrictions = getEffectiveUserRestrictions(userId);
677 return restrictions != null && restrictions.getBoolean(restrictionKey);
678 }
679
680 /**
681 * @return UserRestrictions that are in effect currently. This always returns a new
682 * {@link Bundle}.
683 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700684 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800685 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700686 Bundle restrictions = getEffectiveUserRestrictions(userId);
687 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800688 }
689
690 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700691 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700692 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700693 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
694 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700695 }
696 }
697
698 @Override
699 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
700 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700701 setUserRestrictionNoCheck(key, value, userId);
702 }
703
704 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
705 synchronized (mRestrictionsLock) {
706 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
707 // a copy.
708 final Bundle newRestrictions = new Bundle();
709 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
710 newRestrictions.putBoolean(key, value);
711
712 updateUserRestrictionsInternalRL(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700713 }
714 }
715
Makoto Onuki068c54a2015-10-13 14:34:03 -0700716 /**
717 * Optionally updating user restrictions, calculate the effective user restrictions by
718 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
719 * apply it to {@link com.android.server.AppOpsService}.
720 * TODO applyUserRestrictionsLocked() should also apply to system settings.
721 *
722 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
723 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
724 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
725 * @param userId target user ID.
726 */
727 @GuardedBy("mRestrictionsLock")
728 private void updateUserRestrictionsInternalRL(
729 @Nullable Bundle newRestrictions, int userId) {
730 if (DBG) {
731 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
732 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800733 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700734 final Bundle prevRestrictions = getEffectiveUserRestrictions(userId);
735
736 // Update system restrictions.
737 if (newRestrictions != null) {
738 // If newRestrictions == the current one, it's probably a bug.
739 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
740 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
741 != newRestrictions);
742 mBaseUserRestrictions.put(userId, newRestrictions);
743 }
744
745 mCachedEffectiveUserRestrictions.put(
746 userId, computeEffectiveUserRestrictionsRL(userId));
747
748 applyUserRestrictionsRL(userId, mBaseUserRestrictions.get(userId), prevRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800749 }
750
Makoto Onuki068c54a2015-10-13 14:34:03 -0700751 @GuardedBy("mRestrictionsLock")
752 private void applyUserRestrictionsRL(int userId,
753 Bundle newRestrictions, Bundle prevRestrictions) {
754 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700755 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700756 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700757 } catch (RemoteException e) {
758 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
759 } finally {
760 Binder.restoreCallingIdentity(token);
761 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700762
763 // TODO Move the code from DPMS.setUserRestriction().
764 }
765
766 @GuardedBy("mRestrictionsLock")
767 private void updateEffectiveUserRestrictionsRL(int userId) {
768 updateUserRestrictionsInternalRL(null, userId);
769 }
770
771 @GuardedBy("mRestrictionsLock")
772 private void updateEffectiveUserRestrictionsForAllUsersRL() {
773 // First, invalidate all cached values.
774 synchronized (mRestrictionsLock) {
775 mCachedEffectiveUserRestrictions.clear();
776 }
777 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
778 // it on a handler.
779 final Runnable r = new Runnable() {
780 @Override
781 public void run() {
782 // Then get the list of running users.
783 final int[] runningUsers;
784 try {
785 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
786 } catch (RemoteException e) {
787 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
788 return;
789 }
790 // Then re-calculate the effective restrictions and apply, only for running users.
791 // It's okay if a new user has started after the getRunningUserIds() call,
792 // because we'll do the same thing (re-calculate the restrictions and apply)
793 // when we start a user.
794 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
795 synchronized (mRestrictionsLock) {
796 for (int i = 0; i < runningUsers.length; i++) {
797 updateUserRestrictionsInternalRL(null, runningUsers[i]);
798 }
799 }
800 }
801 };
802 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700803 }
804
Amith Yamasani258848d2012-08-10 17:06:33 -0700805 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700806 * Check if we've hit the limit of how many users can be created.
807 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700808 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700809 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
810 }
811
812 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100813 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700814 checkManageUsersPermission("check if more managed profiles can be added.");
815 if (ActivityManager.isLowRamDeviceStatic()) {
816 return false;
817 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700818 if (!mContext.getPackageManager().hasSystemFeature(
819 PackageManager.FEATURE_MANAGED_USERS)) {
820 return false;
821 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100822 // Limit number of managed profiles that can be created
823 int managedProfilesCount = getProfiles(userId, true).size() - 1;
824 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
825 return false;
826 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700827 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100828 UserInfo userInfo = getUserInfoLocked(userId);
829 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700830 return false;
831 }
832 int usersCount = getAliveUsersExcludingGuestsCountLocked();
833 // We allow creating a managed profile in the special case where there is only one user.
834 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
835 }
836 }
837
838 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700839 int aliveUserCount = 0;
840 final int totalUserCount = mUsers.size();
841 // Skip over users being removed
842 for (int i = 0; i < totalUserCount; i++) {
843 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700844 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700845 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700846 aliveUserCount++;
847 }
848 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700849 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700850 }
851
852 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700853 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700854 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700855 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700856 *
857 * @param message used as message if SecurityException is thrown
858 * @throws SecurityException if the caller is not system or root
859 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700860 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700861 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700862 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400863 && ActivityManager.checkComponentPermission(
864 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700865 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
866 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
867 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400868 }
869
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700870 private static void checkSystemOrRoot(String message) {
871 final int uid = Binder.getCallingUid();
872 if (uid != Process.SYSTEM_UID && uid != 0) {
873 throw new SecurityException("Only system may call: " + message);
874 }
875 }
876
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700877 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700878 try {
879 File dir = new File(mUsersDir, Integer.toString(info.id));
880 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100881 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700882 if (!dir.exists()) {
883 dir.mkdir();
884 FileUtils.setPermissions(
885 dir.getPath(),
886 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
887 -1, -1);
888 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700889 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100890 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
891 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700892 info.iconPath = file.getAbsolutePath();
893 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700894 try {
895 os.close();
896 } catch (IOException ioe) {
897 // What the ... !
898 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100899 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700900 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700901 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700902 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700903 }
904
Amith Yamasani0b285492011-04-14 17:35:23 -0700905 /**
906 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
907 * cache it elsewhere.
908 * @return the array of user ids.
909 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700910 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700911 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700912 return mUserIds;
913 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700914 }
915
Dianne Hackborn4428e172012-08-24 17:43:05 -0700916 int[] getUserIdsLPr() {
917 return mUserIds;
918 }
919
Amith Yamasani13593602012-03-22 16:16:17 -0700920 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700921 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700922 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923 return;
924 }
925 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700926 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700927 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700928 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700929 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100930 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700931 int type;
932 while ((type = parser.next()) != XmlPullParser.START_TAG
933 && type != XmlPullParser.END_DOCUMENT) {
934 ;
935 }
936
937 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700938 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700939 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940 return;
941 }
942
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 mNextSerialNumber = -1;
944 if (parser.getName().equals(TAG_USERS)) {
945 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
946 if (lastSerialNumber != null) {
947 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
948 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700949 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
950 if (versionNumber != null) {
951 mUserVersion = Integer.parseInt(versionNumber);
952 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700953 }
954
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700955 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530956 if (type == XmlPullParser.START_TAG) {
957 final String name = parser.getName();
958 if (name.equals(TAG_USER)) {
959 String id = parser.getAttributeValue(null, ATTR_ID);
960 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700961
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530962 if (user != null) {
963 mUsers.put(user.id, user);
964 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
965 mNextSerialNumber = user.id + 1;
966 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700967 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530968 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800969 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
970 && type != XmlPullParser.END_TAG) {
971 if (type == XmlPullParser.START_TAG) {
972 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700973 UserRestrictionsUtils
974 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800975 }
976 break;
977 }
978 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700979 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700980 }
981 }
Amith Yamasani13593602012-03-22 16:16:17 -0700982 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700983 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700985 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700986 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700987 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800988 } finally {
989 if (fis != null) {
990 try {
991 fis.close();
992 } catch (IOException e) {
993 }
994 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995 }
996 }
997
Amith Yamasani6f34b412012-10-22 18:19:27 -0700998 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800999 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001000 */
Amith Yamasani350962c2013-08-06 11:18:53 -07001001 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001002 int userVersion = mUserVersion;
1003 if (userVersion < 1) {
1004 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -07001005 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001006 if ("Primary".equals(user.name)) {
1007 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001008 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001009 }
1010 userVersion = 1;
1011 }
1012
Amith Yamasanibc9625052012-11-15 14:39:18 -08001013 if (userVersion < 2) {
1014 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -07001015 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001016 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1017 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001018 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001019 }
1020 userVersion = 2;
1021 }
1022
Amith Yamasani350962c2013-08-06 11:18:53 -07001023
Amith Yamasani5e486f52013-08-07 11:06:44 -07001024 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001025 userVersion = 4;
1026 }
1027
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001028 if (userVersion < 5) {
1029 initDefaultGuestRestrictions();
1030 userVersion = 5;
1031 }
1032
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001033 if (userVersion < 6) {
1034 final boolean splitSystemUser = UserManager.isSplitSystemUser();
1035 for (int i = 0; i < mUsers.size(); i++) {
1036 UserInfo user = mUsers.valueAt(i);
1037 // In non-split mode, only user 0 can have restricted profiles
1038 if (!splitSystemUser && user.isRestricted()
1039 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1040 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1041 scheduleWriteUserLocked(user);
1042 }
1043 }
1044 userVersion = 6;
1045 }
1046
Amith Yamasani6f34b412012-10-22 18:19:27 -07001047 if (userVersion < USER_VERSION) {
1048 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1049 + USER_VERSION);
1050 } else {
1051 mUserVersion = userVersion;
1052 writeUserListLocked();
1053 }
1054 }
1055
Amith Yamasani13593602012-03-22 16:16:17 -07001056 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001057 int flags = UserInfo.FLAG_INITIALIZED;
1058 // In split system user mode, the admin and primary flags are assigned to the first human
1059 // user.
1060 if (!UserManager.isSplitSystemUser()) {
1061 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1062 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001063 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001064 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001065 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001066 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001067 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001068 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001069 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001070
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001071 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001072 synchronized (mRestrictionsLock) {
1073 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1074 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001075
Amith Yamasani13593602012-03-22 16:16:17 -07001076 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001077 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001078
Amith Yamasani13593602012-03-22 16:16:17 -07001079 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001080 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001081 }
1082
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001083 private void scheduleWriteUserLocked(UserInfo userInfo) {
1084 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1085 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1086 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1087 }
1088 }
1089
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001090 /*
1091 * Writes the user file in this format:
1092 *
1093 * <user flags="20039023" id="0">
1094 * <name>Primary</name>
1095 * </user>
1096 */
Amith Yamasani13593602012-03-22 16:16:17 -07001097 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001098 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001099 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001100 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001101 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001102 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1103
1104 // XmlSerializer serializer = XmlUtils.serializerInstance();
1105 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001106 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001107 serializer.startDocument(null, true);
1108 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1109
1110 serializer.startTag(null, TAG_USER);
1111 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001112 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001113 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001114 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1115 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1116 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001117 if (userInfo.iconPath != null) {
1118 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1119 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001120 if (userInfo.partial) {
1121 serializer.attribute(null, ATTR_PARTIAL, "true");
1122 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001123 if (userInfo.guestToRemove) {
1124 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1125 }
Kenny Guy2a764942014-04-02 13:29:20 +01001126 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1127 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1128 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001129 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001130 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1131 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1132 Integer.toString(userInfo.restrictedProfileParentId));
1133 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001134 serializer.startTag(null, TAG_NAME);
1135 serializer.text(userInfo.name);
1136 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001137 Bundle restrictions;
1138 synchronized (mRestrictionsLock) {
1139 restrictions = mBaseUserRestrictions.get(userInfo.id);
1140 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001141 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001142 UserRestrictionsUtils
1143 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001144 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001145 serializer.endTag(null, TAG_USER);
1146
1147 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001148 userFile.finishWrite(fos);
1149 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001150 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001151 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001152 }
1153 }
1154
1155 /*
1156 * Writes the user list file in this format:
1157 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001158 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001159 * <user id="0"></user>
1160 * <user id="2"></user>
1161 * </users>
1162 */
Amith Yamasani13593602012-03-22 16:16:17 -07001163 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001164 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001165 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001166 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001167 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001168 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1169
1170 // XmlSerializer serializer = XmlUtils.serializerInstance();
1171 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001172 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001173 serializer.startDocument(null, true);
1174 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1175
1176 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001177 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001178 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001179
Adam Lesinskieddeb492014-09-08 17:50:03 -07001180 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001181 UserRestrictionsUtils
1182 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301183 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001184 final int userSize = mUsers.size();
1185 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001186 UserInfo user = mUsers.valueAt(i);
1187 serializer.startTag(null, TAG_USER);
1188 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1189 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001190 }
1191
1192 serializer.endTag(null, TAG_USERS);
1193
1194 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001195 userListFile.finishWrite(fos);
1196 } catch (Exception e) {
1197 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001198 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001199 }
1200 }
1201
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001202 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001203 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001204 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001205 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001206 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001207 long creationTime = 0L;
1208 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001209 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001210 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001211 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001212 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001213 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001214
1215 FileInputStream fis = null;
1216 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001217 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001218 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001219 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001220 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001221 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001222 int type;
1223 while ((type = parser.next()) != XmlPullParser.START_TAG
1224 && type != XmlPullParser.END_DOCUMENT) {
1225 ;
1226 }
1227
1228 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001229 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001230 return null;
1231 }
1232
1233 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001234 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1235 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001236 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001237 return null;
1238 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001239 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1240 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001241 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001242 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1243 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001244 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1245 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001246 restrictedProfileParentId = readIntAttribute(parser,
1247 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001248 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1249 if ("true".equals(valueString)) {
1250 partial = true;
1251 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001252 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1253 if ("true".equals(valueString)) {
1254 guestToRemove = true;
1255 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001257 int outerDepth = parser.getDepth();
1258 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1259 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1260 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1261 continue;
1262 }
1263 String tag = parser.getName();
1264 if (TAG_NAME.equals(tag)) {
1265 type = parser.next();
1266 if (type == XmlPullParser.TEXT) {
1267 name = parser.getText();
1268 }
1269 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001270 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001271 }
1272 }
1273 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001274
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001275 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001276 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001277 userInfo.creationTime = creationTime;
1278 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001279 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001280 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001281 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001282 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001283 synchronized (mRestrictionsLock) {
1284 mBaseUserRestrictions.append(id, restrictions);
1285 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001286 return userInfo;
1287
1288 } catch (IOException ioe) {
1289 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001290 } finally {
1291 if (fis != null) {
1292 try {
1293 fis.close();
1294 } catch (IOException e) {
1295 }
1296 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001297 }
1298 return null;
1299 }
1300
Amith Yamasani920ace02012-09-20 22:15:37 -07001301 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1302 String valueString = parser.getAttributeValue(null, attr);
1303 if (valueString == null) return defaultValue;
1304 try {
1305 return Integer.parseInt(valueString);
1306 } catch (NumberFormatException nfe) {
1307 return defaultValue;
1308 }
1309 }
1310
1311 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1312 String valueString = parser.getAttributeValue(null, attr);
1313 if (valueString == null) return defaultValue;
1314 try {
1315 return Long.parseLong(valueString);
1316 } catch (NumberFormatException nfe) {
1317 return defaultValue;
1318 }
1319 }
1320
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001321 private boolean isPackageInstalled(String pkg, int userId) {
1322 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1323 PackageManager.GET_UNINSTALLED_PACKAGES,
1324 userId);
1325 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1326 return false;
1327 }
1328 return true;
1329 }
1330
Amith Yamasanib82add22013-07-09 11:24:44 -07001331 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001332 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001333 * Does not do any permissions checking.
1334 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001335 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001336 synchronized (mPackagesLock) {
1337 File dir = Environment.getUserSystemDirectory(userId);
1338 String[] files = dir.list();
1339 if (files == null) return;
1340 for (String fileName : files) {
1341 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1342 File resFile = new File(dir, fileName);
1343 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001344 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001345 }
1346 }
1347 }
1348 }
1349 }
1350
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001351 /**
1352 * Removes the app restrictions file for a specific package and user id, if it exists.
1353 */
1354 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1355 synchronized (mPackagesLock) {
1356 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001357 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001358 if (resFile.exists()) {
1359 resFile.delete();
1360 }
1361 }
1362 }
1363
Kenny Guya52dc3e2014-02-11 15:33:14 +00001364 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001365 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001366 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001367 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001368 }
1369
Amith Yamasani258848d2012-08-10 17:06:33 -07001370 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001371 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001372 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001373 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001374 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001375
Jessica Hummelbe81c802014-04-22 15:49:22 +01001376 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001377 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1378 UserManager.DISALLOW_ADD_USER, false)) {
1379 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1380 return null;
1381 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001382 if (ActivityManager.isLowRamDeviceStatic()) {
1383 return null;
1384 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001385 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001386 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001387 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001388 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001389 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001390 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001391 try {
1392 synchronized (mInstallLock) {
1393 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001394 UserInfo parent = null;
1395 if (parentId != UserHandle.USER_NULL) {
1396 parent = getUserInfoLocked(parentId);
1397 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001398 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001399 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1400 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001401 return null;
1402 }
1403 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1404 // If we're not adding a guest user or a managed profile and the limit has
1405 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001406 return null;
1407 }
1408 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001409 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001410 return null;
1411 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001412 // In legacy mode, restricted profile's parent can only be the owner user
1413 if (isRestricted && !UserManager.isSplitSystemUser()
1414 && (parentId != UserHandle.USER_SYSTEM)) {
1415 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1416 return null;
1417 }
1418 if (isRestricted && UserManager.isSplitSystemUser()) {
1419 if (parent == null) {
1420 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1421 + "specified");
1422 return null;
1423 }
1424 if (!parent.canHaveProfile()) {
1425 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1426 + "created for the specified parent user id " + parentId);
1427 return null;
1428 }
1429 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001430 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001431 // And if there is no device owner, we also assign the admin flag to primary
1432 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001433 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001434 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001435 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001436 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1437 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1438 if (devicePolicyManager == null
1439 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001440 flags |= UserInfo.FLAG_ADMIN;
1441 }
1442 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001443 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001444 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001445 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001446 long now = System.currentTimeMillis();
1447 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001448 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001449 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001450 mUsers.put(userId, userInfo);
1451 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001452 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001453 if (isManagedProfile) {
1454 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1455 parent.profileGroupId = parent.id;
1456 scheduleWriteUserLocked(parent);
1457 }
1458 userInfo.profileGroupId = parent.profileGroupId;
1459 } else if (isRestricted) {
1460 if (!parent.canHaveProfile()) {
1461 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1462 }
1463 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1464 parent.restrictedProfileParentId = parent.id;
1465 scheduleWriteUserLocked(parent);
1466 }
1467 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001468 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001469 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001470 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1471 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1472 final String volumeUuid = vol.getFsUuid();
1473 try {
1474 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1475 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001476 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001477 enforceSerialNumber(userDir, userInfo.serialNumber);
1478 } catch (IOException e) {
1479 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1480 }
1481 }
1482 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001483 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001484 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001485 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001486 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001487 synchronized (mRestrictionsLock) {
1488 mBaseUserRestrictions.append(userId, restrictions);
1489 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001490 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001491 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001492 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001493 if (userInfo != null) {
1494 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1495 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1496 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1497 android.Manifest.permission.MANAGE_USERS);
1498 }
1499 } finally {
1500 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001501 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001502 return userInfo;
1503 }
1504
Amith Yamasani0b285492011-04-14 17:35:23 -07001505 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001506 * @hide
1507 */
1508 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1509 checkManageUsersPermission("setupRestrictedProfile");
1510 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1511 if (user == null) {
1512 return null;
1513 }
1514 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1515 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1516 // the putIntForUser() will fail.
1517 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1518 android.provider.Settings.Secure.LOCATION_MODE,
1519 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1520 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1521 return user;
1522 }
1523
1524 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001525 * Find the current guest user. If the Guest user is partial,
1526 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001527 */
1528 private UserInfo findCurrentGuestUserLocked() {
1529 final int size = mUsers.size();
1530 for (int i = 0; i < size; i++) {
1531 final UserInfo user = mUsers.valueAt(i);
1532 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1533 return user;
1534 }
1535 }
1536 return null;
1537 }
1538
1539 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001540 * Mark this guest user for deletion to allow us to create another guest
1541 * and switch to that user before actually removing this guest.
1542 * @param userHandle the userid of the current guest
1543 * @return whether the user could be marked for deletion
1544 */
1545 public boolean markGuestForDeletion(int userHandle) {
1546 checkManageUsersPermission("Only the system can remove users");
1547 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1548 UserManager.DISALLOW_REMOVE_USER, false)) {
1549 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1550 return false;
1551 }
1552
1553 long ident = Binder.clearCallingIdentity();
1554 try {
1555 final UserInfo user;
1556 synchronized (mPackagesLock) {
1557 user = mUsers.get(userHandle);
1558 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1559 return false;
1560 }
1561 if (!user.isGuest()) {
1562 return false;
1563 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001564 // We set this to a guest user that is to be removed. This is a temporary state
1565 // where we are allowed to add new Guest users, even if this one is still not
1566 // removed. This user will still show up in getUserInfo() calls.
1567 // If we don't get around to removing this Guest user, it will be purged on next
1568 // startup.
1569 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001570 // Mark it as disabled, so that it isn't returned any more when
1571 // profiles are queried.
1572 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001573 writeUserLocked(user);
1574 }
1575 } finally {
1576 Binder.restoreCallingIdentity(ident);
1577 }
1578 return true;
1579 }
1580
1581 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001582 * Removes a user and all data directories created for that user. This method should be called
1583 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001584 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001585 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001586 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001587 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001588 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1589 UserManager.DISALLOW_REMOVE_USER, false)) {
1590 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1591 return false;
1592 }
1593
Kenny Guyee58b4f2014-05-23 15:19:53 +01001594 long ident = Binder.clearCallingIdentity();
1595 try {
1596 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001597 int currentUser = ActivityManager.getCurrentUser();
1598 if (currentUser == userHandle) {
1599 Log.w(LOG_TAG, "Current user cannot be removed");
1600 return false;
1601 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001602 synchronized (mPackagesLock) {
1603 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001604 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001605 return false;
1606 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001607
1608 // We remember deleted user IDs to prevent them from being
1609 // reused during the current boot; they can still be reused
1610 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001611 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001612
Kenny Guyee58b4f2014-05-23 15:19:53 +01001613 try {
1614 mAppOpsService.removeUser(userHandle);
1615 } catch (RemoteException e) {
1616 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1617 }
1618 // Set this to a partially created user, so that the user will be purged
1619 // on next startup, in case the runtime stops now before stopping and
1620 // removing the user completely.
1621 user.partial = true;
1622 // Mark it as disabled, so that it isn't returned any more when
1623 // profiles are queried.
1624 user.flags |= UserInfo.FLAG_DISABLED;
1625 writeUserLocked(user);
1626 }
1627
1628 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1629 && user.isManagedProfile()) {
1630 // Send broadcast to notify system that the user removed was a
1631 // managed user.
1632 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1633 }
1634
1635 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1636 int res;
1637 try {
1638 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1639 new IStopUserCallback.Stub() {
1640 @Override
1641 public void userStopped(int userId) {
1642 finishRemoveUser(userId);
1643 }
1644 @Override
1645 public void userStopAborted(int userId) {
1646 }
1647 });
1648 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001649 return false;
1650 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001651 return res == ActivityManager.USER_OP_SUCCESS;
1652 } finally {
1653 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001654 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001655 }
1656
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001657 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001658 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001659 // Let other services shutdown any activity and clean up their state before completely
1660 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001661 long ident = Binder.clearCallingIdentity();
1662 try {
1663 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1664 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001665 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1666 android.Manifest.permission.MANAGE_USERS,
1667
1668 new BroadcastReceiver() {
1669 @Override
1670 public void onReceive(Context context, Intent intent) {
1671 if (DBG) {
1672 Slog.i(LOG_TAG,
1673 "USER_REMOVED broadcast sent, cleaning up user data "
1674 + userHandle);
1675 }
1676 new Thread() {
1677 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001678 // Clean up any ActivityManager state
1679 LocalServices.getService(ActivityManagerInternal.class)
1680 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001681 synchronized (mInstallLock) {
1682 synchronized (mPackagesLock) {
1683 removeUserStateLocked(userHandle);
1684 }
1685 }
1686 }
1687 }.start();
1688 }
1689 },
1690
1691 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001692 } finally {
1693 Binder.restoreCallingIdentity(ident);
1694 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001695 }
1696
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001697 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001698 mContext.getSystemService(StorageManager.class)
1699 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001700 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001701 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001702
1703 // Remove this user from the list
1704 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001705 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001706 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001707 userFile.delete();
1708 // Update the user list
1709 writeUserListLocked();
1710 updateUserIdsLocked();
1711 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1712 }
1713
Amith Yamasani61f57372012-08-31 12:12:28 -07001714 private void removeDirectoryRecursive(File parent) {
1715 if (parent.isDirectory()) {
1716 String[] files = parent.list();
1717 for (String filename : files) {
1718 File child = new File(parent, filename);
1719 removeDirectoryRecursive(child);
1720 }
1721 }
1722 parent.delete();
1723 }
1724
Kenny Guyf8d3a232014-05-15 16:09:52 +01001725 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001726 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001727 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1728 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001729 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1730 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001731 }
1732
Amith Yamasani2a003292012-08-14 18:25:45 -07001733 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001734 public Bundle getApplicationRestrictions(String packageName) {
1735 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1736 }
1737
1738 @Override
1739 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001740 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001741 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001742 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001743 }
1744 synchronized (mPackagesLock) {
1745 // Read the restrictions from XML
1746 return readApplicationRestrictionsLocked(packageName, userId);
1747 }
1748 }
1749
1750 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001751 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001752 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001753 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001754 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001755 if (restrictions == null || restrictions.isEmpty()) {
1756 cleanAppRestrictionsForPackage(packageName, userId);
1757 } else {
1758 // Write the restrictions to XML
1759 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1760 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001761 }
Robin Lee66e5d962014-04-09 16:44:21 +01001762
Kenny Guyd21b2182014-07-17 16:38:55 +01001763 if (isPackageInstalled(packageName, userId)) {
1764 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1765 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1766 changeIntent.setPackage(packageName);
1767 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1768 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1769 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001770 }
1771
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001772 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001773 mHandler.post(new Runnable() {
1774 @Override
1775 public void run() {
1776 List<ApplicationInfo> apps =
1777 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1778 userHandle).getList();
1779 final long ident = Binder.clearCallingIdentity();
1780 try {
1781 for (ApplicationInfo appInfo : apps) {
1782 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001783 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1784 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001785 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001786 userHandle);
1787 }
1788 }
1789 } finally {
1790 Binder.restoreCallingIdentity(ident);
1791 }
1792 }
1793 });
1794 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001795 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001796 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001797 try {
1798 return mContext.getPackageManager().getApplicationInfo(packageName,
1799 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1800 } catch (NameNotFoundException nnfe) {
1801 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001802 } finally {
1803 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001804 }
1805 }
1806
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001807 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001808 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001809 AtomicFile restrictionsFile =
1810 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1811 packageToRestrictionsFileName(packageName)));
1812 return readApplicationRestrictionsLocked(restrictionsFile);
1813 }
1814
1815 @VisibleForTesting
1816 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001817 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001818 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001819 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001820 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001821 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001822
1823 FileInputStream fis = null;
1824 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001825 fis = restrictionsFile.openRead();
1826 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001827 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001828 XmlUtils.nextElement(parser);
1829 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001830 Slog.e(LOG_TAG, "Unable to read restrictions file "
1831 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001832 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001833 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001834 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1835 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001836 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001837 } catch (IOException|XmlPullParserException e) {
1838 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001839 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001840 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001841 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001842 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001843 }
1844
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001845 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1846 XmlPullParser parser) throws XmlPullParserException, IOException {
1847 int type = parser.getEventType();
1848 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1849 String key = parser.getAttributeValue(null, ATTR_KEY);
1850 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1851 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1852 if (multiple != null) {
1853 values.clear();
1854 int count = Integer.parseInt(multiple);
1855 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1856 if (type == XmlPullParser.START_TAG
1857 && parser.getName().equals(TAG_VALUE)) {
1858 values.add(parser.nextText().trim());
1859 count--;
1860 }
1861 }
1862 String [] valueStrings = new String[values.size()];
1863 values.toArray(valueStrings);
1864 restrictions.putStringArray(key, valueStrings);
1865 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1866 restrictions.putBundle(key, readBundleEntry(parser, values));
1867 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1868 final int outerDepth = parser.getDepth();
1869 ArrayList<Bundle> bundleList = new ArrayList<>();
1870 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1871 Bundle childBundle = readBundleEntry(parser, values);
1872 bundleList.add(childBundle);
1873 }
1874 restrictions.putParcelableArray(key,
1875 bundleList.toArray(new Bundle[bundleList.size()]));
1876 } else {
1877 String value = parser.nextText().trim();
1878 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1879 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1880 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1881 restrictions.putInt(key, Integer.parseInt(value));
1882 } else {
1883 restrictions.putString(key, value);
1884 }
1885 }
1886 }
1887 }
1888
1889 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1890 throws IOException, XmlPullParserException {
1891 Bundle childBundle = new Bundle();
1892 final int outerDepth = parser.getDepth();
1893 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1894 readEntry(childBundle, values, parser);
1895 }
1896 return childBundle;
1897 }
1898
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001899 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001900 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001901 AtomicFile restrictionsFile = new AtomicFile(
1902 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001903 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001904 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1905 }
1906
1907 @VisibleForTesting
1908 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1909 AtomicFile restrictionsFile) {
1910 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001911 try {
1912 fos = restrictionsFile.startWrite();
1913 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1914
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001915 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001916 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001917 serializer.startDocument(null, true);
1918 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1919
1920 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001921 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001922 serializer.endTag(null, TAG_RESTRICTIONS);
1923
1924 serializer.endDocument();
1925 restrictionsFile.finishWrite(fos);
1926 } catch (Exception e) {
1927 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001928 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1929 }
1930 }
1931
1932 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1933 throws IOException {
1934 for (String key : restrictions.keySet()) {
1935 Object value = restrictions.get(key);
1936 serializer.startTag(null, TAG_ENTRY);
1937 serializer.attribute(null, ATTR_KEY, key);
1938
1939 if (value instanceof Boolean) {
1940 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1941 serializer.text(value.toString());
1942 } else if (value instanceof Integer) {
1943 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1944 serializer.text(value.toString());
1945 } else if (value == null || value instanceof String) {
1946 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1947 serializer.text(value != null ? (String) value : "");
1948 } else if (value instanceof Bundle) {
1949 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1950 writeBundle((Bundle) value, serializer);
1951 } else if (value instanceof Parcelable[]) {
1952 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1953 Parcelable[] array = (Parcelable[]) value;
1954 for (Parcelable parcelable : array) {
1955 if (!(parcelable instanceof Bundle)) {
1956 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1957 }
1958 serializer.startTag(null, TAG_ENTRY);
1959 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1960 writeBundle((Bundle) parcelable, serializer);
1961 serializer.endTag(null, TAG_ENTRY);
1962 }
1963 } else {
1964 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1965 String[] values = (String[]) value;
1966 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1967 for (String choice : values) {
1968 serializer.startTag(null, TAG_VALUE);
1969 serializer.text(choice != null ? choice : "");
1970 serializer.endTag(null, TAG_VALUE);
1971 }
1972 }
1973 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001974 }
1975 }
1976
1977 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001978 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001979 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001980 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001981 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001982 }
1983 }
1984
1985 @Override
1986 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001987 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001988 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001989 UserInfo info = getUserInfoLocked(userId);
1990 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 }
1992 // Not found
1993 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001994 }
1995 }
1996
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001997 @Override
1998 public long getUserCreationTime(int userHandle) {
1999 int callingUserId = UserHandle.getCallingUserId();
2000 UserInfo userInfo = null;
2001 synchronized (mPackagesLock) {
2002 if (callingUserId == userHandle) {
2003 userInfo = getUserInfoLocked(userHandle);
2004 } else {
2005 UserInfo parent = getProfileParentLocked(userHandle);
2006 if (parent != null && parent.id == callingUserId) {
2007 userInfo = getUserInfoLocked(userHandle);
2008 }
2009 }
2010 }
2011 if (userInfo == null) {
2012 throw new SecurityException("userHandle can only be the calling user or a managed "
2013 + "profile associated with this user");
2014 }
2015 return userInfo.creationTime;
2016 }
2017
Amith Yamasani0b285492011-04-14 17:35:23 -07002018 /**
2019 * Caches the list of user ids in an array, adjusting the array size when necessary.
2020 */
Amith Yamasani13593602012-03-22 16:16:17 -07002021 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002022 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002023 final int userSize = mUsers.size();
2024 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002025 if (!mUsers.valueAt(i).partial) {
2026 num++;
2027 }
2028 }
Amith Yamasani16389312012-10-17 21:20:14 -07002029 final int[] newUsers = new int[num];
2030 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002031 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002032 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07002033 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002034 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002035 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002036 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002037 }
2038
2039 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002040 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002041 * @param userId the user that was just foregrounded
2042 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002043 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002044 synchronized (mPackagesLock) {
2045 UserInfo user = mUsers.get(userId);
2046 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002047 if (user == null || user.partial) {
2048 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2049 return;
2050 }
2051 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002052 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002053 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002054 }
2055 }
2056 }
2057
2058 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002059 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002060 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2061 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002062 * @return
2063 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002064 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07002065 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002066 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002067 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002068 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002069 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002070 }
2071 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002072 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002073 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002074 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002075 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002076
Amith Yamasanifc95e702013-09-26 13:20:17 -07002077 private String packageToRestrictionsFileName(String packageName) {
2078 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2079 }
2080
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002081 /**
2082 * Create new {@code /data/user/[id]} directory and sets default
2083 * permissions.
2084 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002085 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2086 final StorageManager storage = context.getSystemService(StorageManager.class);
2087 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2088 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002089 }
2090
2091 /**
2092 * Enforce that serial number stored in user directory inode matches the
2093 * given expected value. Gracefully sets the serial number if currently
2094 * undefined.
2095 *
2096 * @throws IOException when problem extracting serial number, or serial
2097 * number is mismatched.
2098 */
2099 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2100 final int foundSerial = getSerialNumber(file);
2101 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2102
2103 if (foundSerial == -1) {
2104 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2105 try {
2106 setSerialNumber(file, serialNumber);
2107 } catch (IOException e) {
2108 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2109 }
2110
2111 } else if (foundSerial != serialNumber) {
2112 throw new IOException("Found serial number " + foundSerial
2113 + " doesn't match expected " + serialNumber);
2114 }
2115 }
2116
2117 /**
2118 * Set serial number stored in user directory inode.
2119 *
2120 * @throws IOException if serial number was already set
2121 */
2122 private static void setSerialNumber(File file, int serialNumber)
2123 throws IOException {
2124 try {
2125 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2126 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2127 } catch (ErrnoException e) {
2128 throw e.rethrowAsIOException();
2129 }
2130 }
2131
2132 /**
2133 * Return serial number stored in user directory inode.
2134 *
2135 * @return parsed serial number, or -1 if not set
2136 */
2137 private static int getSerialNumber(File file) throws IOException {
2138 try {
2139 final byte[] buf = new byte[256];
2140 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2141 final String serial = new String(buf, 0, len);
2142 try {
2143 return Integer.parseInt(serial);
2144 } catch (NumberFormatException e) {
2145 throw new IOException("Bad serial number: " + serial);
2146 }
2147 } catch (ErrnoException e) {
2148 if (e.errno == OsConstants.ENODATA) {
2149 return -1;
2150 } else {
2151 throw e.rethrowAsIOException();
2152 }
2153 }
2154 }
2155
Amith Yamasani920ace02012-09-20 22:15:37 -07002156 @Override
2157 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2158 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2159 != PackageManager.PERMISSION_GRANTED) {
2160 pw.println("Permission Denial: can't dump UserManager from from pid="
2161 + Binder.getCallingPid()
2162 + ", uid=" + Binder.getCallingUid()
2163 + " without permission "
2164 + android.Manifest.permission.DUMP);
2165 return;
2166 }
2167
2168 long now = System.currentTimeMillis();
2169 StringBuilder sb = new StringBuilder();
2170 synchronized (mPackagesLock) {
2171 pw.println("Users:");
2172 for (int i = 0; i < mUsers.size(); i++) {
2173 UserInfo user = mUsers.valueAt(i);
2174 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002175 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002176 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002177 if (user.partial) pw.print(" <partial>");
2178 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002179 pw.print(" Created: ");
2180 if (user.creationTime == 0) {
2181 pw.println("<unknown>");
2182 } else {
2183 sb.setLength(0);
2184 TimeUtils.formatDuration(now - user.creationTime, sb);
2185 sb.append(" ago");
2186 pw.println(sb);
2187 }
2188 pw.print(" Last logged in: ");
2189 if (user.lastLoggedInTime == 0) {
2190 pw.println("<unknown>");
2191 } else {
2192 sb.setLength(0);
2193 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2194 sb.append(" ago");
2195 pw.println(sb);
2196 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002197 pw.println(" Restrictions:");
2198 UserRestrictionsUtils.dumpRestrictions(
Makoto Onuki068c54a2015-10-13 14:34:03 -07002199 pw, " ", mBaseUserRestrictions.get(user.id));
2200 pw.println(" Effective restrictions:");
2201 UserRestrictionsUtils.dumpRestrictions(
2202 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002203 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002204 pw.println();
2205 pw.println("Guest restrictions:");
2206 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002207 }
2208 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002209
2210 final class MainHandler extends Handler {
2211
2212 @Override
2213 public void handleMessage(Message msg) {
2214 switch (msg.what) {
2215 case WRITE_USER_MSG:
2216 removeMessages(WRITE_USER_MSG, msg.obj);
2217 synchronized (mPackagesLock) {
2218 int userId = ((UserInfo) msg.obj).id;
2219 UserInfo userInfo = mUsers.get(userId);
2220 if (userInfo != null) {
2221 writeUserLocked(userInfo);
2222 }
2223 }
2224 }
2225 }
2226 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002227
2228 /**
2229 * @param userId
2230 * @return whether the user has been initialized yet
2231 */
2232 boolean isInitialized(int userId) {
2233 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2234 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002235
2236 private class LocalService extends UserManagerInternal {
2237
2238 @Override
2239 public Object getUserRestrictionsLock() {
2240 return mRestrictionsLock;
2241 }
2242
2243 @Override
2244 @GuardedBy("mRestrictionsLock")
2245 public void updateEffectiveUserRestrictionsRL(int userId) {
2246 UserManagerService.this.updateEffectiveUserRestrictionsRL(userId);
2247 }
2248
2249 @Override
2250 @GuardedBy("mRestrictionsLock")
2251 public void updateEffectiveUserRestrictionsForAllUsersRL() {
2252 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersRL();
2253 }
2254
2255 @Override
2256 public Bundle getBaseUserRestrictions(int userId) {
2257 synchronized (mRestrictionsLock) {
2258 return mBaseUserRestrictions.get(userId);
2259 }
2260 }
2261
2262 @Override
2263 public void setBaseUserRestrictionsByDpmsForMigration(
2264 int userId, Bundle baseRestrictions) {
2265 synchronized (mRestrictionsLock) {
2266 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2267 invalidateEffectiveUserRestrictionsRL(userId);
2268 }
2269
2270 synchronized (mPackagesLock) {
2271 final UserInfo userInfo = mUsers.get(userId);
2272 if (userInfo != null) {
2273 writeUserLocked(userInfo);
2274 } else {
2275 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2276 }
2277 }
2278 }
2279 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002280}