blob: ebb69bf7d7ca4b50d4564f252ef876693e0d3a20 [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;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070027import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070028import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010051import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070053import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070054import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010055import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070056import android.os.storage.VolumeInfo;
57import android.system.ErrnoException;
58import android.system.Os;
59import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070060import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070061import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Slog;
63import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Xml;
67
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040070import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070074import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.BufferedOutputStream;
81import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileOutputStream;
86import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.util.ArrayList;
90import java.util.List;
91
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import libcore.io.IoUtils;
93
Makoto Onuki068c54a2015-10-13 14:34:03 -070094/**
95 * Service for {@link UserManager}.
96 *
97 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070098 * <ul>
99 * <li> Methods suffixed with "LILP" should be called within {@link #mInstallLock} and
100 * {@link #mPackagesLock} locks obtained in the respective order.
101 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
102 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
103 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700104 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700105public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700106 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki068c54a2015-10-13 14:34:03 -0700107 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700113 private static final String ATTR_CREATION_TIME = "created";
114 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String ATTR_SERIAL_NO = "serialNumber";
116 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700117 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700118 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100120 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700121 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530122 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800125 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String TAG_ENTRY = "entry";
127 private static final String TAG_VALUE = "value";
128 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700129 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
133 private static final String ATTR_TYPE_STRING = "s";
134 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700135 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700136 private static final String ATTR_TYPE_BUNDLE = "B";
137 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700138
Amith Yamasani0b285492011-04-14 17:35:23 -0700139 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700141 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100142 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700145 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146
Amith Yamasani634cf312012-10-04 17:34:21 -0700147 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700148 // We need to keep process uid within Integer.MAX_VALUE.
149 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700150
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700151 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700152
Amith Yamasani920ace02012-09-20 22:15:37 -0700153 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
154
Nicolas Prevotb8186812015-08-06 15:00:03 +0100155 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700156 // without first making sure that the rest of the framework is prepared for it.
157 private static final int MAX_MANAGED_PROFILES = 1;
158
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800159 static final int WRITE_USER_MSG = 1;
160 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700162 private static final String XATTR_SERIAL = "user.serial";
163
Dianne Hackborn4428e172012-08-24 17:43:05 -0700164 private final Context mContext;
165 private final PackageManagerService mPm;
166 private final Object mInstallLock;
167 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700168 // Short-term lock for internal state, when interaction/sync with PM is not required
169 private final Object mUsersLock = new Object();
170 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800172 private final Handler mHandler;
173
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174 private final File mUsersDir;
175 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Fyodor Kupolov82402752015-10-28 14:54:51 -0700177 @GuardedBy("mUsersLock")
178 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700179
180 /**
181 * User restrictions set via UserManager. This doesn't include restrictions set by
182 * device owner / profile owners.
183 *
184 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
185 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
186 * maybe shared between {@link #mBaseUserRestrictions} and
187 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
188 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700189 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700190 */
191 @GuardedBy("mRestrictionsLock")
192 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
193
194 /**
195 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
196 * with device / profile owner restrictions. We'll initialize it lazily; use
197 * {@link #getEffectiveUserRestrictions} to access it.
198 *
199 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
200 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
201 * maybe shared between {@link #mBaseUserRestrictions} and
202 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
203 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700204 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700205 */
206 @GuardedBy("mRestrictionsLock")
207 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
208
Makoto Onuki4f160732015-10-27 17:15:38 -0700209 /**
Fyodor Kupolov82402752015-10-28 14:54:51 -0700210 * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}. We
Makoto Onuki4f160732015-10-27 17:15:38 -0700211 * use it to detect restrictions that have changed since the last
Fyodor Kupolov82402752015-10-28 14:54:51 -0700212 * {@link #applyUserRestrictionsLR} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700213 */
214 @GuardedBy("mRestrictionsLock")
215 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
216
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530217 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800218
219 /**
220 * Set of user IDs being actively removed. Removed IDs linger in this set
221 * for several seconds to work around a VFS caching issue.
222 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700223 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800224 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225
Fyodor Kupolov82402752015-10-28 14:54:51 -0700226 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700227 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700228 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700229 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700230
Jason Monk62062992014-05-06 09:55:28 -0400231 private IAppOpsService mAppOpsService;
232
Makoto Onuki068c54a2015-10-13 14:34:03 -0700233 private final LocalService mLocalService;
234
Amith Yamasani258848d2012-08-10 17:06:33 -0700235 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700236
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237 public static UserManagerService getInstance() {
238 synchronized (UserManagerService.class) {
239 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700241 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700242
243 /**
244 * Available for testing purposes.
245 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700246 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248 }
249
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250 /**
251 * Called by package manager to create the service. This is closely
252 * associated with the package manager, and the given lock is the
253 * package manager's own lock.
254 */
255 UserManagerService(Context context, PackageManagerService pm,
256 Object installLock, Object packagesLock) {
257 this(context, pm, installLock, packagesLock,
258 Environment.getDataDirectory(),
259 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700260 }
261
Dianne Hackborn4428e172012-08-24 17:43:05 -0700262 /**
263 * Available for testing purposes.
264 */
265 private UserManagerService(Context context, PackageManagerService pm,
266 Object installLock, Object packagesLock,
267 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 mContext = context;
269 mPm = pm;
270 mInstallLock = installLock;
271 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800272 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 synchronized (mInstallLock) {
274 synchronized (mPackagesLock) {
275 mUsersDir = new File(dataDir, USER_INFO_DIR);
276 mUsersDir.mkdirs();
277 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700278 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700279 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700280 FileUtils.setPermissions(mUsersDir.toString(),
281 FileUtils.S_IRWXU|FileUtils.S_IRWXG
282 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
283 -1, -1);
284 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800285 initDefaultGuestRestrictions();
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 readUserListLILP();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700287 sInstance = this;
288 }
289 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700290 mLocalService = new LocalService();
291 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700292 }
293
294 void systemReady() {
295 synchronized (mInstallLock) {
296 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700297 synchronized (mUsersLock) {
298 // Prune out any partially created/partially removed users.
299 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
300 final int userSize = mUsers.size();
301 for (int i = 0; i < userSize; i++) {
302 UserInfo ui = mUsers.valueAt(i);
303 if ((ui.partial || ui.guestToRemove) && i != 0) {
304 partials.add(ui);
305 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700306 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700307 final int partialsSize = partials.size();
308 for (int i = 0; i < partialsSize; i++) {
309 UserInfo ui = partials.get(i);
310 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
311 + " (name=" + ui.name + ")");
312 removeUserStateLILP(ui.id);
313 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700314 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700315 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700316 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700317 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400318 mAppOpsService = IAppOpsService.Stub.asInterface(
319 ServiceManager.getService(Context.APP_OPS_SERVICE));
320 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700321 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400322 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700323 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400324 } catch (RemoteException e) {
325 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
326 }
327 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700328 }
329
330 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700331 public UserInfo getPrimaryUser() {
332 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700333 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700334 final int userSize = mUsers.size();
335 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700336 UserInfo ui = mUsers.valueAt(i);
337 if (ui.isPrimary()) {
338 return ui;
339 }
340 }
341 }
342 return null;
343 }
344
345 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700346 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700347 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700348 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700349 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700350 final int userSize = mUsers.size();
351 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700352 UserInfo ui = mUsers.valueAt(i);
353 if (ui.partial) {
354 continue;
355 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800356 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700357 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700358 }
Amith Yamasani13593602012-03-22 16:16:17 -0700359 }
360 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700361 }
Amith Yamasani13593602012-03-22 16:16:17 -0700362 }
363
Amith Yamasani258848d2012-08-10 17:06:33 -0700364 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100365 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800366 if (userId != UserHandle.getCallingUserId()) {
367 checkManageUsersPermission("getting profiles related to user " + userId);
368 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700369 final long ident = Binder.clearCallingIdentity();
370 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700371 synchronized (mUsersLock) {
372 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100373 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700374 } finally {
375 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000376 }
377 }
378
Amith Yamasanibe465322014-04-24 13:45:17 -0700379 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700380 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
381 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700382 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700383 if (user == null) {
384 // Probably a dying user
385 return users;
386 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700387 final int userSize = mUsers.size();
388 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700389 UserInfo profile = mUsers.valueAt(i);
390 if (!isProfileOf(user, profile)) {
391 continue;
392 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100393 if (enabledOnly && !profile.isEnabled()) {
394 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700395 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700396 if (mRemovingUserIds.get(profile.id)) {
397 continue;
398 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700399 users.add(profile);
400 }
401 return users;
402 }
403
Jessica Hummelbe81c802014-04-22 15:49:22 +0100404 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700405 public int getCredentialOwnerProfile(int userHandle) {
406 checkManageUsersPermission("get the credential owner");
Clara Bayarrif05b9d02015-10-23 13:25:19 +0100407 if (!"file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700408 synchronized (mUsersLock) {
409 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700410 if (profileParent != null) {
411 return profileParent.id;
412 }
413 }
414 }
415
416 return userHandle;
417 }
418
419 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700420 public boolean isSameProfileGroup(int userId, int otherUserId) {
421 if (userId == otherUserId) return true;
422 checkManageUsersPermission("check if in the same profile group");
423 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700424 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700425 }
426 }
427
Fyodor Kupolov82402752015-10-28 14:54:51 -0700428 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
429 synchronized (mUsersLock) {
430 UserInfo userInfo = getUserInfoLU(userId);
431 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
432 return false;
433 }
434 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
435 if (otherUserInfo == null
436 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
437 return false;
438 }
439 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700440 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700441 }
442
443 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100444 public UserInfo getProfileParent(int userHandle) {
445 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700446 synchronized (mUsersLock) {
447 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700448 }
449 }
450
Fyodor Kupolov82402752015-10-28 14:54:51 -0700451 private UserInfo getProfileParentLU(int userHandle) {
452 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700453 if (profile == null) {
454 return null;
455 }
456 int parentUserId = profile.profileGroupId;
457 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
458 return null;
459 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700460 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100461 }
462 }
463
Fyodor Kupolov82402752015-10-28 14:54:51 -0700464 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100465 return user.id == profile.id ||
466 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
467 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000468 }
469
470 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100471 public void setUserEnabled(int userId) {
472 checkManageUsersPermission("enable user");
473 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700474 UserInfo info;
475 synchronized (mUsersLock) {
476 info = getUserInfoLU(userId);
477 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100478 if (info != null && !info.isEnabled()) {
479 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700480 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100481 }
482 }
483 }
484
485 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700486 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700487 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700488 synchronized (mUsersLock) {
489 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700490 }
491 }
492
Amith Yamasani71e6c692013-03-24 17:39:28 -0700493 @Override
494 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700495 synchronized (mUsersLock) {
496 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700497 }
498 }
499
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700500 @Override
501 public boolean canHaveRestrictedProfile(int userId) {
502 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700503 synchronized (mUsersLock) {
504 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700505 if (userInfo == null || !userInfo.canHaveProfile()) {
506 return false;
507 }
508 if (!userInfo.isAdmin()) {
509 return false;
510 }
511 }
512 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
513 Context.DEVICE_POLICY_SERVICE);
514 // restricted profile can be created if there is no DO set and the admin user has no PO
515 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
516 }
517
Amith Yamasani195263742012-08-21 15:40:12 -0700518 /*
519 * Should be locked on mUsers before calling this.
520 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700521 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700522 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700523 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800524 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700525 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
526 return null;
527 }
528 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700529 }
530
Fyodor Kupolov82402752015-10-28 14:54:51 -0700531 /**
532 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
533 * <p>No permissions checking or any addition checks are made</p>
534 */
535 private UserInfo getUserInfoNoChecks(int userId) {
536 synchronized (mUsersLock) {
537 return mUsers.get(userId);
538 }
539 }
540
Amith Yamasani236b2b52015-08-18 14:32:14 -0700541 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700542 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700544 }
545
Amith Yamasani258848d2012-08-10 17:06:33 -0700546 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700547 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700548 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700549 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700550 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700551 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700552 if (info == null || info.partial) {
553 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
554 return;
555 }
Amith Yamasani13593602012-03-22 16:16:17 -0700556 if (name != null && !name.equals(info.name)) {
557 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700559 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700560 }
561 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700562 if (changed) {
563 sendUserInfoChangedBroadcast(userId);
564 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700565 }
566
Amith Yamasani258848d2012-08-10 17:06:33 -0700567 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700568 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700569 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400570 long ident = Binder.clearCallingIdentity();
571 try {
572 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700573 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400574 if (info == null || info.partial) {
575 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
576 return;
577 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 writeBitmapLP(info, bitmap);
579 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700580 }
Jason Monk9a944532014-07-08 09:31:21 -0400581 sendUserInfoChangedBroadcast(userId);
582 } finally {
583 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700584 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700585 }
586
587 private void sendUserInfoChangedBroadcast(int userId) {
588 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
589 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
590 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700591 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700592 }
593
Amith Yamasani258848d2012-08-10 17:06:33 -0700594 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100595 public ParcelFileDescriptor getUserIcon(int userId) {
596 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700597 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700598 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700599 if (info == null || info.partial) {
600 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
601 return null;
602 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100604 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
605 || callingGroupId != info.profileGroupId) {
606 checkManageUsersPermission("get the icon of a user who is not related");
607 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700608 if (info.iconPath == null) {
609 return null;
610 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100611 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700612 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100613
614 try {
615 return ParcelFileDescriptor.open(
616 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
617 } catch (FileNotFoundException e) {
618 Log.e(LOG_TAG, "Couldn't find icon file", e);
619 }
620 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700621 }
622
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700623 public void makeInitialized(int userId) {
624 checkManageUsersPermission("makeInitialized");
625 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700626 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700627 if (info == null || info.partial) {
628 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700629 // TODO Check if we should return here instead of a null check below
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700630 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700632 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700633 scheduleWriteUserLP(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700634 }
635 }
636 }
637
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700638 /**
639 * If default guest restrictions haven't been initialized yet, add the basic
640 * restrictions.
641 */
642 private void initDefaultGuestRestrictions() {
643 if (mGuestRestrictions.isEmpty()) {
644 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800645 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700646 }
647 }
648
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800649 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530650 public Bundle getDefaultGuestRestrictions() {
651 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700652 // TODO Switch to mGuestRestrictions for locking
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530653 synchronized (mPackagesLock) {
654 return new Bundle(mGuestRestrictions);
655 }
656 }
657
658 @Override
659 public void setDefaultGuestRestrictions(Bundle restrictions) {
660 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 synchronized (mInstallLock) {
662 synchronized (mPackagesLock) {
663 mGuestRestrictions.clear();
664 mGuestRestrictions.putAll(restrictions);
665 writeUserListLILP();
666 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530667 }
668 }
669
Makoto Onuki068c54a2015-10-13 14:34:03 -0700670 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700671 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700672 final DevicePolicyManagerInternal dpmi =
673 LocalServices.getService(DevicePolicyManagerInternal.class);
674 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
675
676 final Bundle effective;
677 if (dpmi == null) {
678 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
679 effective = systemRestrictions;
680 } else {
681 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
682 }
683 return effective;
684 }
685
686 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700687 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700688 if (DBG) {
689 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
690 }
691 mCachedEffectiveUserRestrictions.remove(userId);
692 }
693
694 private Bundle getEffectiveUserRestrictions(int userId) {
695 synchronized (mRestrictionsLock) {
696 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
697 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700699 mCachedEffectiveUserRestrictions.put(userId, restrictions);
700 }
701 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700702 }
703 }
704
Makoto Onuki068c54a2015-10-13 14:34:03 -0700705 /** @return a specific user restriction that's in effect currently. */
706 @Override
707 public boolean hasUserRestriction(String restrictionKey, int userId) {
708 Bundle restrictions = getEffectiveUserRestrictions(userId);
709 return restrictions != null && restrictions.getBoolean(restrictionKey);
710 }
711
712 /**
713 * @return UserRestrictions that are in effect currently. This always returns a new
714 * {@link Bundle}.
715 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700716 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800717 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700718 Bundle restrictions = getEffectiveUserRestrictions(userId);
719 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800720 }
721
722 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700723 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700724 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700725 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
726 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700727 }
728 }
729
730 @Override
731 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
732 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700733 setUserRestrictionNoCheck(key, value, userId);
734 }
735
736 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
737 synchronized (mRestrictionsLock) {
738 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
739 // a copy.
740 final Bundle newRestrictions = new Bundle();
741 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
742 newRestrictions.putBoolean(key, value);
743
Fyodor Kupolov82402752015-10-28 14:54:51 -0700744 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700745 }
746 }
747
Makoto Onuki068c54a2015-10-13 14:34:03 -0700748 /**
749 * Optionally updating user restrictions, calculate the effective user restrictions by
750 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
751 * apply it to {@link com.android.server.AppOpsService}.
752 * TODO applyUserRestrictionsLocked() should also apply to system settings.
753 *
754 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
755 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
756 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
757 * @param userId target user ID.
758 */
759 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700760 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700761 @Nullable Bundle newRestrictions, int userId) {
762 if (DBG) {
763 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
764 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800765 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700766 // Update system restrictions.
767 if (newRestrictions != null) {
768 // If newRestrictions == the current one, it's probably a bug.
769 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
770 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
771 != newRestrictions);
772 mBaseUserRestrictions.put(userId, newRestrictions);
773 }
774
Fyodor Kupolov82402752015-10-28 14:54:51 -0700775 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700776
Makoto Onuki759a7632015-10-28 16:43:10 -0700777 mCachedEffectiveUserRestrictions.put(userId, effective);
778
Fyodor Kupolov82402752015-10-28 14:54:51 -0700779 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800780 }
781
Makoto Onuki068c54a2015-10-13 14:34:03 -0700782 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700783 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onuki4f160732015-10-27 17:15:38 -0700784 final Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
785
786 if (DBG) {
787 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
788 + " new=" + newRestrictions + " prev=" + prevRestrictions);
789 }
790
Makoto Onuki068c54a2015-10-13 14:34:03 -0700791 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700792 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700793 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700794 } catch (RemoteException e) {
795 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
796 } finally {
797 Binder.restoreCallingIdentity(token);
798 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700799
Makoto Onuki4f160732015-10-27 17:15:38 -0700800 UserRestrictionsUtils.applyUserRestrictions(
801 mContext, userId, newRestrictions, prevRestrictions);
802
803 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 }
805
806 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700807 private void updateEffectiveUserRestrictionsLR(int userId) {
808 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700809 }
810
811 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700812 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700813 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700814 mCachedEffectiveUserRestrictions.clear();
815
Makoto Onuki068c54a2015-10-13 14:34:03 -0700816 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
817 // it on a handler.
818 final Runnable r = new Runnable() {
819 @Override
820 public void run() {
821 // Then get the list of running users.
822 final int[] runningUsers;
823 try {
824 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
825 } catch (RemoteException e) {
826 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
827 return;
828 }
829 // Then re-calculate the effective restrictions and apply, only for running users.
830 // It's okay if a new user has started after the getRunningUserIds() call,
831 // because we'll do the same thing (re-calculate the restrictions and apply)
832 // when we start a user.
833 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
834 synchronized (mRestrictionsLock) {
835 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700836 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700837 }
838 }
839 }
840 };
841 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700842 }
843
Amith Yamasani258848d2012-08-10 17:06:33 -0700844 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700845 * Check if we've hit the limit of how many users can be created.
846 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700847 private boolean isUserLimitReached() {
848 int count;
849 synchronized (mUsersLock) {
850 count = getAliveUsersExcludingGuestsCountLU();
851 }
852 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700853 }
854
855 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000856 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700857 checkManageUsersPermission("check if more managed profiles can be added.");
858 if (ActivityManager.isLowRamDeviceStatic()) {
859 return false;
860 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700861 if (!mContext.getPackageManager().hasSystemFeature(
862 PackageManager.FEATURE_MANAGED_USERS)) {
863 return false;
864 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100865 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000866 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
867 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
868 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100869 return false;
870 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700871 synchronized(mUsersLock) {
872 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100873 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700874 return false;
875 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000876 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
877 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700878 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000879 return usersCountAfterRemoving == 1
880 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700881 }
882 }
883
Fyodor Kupolov82402752015-10-28 14:54:51 -0700884 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700885 int aliveUserCount = 0;
886 final int totalUserCount = mUsers.size();
887 // Skip over users being removed
888 for (int i = 0; i < totalUserCount; i++) {
889 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700890 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700891 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700892 aliveUserCount++;
893 }
894 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700895 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700896 }
897
898 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700899 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700900 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700901 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700902 *
903 * @param message used as message if SecurityException is thrown
904 * @throws SecurityException if the caller is not system or root
905 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700906 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700907 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700908 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400909 && ActivityManager.checkComponentPermission(
910 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700911 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
912 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
913 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400914 }
915
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700916 private static void checkSystemOrRoot(String message) {
917 final int uid = Binder.getCallingUid();
918 if (uid != Process.SYSTEM_UID && uid != 0) {
919 throw new SecurityException("Only system may call: " + message);
920 }
921 }
922
Fyodor Kupolov82402752015-10-28 14:54:51 -0700923 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700924 try {
925 File dir = new File(mUsersDir, Integer.toString(info.id));
926 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100927 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700928 if (!dir.exists()) {
929 dir.mkdir();
930 FileUtils.setPermissions(
931 dir.getPath(),
932 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
933 -1, -1);
934 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700935 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100936 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
937 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700938 info.iconPath = file.getAbsolutePath();
939 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700940 try {
941 os.close();
942 } catch (IOException ioe) {
943 // What the ... !
944 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100945 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700946 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700947 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700948 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700949 }
950
Amith Yamasani0b285492011-04-14 17:35:23 -0700951 /**
952 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
953 * cache it elsewhere.
954 * @return the array of user ids.
955 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700956 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700957 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700958 return mUserIds;
959 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700960 }
961
Fyodor Kupolov82402752015-10-28 14:54:51 -0700962 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700964 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700965 return;
966 }
967 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700968 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700969 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700970 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700971 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100972 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700973 int type;
974 while ((type = parser.next()) != XmlPullParser.START_TAG
975 && type != XmlPullParser.END_DOCUMENT) {
976 ;
977 }
978
979 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700980 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700981 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700982 return;
983 }
984
Amith Yamasani2a003292012-08-14 18:25:45 -0700985 mNextSerialNumber = -1;
986 if (parser.getName().equals(TAG_USERS)) {
987 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
988 if (lastSerialNumber != null) {
989 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
990 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700991 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
992 if (versionNumber != null) {
993 mUserVersion = Integer.parseInt(versionNumber);
994 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700995 }
996
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700997 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530998 if (type == XmlPullParser.START_TAG) {
999 final String name = parser.getName();
1000 if (name.equals(TAG_USER)) {
1001 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001002 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001003
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301004 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001005 synchronized (mUsersLock) {
1006 mUsers.put(user.id, user);
1007 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1008 mNextSerialNumber = user.id + 1;
1009 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301010 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001011 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301012 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001013 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1014 && type != XmlPullParser.END_TAG) {
1015 if (type == XmlPullParser.START_TAG) {
1016 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001017 UserRestrictionsUtils
1018 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001019 }
1020 break;
1021 }
1022 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001023 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001024 }
1025 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001026 updateUserIds();
1027 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001028 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001029 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001030 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001031 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001032 } finally {
1033 if (fis != null) {
1034 try {
1035 fis.close();
1036 } catch (IOException e) {
1037 }
1038 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 }
1040 }
1041
Amith Yamasani6f34b412012-10-22 18:19:27 -07001042 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001043 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001044 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001046 int userVersion = mUserVersion;
1047 if (userVersion < 1) {
1048 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001049 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001050 if ("Primary".equals(user.name)) {
1051 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001052 scheduleWriteUserLP(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001053 }
1054 userVersion = 1;
1055 }
1056
Amith Yamasanibc9625052012-11-15 14:39:18 -08001057 if (userVersion < 2) {
1058 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001059 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001060 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1061 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001062 scheduleWriteUserLP(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001063 }
1064 userVersion = 2;
1065 }
1066
Amith Yamasani350962c2013-08-06 11:18:53 -07001067
Amith Yamasani5e486f52013-08-07 11:06:44 -07001068 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001069 userVersion = 4;
1070 }
1071
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001072 if (userVersion < 5) {
1073 initDefaultGuestRestrictions();
1074 userVersion = 5;
1075 }
1076
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001077 if (userVersion < 6) {
1078 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001079 synchronized (mUsersLock) {
1080 for (int i = 0; i < mUsers.size(); i++) {
1081 UserInfo user = mUsers.valueAt(i);
1082 // In non-split mode, only user 0 can have restricted profiles
1083 if (!splitSystemUser && user.isRestricted()
1084 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1085 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1086 scheduleWriteUserLP(user);
1087 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001088 }
1089 }
1090 userVersion = 6;
1091 }
1092
Amith Yamasani6f34b412012-10-22 18:19:27 -07001093 if (userVersion < USER_VERSION) {
1094 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1095 + USER_VERSION);
1096 } else {
1097 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001098 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001099 }
1100 }
1101
Fyodor Kupolov82402752015-10-28 14:54:51 -07001102 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001103 int flags = UserInfo.FLAG_INITIALIZED;
1104 // In split system user mode, the admin and primary flags are assigned to the first human
1105 // user.
1106 if (!UserManager.isSplitSystemUser()) {
1107 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1108 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001109 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001110 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001111 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001112 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001113 synchronized (mUsersLock) {
1114 mUsers.put(system.id, system);
1115 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001116 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001117 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001118
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001119 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001120 synchronized (mRestrictionsLock) {
1121 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1122 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001123
Fyodor Kupolov82402752015-10-28 14:54:51 -07001124 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001125 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126
Fyodor Kupolov82402752015-10-28 14:54:51 -07001127 writeUserListLILP();
1128 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001129 }
1130
Fyodor Kupolov82402752015-10-28 14:54:51 -07001131 private void scheduleWriteUserLP(UserInfo userInfo) {
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001132 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1133 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1134 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1135 }
1136 }
1137
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001138 /*
1139 * Writes the user file in this format:
1140 *
1141 * <user flags="20039023" id="0">
1142 * <name>Primary</name>
1143 * </user>
1144 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001145 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001146 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001147 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001148 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001149 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001150 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1151
1152 // XmlSerializer serializer = XmlUtils.serializerInstance();
1153 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001154 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001155 serializer.startDocument(null, true);
1156 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1157
1158 serializer.startTag(null, TAG_USER);
1159 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001160 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001161 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001162 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1163 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1164 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001165 if (userInfo.iconPath != null) {
1166 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1167 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001168 if (userInfo.partial) {
1169 serializer.attribute(null, ATTR_PARTIAL, "true");
1170 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001171 if (userInfo.guestToRemove) {
1172 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1173 }
Kenny Guy2a764942014-04-02 13:29:20 +01001174 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1175 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1176 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001177 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001178 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1179 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1180 Integer.toString(userInfo.restrictedProfileParentId));
1181 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001182 serializer.startTag(null, TAG_NAME);
1183 serializer.text(userInfo.name);
1184 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001185 Bundle restrictions;
1186 synchronized (mRestrictionsLock) {
1187 restrictions = mBaseUserRestrictions.get(userInfo.id);
1188 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001189 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001190 UserRestrictionsUtils
1191 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001192 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001193 serializer.endTag(null, TAG_USER);
1194
1195 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001196 userFile.finishWrite(fos);
1197 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001198 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001199 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 }
1201 }
1202
1203 /*
1204 * Writes the user list file in this format:
1205 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001206 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001207 * <user id="0"></user>
1208 * <user id="2"></user>
1209 * </users>
1210 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001211 private void writeUserListLILP() {
1212 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001213 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001214 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001215 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001216 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001217 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1218
1219 // XmlSerializer serializer = XmlUtils.serializerInstance();
1220 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001221 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001222 serializer.startDocument(null, true);
1223 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1224
1225 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001226 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001227 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001228
Adam Lesinskieddeb492014-09-08 17:50:03 -07001229 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001230 UserRestrictionsUtils
1231 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301232 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001233 int[] userIdsToWrite;
1234 synchronized (mUsersLock) {
1235 userIdsToWrite = new int[mUsers.size()];
1236 for (int i = 0; i < userIdsToWrite.length; i++) {
1237 UserInfo user = mUsers.valueAt(i);
1238 userIdsToWrite[i] = user.id;
1239 }
1240 }
1241 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001242 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001243 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001244 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001245 }
1246
1247 serializer.endTag(null, TAG_USERS);
1248
1249 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 userListFile.finishWrite(fos);
1251 } catch (Exception e) {
1252 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001253 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 }
1255 }
1256
Fyodor Kupolov82402752015-10-28 14:54:51 -07001257 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001258 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001261 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001262 long creationTime = 0L;
1263 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001264 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001265 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001266 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001267 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001268 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001269
1270 FileInputStream fis = null;
1271 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001272 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001273 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001274 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001275 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001276 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001277 int type;
1278 while ((type = parser.next()) != XmlPullParser.START_TAG
1279 && type != XmlPullParser.END_DOCUMENT) {
1280 ;
1281 }
1282
1283 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001284 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001285 return null;
1286 }
1287
1288 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001289 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1290 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001291 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001292 return null;
1293 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001294 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1295 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001296 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001297 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1298 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001299 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1300 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001301 restrictedProfileParentId = readIntAttribute(parser,
1302 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001303 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1304 if ("true".equals(valueString)) {
1305 partial = true;
1306 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001307 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1308 if ("true".equals(valueString)) {
1309 guestToRemove = true;
1310 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001312 int outerDepth = parser.getDepth();
1313 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1314 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1315 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1316 continue;
1317 }
1318 String tag = parser.getName();
1319 if (TAG_NAME.equals(tag)) {
1320 type = parser.next();
1321 if (type == XmlPullParser.TEXT) {
1322 name = parser.getText();
1323 }
1324 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001325 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326 }
1327 }
1328 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001329
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001330 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001331 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001332 userInfo.creationTime = creationTime;
1333 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001334 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001335 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001336 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001337 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001338 synchronized (mRestrictionsLock) {
1339 mBaseUserRestrictions.append(id, restrictions);
1340 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001341 return userInfo;
1342
1343 } catch (IOException ioe) {
1344 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001345 } finally {
1346 if (fis != null) {
1347 try {
1348 fis.close();
1349 } catch (IOException e) {
1350 }
1351 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001352 }
1353 return null;
1354 }
1355
Amith Yamasani920ace02012-09-20 22:15:37 -07001356 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1357 String valueString = parser.getAttributeValue(null, attr);
1358 if (valueString == null) return defaultValue;
1359 try {
1360 return Integer.parseInt(valueString);
1361 } catch (NumberFormatException nfe) {
1362 return defaultValue;
1363 }
1364 }
1365
1366 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1367 String valueString = parser.getAttributeValue(null, attr);
1368 if (valueString == null) return defaultValue;
1369 try {
1370 return Long.parseLong(valueString);
1371 } catch (NumberFormatException nfe) {
1372 return defaultValue;
1373 }
1374 }
1375
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001376 private boolean isPackageInstalled(String pkg, int userId) {
1377 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1378 PackageManager.GET_UNINSTALLED_PACKAGES,
1379 userId);
1380 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1381 return false;
1382 }
1383 return true;
1384 }
1385
Amith Yamasanib82add22013-07-09 11:24:44 -07001386 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001387 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001388 * Does not do any permissions checking.
1389 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001390 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001391 synchronized (mPackagesLock) {
1392 File dir = Environment.getUserSystemDirectory(userId);
1393 String[] files = dir.list();
1394 if (files == null) return;
1395 for (String fileName : files) {
1396 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1397 File resFile = new File(dir, fileName);
1398 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001399 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001400 }
1401 }
1402 }
1403 }
1404 }
1405
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001406 /**
1407 * Removes the app restrictions file for a specific package and user id, if it exists.
1408 */
1409 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1410 synchronized (mPackagesLock) {
1411 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001412 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001413 if (resFile.exists()) {
1414 resFile.delete();
1415 }
1416 }
1417 }
1418
Kenny Guya52dc3e2014-02-11 15:33:14 +00001419 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001420 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001421 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001422 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001423 }
1424
Amith Yamasani258848d2012-08-10 17:06:33 -07001425 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001426 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001427 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001428 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001429 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001430
Jessica Hummelbe81c802014-04-22 15:49:22 +01001431 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001432 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1433 UserManager.DISALLOW_ADD_USER, false)) {
1434 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1435 return null;
1436 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001437 if (ActivityManager.isLowRamDeviceStatic()) {
1438 return null;
1439 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001440 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001441 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001442 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001443 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001444 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001445 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001446 try {
1447 synchronized (mInstallLock) {
1448 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001449 UserInfo parent = null;
1450 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001451 synchronized (mUsersLock) {
1452 parent = getUserInfoLU(parentId);
1453 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001454 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001455 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001456 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001457 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001458 return null;
1459 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001460 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001461 // If we're not adding a guest user or a managed profile and the limit has
1462 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001463 return null;
1464 }
1465 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001466 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001467 return null;
1468 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001469 // In legacy mode, restricted profile's parent can only be the owner user
1470 if (isRestricted && !UserManager.isSplitSystemUser()
1471 && (parentId != UserHandle.USER_SYSTEM)) {
1472 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1473 return null;
1474 }
1475 if (isRestricted && UserManager.isSplitSystemUser()) {
1476 if (parent == null) {
1477 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1478 + "specified");
1479 return null;
1480 }
1481 if (!parent.canHaveProfile()) {
1482 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1483 + "created for the specified parent user id " + parentId);
1484 return null;
1485 }
1486 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001487 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001488 // And if there is no device owner, we also assign the admin flag to primary
1489 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001490 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001491 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001492 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001493 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1494 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1495 if (devicePolicyManager == null
1496 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001497 flags |= UserInfo.FLAG_ADMIN;
1498 }
1499 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001500 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001501 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001502 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001503 long now = System.currentTimeMillis();
1504 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001505 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001506 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001507 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001508 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001509 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001510 if (isManagedProfile) {
1511 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1512 parent.profileGroupId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001513 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001514 }
1515 userInfo.profileGroupId = parent.profileGroupId;
1516 } else if (isRestricted) {
1517 if (!parent.canHaveProfile()) {
1518 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1519 }
1520 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1521 parent.restrictedProfileParentId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001522 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001523 }
1524 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001525 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001526 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001527 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1528 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1529 final String volumeUuid = vol.getFsUuid();
1530 try {
1531 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1532 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001533 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001534 enforceSerialNumber(userDir, userInfo.serialNumber);
1535 } catch (IOException e) {
1536 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1537 }
1538 }
1539 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001540 userInfo.partial = false;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001541 scheduleWriteUserLP(userInfo);
1542 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001543 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001544 synchronized (mRestrictionsLock) {
1545 mBaseUserRestrictions.append(userId, restrictions);
1546 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001547 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001548 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001549 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001550 if (userInfo != null) {
1551 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1552 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1553 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1554 android.Manifest.permission.MANAGE_USERS);
1555 }
1556 } finally {
1557 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001558 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001559 return userInfo;
1560 }
1561
Amith Yamasani0b285492011-04-14 17:35:23 -07001562 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001563 * @hide
1564 */
1565 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1566 checkManageUsersPermission("setupRestrictedProfile");
1567 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1568 if (user == null) {
1569 return null;
1570 }
1571 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1572 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1573 // the putIntForUser() will fail.
1574 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1575 android.provider.Settings.Secure.LOCATION_MODE,
1576 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1577 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1578 return user;
1579 }
1580
1581 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001582 * Find the current guest user. If the Guest user is partial,
1583 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001584 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001585 private UserInfo findCurrentGuestUser() {
1586 synchronized (mUsersLock) {
1587 final int size = mUsers.size();
1588 for (int i = 0; i < size; i++) {
1589 final UserInfo user = mUsers.valueAt(i);
1590 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1591 return user;
1592 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001593 }
1594 }
1595 return null;
1596 }
1597
1598 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001599 * Mark this guest user for deletion to allow us to create another guest
1600 * and switch to that user before actually removing this guest.
1601 * @param userHandle the userid of the current guest
1602 * @return whether the user could be marked for deletion
1603 */
1604 public boolean markGuestForDeletion(int userHandle) {
1605 checkManageUsersPermission("Only the system can remove users");
1606 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1607 UserManager.DISALLOW_REMOVE_USER, false)) {
1608 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1609 return false;
1610 }
1611
1612 long ident = Binder.clearCallingIdentity();
1613 try {
1614 final UserInfo user;
1615 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001616 synchronized (mUsersLock) {
1617 user = mUsers.get(userHandle);
1618 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1619 return false;
1620 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001621 }
1622 if (!user.isGuest()) {
1623 return false;
1624 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001625 // We set this to a guest user that is to be removed. This is a temporary state
1626 // where we are allowed to add new Guest users, even if this one is still not
1627 // removed. This user will still show up in getUserInfo() calls.
1628 // If we don't get around to removing this Guest user, it will be purged on next
1629 // startup.
1630 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001631 // Mark it as disabled, so that it isn't returned any more when
1632 // profiles are queried.
1633 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001634 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001635 }
1636 } finally {
1637 Binder.restoreCallingIdentity(ident);
1638 }
1639 return true;
1640 }
1641
1642 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001643 * Removes a user and all data directories created for that user. This method should be called
1644 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001645 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001646 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001647 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001648 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001649 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1650 UserManager.DISALLOW_REMOVE_USER, false)) {
1651 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1652 return false;
1653 }
1654
Kenny Guyee58b4f2014-05-23 15:19:53 +01001655 long ident = Binder.clearCallingIdentity();
1656 try {
1657 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001658 int currentUser = ActivityManager.getCurrentUser();
1659 if (currentUser == userHandle) {
1660 Log.w(LOG_TAG, "Current user cannot be removed");
1661 return false;
1662 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001663 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001664 synchronized (mUsersLock) {
1665 user = mUsers.get(userHandle);
1666 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1667 return false;
1668 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001669
Fyodor Kupolov82402752015-10-28 14:54:51 -07001670 // We remember deleted user IDs to prevent them from being
1671 // reused during the current boot; they can still be reused
1672 // after a reboot.
1673 mRemovingUserIds.put(userHandle, true);
1674 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001675
Kenny Guyee58b4f2014-05-23 15:19:53 +01001676 try {
1677 mAppOpsService.removeUser(userHandle);
1678 } catch (RemoteException e) {
1679 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1680 }
1681 // Set this to a partially created user, so that the user will be purged
1682 // on next startup, in case the runtime stops now before stopping and
1683 // removing the user completely.
1684 user.partial = true;
1685 // Mark it as disabled, so that it isn't returned any more when
1686 // profiles are queried.
1687 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001688 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001689 }
1690
1691 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1692 && user.isManagedProfile()) {
1693 // Send broadcast to notify system that the user removed was a
1694 // managed user.
1695 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1696 }
1697
1698 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1699 int res;
1700 try {
1701 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1702 new IStopUserCallback.Stub() {
1703 @Override
1704 public void userStopped(int userId) {
1705 finishRemoveUser(userId);
1706 }
1707 @Override
1708 public void userStopAborted(int userId) {
1709 }
1710 });
1711 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001712 return false;
1713 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001714 return res == ActivityManager.USER_OP_SUCCESS;
1715 } finally {
1716 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001717 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001718 }
1719
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001720 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001721 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001722 // Let other services shutdown any activity and clean up their state before completely
1723 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001724 long ident = Binder.clearCallingIdentity();
1725 try {
1726 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1727 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001728 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1729 android.Manifest.permission.MANAGE_USERS,
1730
1731 new BroadcastReceiver() {
1732 @Override
1733 public void onReceive(Context context, Intent intent) {
1734 if (DBG) {
1735 Slog.i(LOG_TAG,
1736 "USER_REMOVED broadcast sent, cleaning up user data "
1737 + userHandle);
1738 }
1739 new Thread() {
1740 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001741 // Clean up any ActivityManager state
1742 LocalServices.getService(ActivityManagerInternal.class)
1743 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001744 synchronized (mInstallLock) {
1745 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001746 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001747 }
1748 }
1749 }
1750 }.start();
1751 }
1752 },
1753
1754 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001755 } finally {
1756 Binder.restoreCallingIdentity(ident);
1757 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001758 }
1759
Fyodor Kupolov82402752015-10-28 14:54:51 -07001760 private void removeUserStateLILP(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001761 mContext.getSystemService(StorageManager.class)
1762 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001763 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001764 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001765
1766 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001767 synchronized (mUsersLock) {
1768 mUsers.remove(userHandle);
1769 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001770 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001771 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001772 userFile.delete();
1773 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001774 writeUserListLILP();
1775 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001776 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1777 }
1778
Amith Yamasani61f57372012-08-31 12:12:28 -07001779 private void removeDirectoryRecursive(File parent) {
1780 if (parent.isDirectory()) {
1781 String[] files = parent.list();
1782 for (String filename : files) {
1783 File child = new File(parent, filename);
1784 removeDirectoryRecursive(child);
1785 }
1786 }
1787 parent.delete();
1788 }
1789
Kenny Guyf8d3a232014-05-15 16:09:52 +01001790 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001791 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001792 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1793 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001794 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1795 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001796 }
1797
Amith Yamasani2a003292012-08-14 18:25:45 -07001798 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001799 public Bundle getApplicationRestrictions(String packageName) {
1800 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1801 }
1802
1803 @Override
1804 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001805 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001806 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001807 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001808 }
1809 synchronized (mPackagesLock) {
1810 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001811 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001812 }
1813 }
1814
1815 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001816 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001817 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001818 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001819 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001820 if (restrictions == null || restrictions.isEmpty()) {
1821 cleanAppRestrictionsForPackage(packageName, userId);
1822 } else {
1823 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001824 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001825 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001826 }
Robin Lee66e5d962014-04-09 16:44:21 +01001827
Kenny Guyd21b2182014-07-17 16:38:55 +01001828 if (isPackageInstalled(packageName, userId)) {
1829 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1830 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1831 changeIntent.setPackage(packageName);
1832 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1833 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1834 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001835 }
1836
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001837 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001838 mHandler.post(new Runnable() {
1839 @Override
1840 public void run() {
1841 List<ApplicationInfo> apps =
1842 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1843 userHandle).getList();
1844 final long ident = Binder.clearCallingIdentity();
1845 try {
1846 for (ApplicationInfo appInfo : apps) {
1847 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001848 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1849 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001850 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001851 userHandle);
1852 }
1853 }
1854 } finally {
1855 Binder.restoreCallingIdentity(ident);
1856 }
1857 }
1858 });
1859 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001860 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001861 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001862 try {
1863 return mContext.getPackageManager().getApplicationInfo(packageName,
1864 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1865 } catch (NameNotFoundException nnfe) {
1866 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001867 } finally {
1868 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001869 }
1870 }
1871
Fyodor Kupolov82402752015-10-28 14:54:51 -07001872 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001873 AtomicFile restrictionsFile =
1874 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1875 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001877 }
1878
1879 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001880 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001881 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001882 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001883 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001884 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001885 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001886
1887 FileInputStream fis = null;
1888 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001889 fis = restrictionsFile.openRead();
1890 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001891 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001892 XmlUtils.nextElement(parser);
1893 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001894 Slog.e(LOG_TAG, "Unable to read restrictions file "
1895 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001896 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001897 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001898 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1899 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001901 } catch (IOException|XmlPullParserException e) {
1902 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001903 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001904 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001905 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001906 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001907 }
1908
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001909 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1910 XmlPullParser parser) throws XmlPullParserException, IOException {
1911 int type = parser.getEventType();
1912 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1913 String key = parser.getAttributeValue(null, ATTR_KEY);
1914 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1915 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1916 if (multiple != null) {
1917 values.clear();
1918 int count = Integer.parseInt(multiple);
1919 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1920 if (type == XmlPullParser.START_TAG
1921 && parser.getName().equals(TAG_VALUE)) {
1922 values.add(parser.nextText().trim());
1923 count--;
1924 }
1925 }
1926 String [] valueStrings = new String[values.size()];
1927 values.toArray(valueStrings);
1928 restrictions.putStringArray(key, valueStrings);
1929 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1930 restrictions.putBundle(key, readBundleEntry(parser, values));
1931 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1932 final int outerDepth = parser.getDepth();
1933 ArrayList<Bundle> bundleList = new ArrayList<>();
1934 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1935 Bundle childBundle = readBundleEntry(parser, values);
1936 bundleList.add(childBundle);
1937 }
1938 restrictions.putParcelableArray(key,
1939 bundleList.toArray(new Bundle[bundleList.size()]));
1940 } else {
1941 String value = parser.nextText().trim();
1942 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1943 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1944 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1945 restrictions.putInt(key, Integer.parseInt(value));
1946 } else {
1947 restrictions.putString(key, value);
1948 }
1949 }
1950 }
1951 }
1952
1953 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1954 throws IOException, XmlPullParserException {
1955 Bundle childBundle = new Bundle();
1956 final int outerDepth = parser.getDepth();
1957 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1958 readEntry(childBundle, values, parser);
1959 }
1960 return childBundle;
1961 }
1962
Fyodor Kupolov82402752015-10-28 14:54:51 -07001963 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001964 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001965 AtomicFile restrictionsFile = new AtomicFile(
1966 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001967 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001968 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001969 }
1970
1971 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001972 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001973 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001974 try {
1975 fos = restrictionsFile.startWrite();
1976 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1977
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001978 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001979 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001980 serializer.startDocument(null, true);
1981 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1982
1983 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001984 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001985 serializer.endTag(null, TAG_RESTRICTIONS);
1986
1987 serializer.endDocument();
1988 restrictionsFile.finishWrite(fos);
1989 } catch (Exception e) {
1990 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001991 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1992 }
1993 }
1994
1995 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1996 throws IOException {
1997 for (String key : restrictions.keySet()) {
1998 Object value = restrictions.get(key);
1999 serializer.startTag(null, TAG_ENTRY);
2000 serializer.attribute(null, ATTR_KEY, key);
2001
2002 if (value instanceof Boolean) {
2003 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2004 serializer.text(value.toString());
2005 } else if (value instanceof Integer) {
2006 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2007 serializer.text(value.toString());
2008 } else if (value == null || value instanceof String) {
2009 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2010 serializer.text(value != null ? (String) value : "");
2011 } else if (value instanceof Bundle) {
2012 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2013 writeBundle((Bundle) value, serializer);
2014 } else if (value instanceof Parcelable[]) {
2015 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2016 Parcelable[] array = (Parcelable[]) value;
2017 for (Parcelable parcelable : array) {
2018 if (!(parcelable instanceof Bundle)) {
2019 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2020 }
2021 serializer.startTag(null, TAG_ENTRY);
2022 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2023 writeBundle((Bundle) parcelable, serializer);
2024 serializer.endTag(null, TAG_ENTRY);
2025 }
2026 } else {
2027 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2028 String[] values = (String[]) value;
2029 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2030 for (String choice : values) {
2031 serializer.startTag(null, TAG_VALUE);
2032 serializer.text(choice != null ? choice : "");
2033 serializer.endTag(null, TAG_VALUE);
2034 }
2035 }
2036 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002037 }
2038 }
2039
2040 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002041 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002042 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002043 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002044 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002045 }
2046 }
2047
2048 @Override
2049 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002050 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002051 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002052 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002053 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002054 }
2055 // Not found
2056 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002057 }
2058 }
2059
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002060 @Override
2061 public long getUserCreationTime(int userHandle) {
2062 int callingUserId = UserHandle.getCallingUserId();
2063 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002064 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002065 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002067 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002068 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002069 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002070 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002071 }
2072 }
2073 }
2074 if (userInfo == null) {
2075 throw new SecurityException("userHandle can only be the calling user or a managed "
2076 + "profile associated with this user");
2077 }
2078 return userInfo.creationTime;
2079 }
2080
Amith Yamasani0b285492011-04-14 17:35:23 -07002081 /**
2082 * Caches the list of user ids in an array, adjusting the array size when necessary.
2083 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002084 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002085 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 synchronized (mUsersLock) {
2087 final int userSize = mUsers.size();
2088 for (int i = 0; i < userSize; i++) {
2089 if (!mUsers.valueAt(i).partial) {
2090 num++;
2091 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002092 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002093 final int[] newUsers = new int[num];
2094 int n = 0;
2095 for (int i = 0; i < userSize; i++) {
2096 if (!mUsers.valueAt(i).partial) {
2097 newUsers[n++] = mUsers.keyAt(i);
2098 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002099 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002100 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002101 }
2102 }
2103
2104 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002105 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002106 * @param userId the user that was just foregrounded
2107 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002108 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002109 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002110 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002111 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002112 if (user == null || user.partial) {
2113 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2114 return;
2115 }
2116 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002117 user.lastLoggedInTime = now;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002118 scheduleWriteUserLP(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002119 }
2120 }
2121 }
2122
2123 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002124 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002125 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2126 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002127 * @return
2128 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 private int getNextAvailableId() {
2130 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002131 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002132 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002133 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002134 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002135 }
2136 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002137 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002138 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002139 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002140 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002141
Amith Yamasanifc95e702013-09-26 13:20:17 -07002142 private String packageToRestrictionsFileName(String packageName) {
2143 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2144 }
2145
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002146 /**
2147 * Create new {@code /data/user/[id]} directory and sets default
2148 * permissions.
2149 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002150 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2151 final StorageManager storage = context.getSystemService(StorageManager.class);
2152 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2153 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002154 }
2155
2156 /**
2157 * Enforce that serial number stored in user directory inode matches the
2158 * given expected value. Gracefully sets the serial number if currently
2159 * undefined.
2160 *
2161 * @throws IOException when problem extracting serial number, or serial
2162 * number is mismatched.
2163 */
2164 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2165 final int foundSerial = getSerialNumber(file);
2166 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2167
2168 if (foundSerial == -1) {
2169 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2170 try {
2171 setSerialNumber(file, serialNumber);
2172 } catch (IOException e) {
2173 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2174 }
2175
2176 } else if (foundSerial != serialNumber) {
2177 throw new IOException("Found serial number " + foundSerial
2178 + " doesn't match expected " + serialNumber);
2179 }
2180 }
2181
2182 /**
2183 * Set serial number stored in user directory inode.
2184 *
2185 * @throws IOException if serial number was already set
2186 */
2187 private static void setSerialNumber(File file, int serialNumber)
2188 throws IOException {
2189 try {
2190 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2191 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2192 } catch (ErrnoException e) {
2193 throw e.rethrowAsIOException();
2194 }
2195 }
2196
2197 /**
2198 * Return serial number stored in user directory inode.
2199 *
2200 * @return parsed serial number, or -1 if not set
2201 */
2202 private static int getSerialNumber(File file) throws IOException {
2203 try {
2204 final byte[] buf = new byte[256];
2205 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2206 final String serial = new String(buf, 0, len);
2207 try {
2208 return Integer.parseInt(serial);
2209 } catch (NumberFormatException e) {
2210 throw new IOException("Bad serial number: " + serial);
2211 }
2212 } catch (ErrnoException e) {
2213 if (e.errno == OsConstants.ENODATA) {
2214 return -1;
2215 } else {
2216 throw e.rethrowAsIOException();
2217 }
2218 }
2219 }
2220
Amith Yamasani920ace02012-09-20 22:15:37 -07002221 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002222 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2223 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2224 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2225 }
2226
2227 int onShellCommand(Shell shell, String cmd) {
2228 if (cmd == null) {
2229 return shell.handleDefaultCommands(cmd);
2230 }
2231
2232 final PrintWriter pw = shell.getOutPrintWriter();
2233 try {
2234 switch(cmd) {
2235 case "list":
2236 return runList(pw);
2237 }
2238 } catch (RemoteException e) {
2239 pw.println("Remote exception: " + e);
2240 }
2241 return -1;
2242 }
2243
2244 private int runList(PrintWriter pw) throws RemoteException {
2245 final IActivityManager am = ActivityManagerNative.getDefault();
2246 final List<UserInfo> users = getUsers(false);
2247 if (users == null) {
2248 pw.println("Error: couldn't get users");
2249 return 1;
2250 } else {
2251 pw.println("Users:");
2252 for (int i = 0; i < users.size(); i++) {
2253 String running = am.isUserRunning(users.get(i).id, false) ? " running" : "";
2254 pw.println("\t" + users.get(i).toString() + running);
2255 }
2256 return 0;
2257 }
2258 }
2259
2260 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002261 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2262 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2263 != PackageManager.PERMISSION_GRANTED) {
2264 pw.println("Permission Denial: can't dump UserManager from from pid="
2265 + Binder.getCallingPid()
2266 + ", uid=" + Binder.getCallingUid()
2267 + " without permission "
2268 + android.Manifest.permission.DUMP);
2269 return;
2270 }
2271
2272 long now = System.currentTimeMillis();
2273 StringBuilder sb = new StringBuilder();
2274 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002275 synchronized (mUsersLock) {
2276 pw.println("Users:");
2277 for (int i = 0; i < mUsers.size(); i++) {
2278 UserInfo user = mUsers.valueAt(i);
2279 if (user == null) {
2280 continue;
2281 }
2282 pw.print(" "); pw.print(user);
2283 pw.print(" serialNo="); pw.print(user.serialNumber);
2284 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2285 pw.print(" <removing> ");
2286 }
2287 if (user.partial) {
2288 pw.print(" <partial>");
2289 }
2290 pw.println();
2291 pw.print(" Created: ");
2292 if (user.creationTime == 0) {
2293 pw.println("<unknown>");
2294 } else {
2295 sb.setLength(0);
2296 TimeUtils.formatDuration(now - user.creationTime, sb);
2297 sb.append(" ago");
2298 pw.println(sb);
2299 }
2300 pw.print(" Last logged in: ");
2301 if (user.lastLoggedInTime == 0) {
2302 pw.println("<unknown>");
2303 } else {
2304 sb.setLength(0);
2305 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2306 sb.append(" ago");
2307 pw.println(sb);
2308 }
2309 pw.println(" Restrictions:");
2310 synchronized (mRestrictionsLock) {
2311 UserRestrictionsUtils.dumpRestrictions(
2312 pw, " ", mBaseUserRestrictions.get(user.id));
2313 pw.println(" Effective restrictions:");
2314 UserRestrictionsUtils.dumpRestrictions(
2315 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2316 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002317 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002318 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002319 pw.println();
2320 pw.println("Guest restrictions:");
2321 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002322 }
2323 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002324
2325 final class MainHandler extends Handler {
2326
2327 @Override
2328 public void handleMessage(Message msg) {
2329 switch (msg.what) {
2330 case WRITE_USER_MSG:
2331 removeMessages(WRITE_USER_MSG, msg.obj);
2332 synchronized (mPackagesLock) {
2333 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002334 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002335 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002336 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002337 }
2338 }
2339 }
2340 }
2341 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002342
2343 /**
2344 * @param userId
2345 * @return whether the user has been initialized yet
2346 */
2347 boolean isInitialized(int userId) {
2348 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2349 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002350
2351 private class LocalService extends UserManagerInternal {
2352
2353 @Override
2354 public Object getUserRestrictionsLock() {
2355 return mRestrictionsLock;
2356 }
2357
2358 @Override
2359 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002360 public void updateEffectiveUserRestrictionsLR(int userId) {
2361 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002362 }
2363
2364 @Override
2365 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002366 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2367 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002368 }
2369
2370 @Override
2371 public Bundle getBaseUserRestrictions(int userId) {
2372 synchronized (mRestrictionsLock) {
2373 return mBaseUserRestrictions.get(userId);
2374 }
2375 }
2376
2377 @Override
2378 public void setBaseUserRestrictionsByDpmsForMigration(
2379 int userId, Bundle baseRestrictions) {
2380 synchronized (mRestrictionsLock) {
2381 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002382 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002383 }
2384
Fyodor Kupolov82402752015-10-28 14:54:51 -07002385 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002386 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002387 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002388 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002389 } else {
2390 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2391 }
2392 }
2393 }
2394 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002395
2396 private class Shell extends ShellCommand {
2397 @Override
2398 public int onCommand(String cmd) {
2399 return onShellCommand(this, cmd);
2400 }
2401
2402 @Override
2403 public void onHelp() {
2404 final PrintWriter pw = getOutPrintWriter();
2405 pw.println("User manager (user) commands:");
2406 pw.println(" help");
2407 pw.println(" Print this help text.");
2408 pw.println("");
2409 pw.println(" list");
2410 pw.println(" Prints all users on the system.");
2411 }
2412 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002413}