blob: c41d49359a665c7335366e276ed33af2a711c7f7 [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 Prevotb8186812015-08-06 15:00:03 +0100856 public boolean canAddMoreManagedProfiles(int userId) {
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
866 int managedProfilesCount = getProfiles(userId, true).size() - 1;
867 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
868 return false;
869 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700870 synchronized(mUsersLock) {
871 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100872 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700873 return false;
874 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700875 int usersCount = getAliveUsersExcludingGuestsCountLU();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700876 // We allow creating a managed profile in the special case where there is only one user.
877 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
878 }
879 }
880
Fyodor Kupolov82402752015-10-28 14:54:51 -0700881 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700882 int aliveUserCount = 0;
883 final int totalUserCount = mUsers.size();
884 // Skip over users being removed
885 for (int i = 0; i < totalUserCount; i++) {
886 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700887 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700888 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700889 aliveUserCount++;
890 }
891 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700892 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700893 }
894
895 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700896 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700897 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700898 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700899 *
900 * @param message used as message if SecurityException is thrown
901 * @throws SecurityException if the caller is not system or root
902 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700903 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700904 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700905 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400906 && ActivityManager.checkComponentPermission(
907 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700908 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
909 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
910 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400911 }
912
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700913 private static void checkSystemOrRoot(String message) {
914 final int uid = Binder.getCallingUid();
915 if (uid != Process.SYSTEM_UID && uid != 0) {
916 throw new SecurityException("Only system may call: " + message);
917 }
918 }
919
Fyodor Kupolov82402752015-10-28 14:54:51 -0700920 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700921 try {
922 File dir = new File(mUsersDir, Integer.toString(info.id));
923 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100924 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700925 if (!dir.exists()) {
926 dir.mkdir();
927 FileUtils.setPermissions(
928 dir.getPath(),
929 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
930 -1, -1);
931 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700932 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100933 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
934 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700935 info.iconPath = file.getAbsolutePath();
936 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700937 try {
938 os.close();
939 } catch (IOException ioe) {
940 // What the ... !
941 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100942 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700943 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700945 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700946 }
947
Amith Yamasani0b285492011-04-14 17:35:23 -0700948 /**
949 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
950 * cache it elsewhere.
951 * @return the array of user ids.
952 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700953 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700954 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700955 return mUserIds;
956 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700957 }
958
Fyodor Kupolov82402752015-10-28 14:54:51 -0700959 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700960 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700961 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700962 return;
963 }
964 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700965 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700967 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700968 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100969 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 int type;
971 while ((type = parser.next()) != XmlPullParser.START_TAG
972 && type != XmlPullParser.END_DOCUMENT) {
973 ;
974 }
975
976 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700977 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700978 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700979 return;
980 }
981
Amith Yamasani2a003292012-08-14 18:25:45 -0700982 mNextSerialNumber = -1;
983 if (parser.getName().equals(TAG_USERS)) {
984 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
985 if (lastSerialNumber != null) {
986 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
987 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700988 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
989 if (versionNumber != null) {
990 mUserVersion = Integer.parseInt(versionNumber);
991 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700992 }
993
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700994 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530995 if (type == XmlPullParser.START_TAG) {
996 final String name = parser.getName();
997 if (name.equals(TAG_USER)) {
998 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001000
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301001 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001002 synchronized (mUsersLock) {
1003 mUsers.put(user.id, user);
1004 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1005 mNextSerialNumber = user.id + 1;
1006 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301007 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001008 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301009 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001010 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1011 && type != XmlPullParser.END_TAG) {
1012 if (type == XmlPullParser.START_TAG) {
1013 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001014 UserRestrictionsUtils
1015 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001016 }
1017 break;
1018 }
1019 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001020 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001021 }
1022 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001023 updateUserIds();
1024 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001025 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001026 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001027 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001028 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001029 } finally {
1030 if (fis != null) {
1031 try {
1032 fis.close();
1033 } catch (IOException e) {
1034 }
1035 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001036 }
1037 }
1038
Amith Yamasani6f34b412012-10-22 18:19:27 -07001039 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001040 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001041 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001042 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001043 int userVersion = mUserVersion;
1044 if (userVersion < 1) {
1045 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001046 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001047 if ("Primary".equals(user.name)) {
1048 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001049 scheduleWriteUserLP(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001050 }
1051 userVersion = 1;
1052 }
1053
Amith Yamasanibc9625052012-11-15 14:39:18 -08001054 if (userVersion < 2) {
1055 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001056 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001057 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1058 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001059 scheduleWriteUserLP(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001060 }
1061 userVersion = 2;
1062 }
1063
Amith Yamasani350962c2013-08-06 11:18:53 -07001064
Amith Yamasani5e486f52013-08-07 11:06:44 -07001065 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001066 userVersion = 4;
1067 }
1068
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001069 if (userVersion < 5) {
1070 initDefaultGuestRestrictions();
1071 userVersion = 5;
1072 }
1073
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001074 if (userVersion < 6) {
1075 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001076 synchronized (mUsersLock) {
1077 for (int i = 0; i < mUsers.size(); i++) {
1078 UserInfo user = mUsers.valueAt(i);
1079 // In non-split mode, only user 0 can have restricted profiles
1080 if (!splitSystemUser && user.isRestricted()
1081 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1082 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1083 scheduleWriteUserLP(user);
1084 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001085 }
1086 }
1087 userVersion = 6;
1088 }
1089
Amith Yamasani6f34b412012-10-22 18:19:27 -07001090 if (userVersion < USER_VERSION) {
1091 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1092 + USER_VERSION);
1093 } else {
1094 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001095 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001096 }
1097 }
1098
Fyodor Kupolov82402752015-10-28 14:54:51 -07001099 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001100 int flags = UserInfo.FLAG_INITIALIZED;
1101 // In split system user mode, the admin and primary flags are assigned to the first human
1102 // user.
1103 if (!UserManager.isSplitSystemUser()) {
1104 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1105 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001106 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001107 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001108 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001109 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001110 synchronized (mUsersLock) {
1111 mUsers.put(system.id, system);
1112 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001113 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001114 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001115
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001116 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001117 synchronized (mRestrictionsLock) {
1118 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1119 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001120
Fyodor Kupolov82402752015-10-28 14:54:51 -07001121 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001122 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001123
Fyodor Kupolov82402752015-10-28 14:54:51 -07001124 writeUserListLILP();
1125 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126 }
1127
Fyodor Kupolov82402752015-10-28 14:54:51 -07001128 private void scheduleWriteUserLP(UserInfo userInfo) {
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001129 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1130 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1131 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1132 }
1133 }
1134
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001135 /*
1136 * Writes the user file in this format:
1137 *
1138 * <user flags="20039023" id="0">
1139 * <name>Primary</name>
1140 * </user>
1141 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001142 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001143 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001144 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001145 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001146 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001147 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1148
1149 // XmlSerializer serializer = XmlUtils.serializerInstance();
1150 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001151 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001152 serializer.startDocument(null, true);
1153 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1154
1155 serializer.startTag(null, TAG_USER);
1156 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001157 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001158 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001159 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1160 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1161 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001162 if (userInfo.iconPath != null) {
1163 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1164 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001165 if (userInfo.partial) {
1166 serializer.attribute(null, ATTR_PARTIAL, "true");
1167 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001168 if (userInfo.guestToRemove) {
1169 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1170 }
Kenny Guy2a764942014-04-02 13:29:20 +01001171 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1172 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1173 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001174 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001175 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1176 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1177 Integer.toString(userInfo.restrictedProfileParentId));
1178 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001179 serializer.startTag(null, TAG_NAME);
1180 serializer.text(userInfo.name);
1181 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 Bundle restrictions;
1183 synchronized (mRestrictionsLock) {
1184 restrictions = mBaseUserRestrictions.get(userInfo.id);
1185 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001186 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 UserRestrictionsUtils
1188 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001189 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001190 serializer.endTag(null, TAG_USER);
1191
1192 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001193 userFile.finishWrite(fos);
1194 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001195 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001196 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001197 }
1198 }
1199
1200 /*
1201 * Writes the user list file in this format:
1202 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001203 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001204 * <user id="0"></user>
1205 * <user id="2"></user>
1206 * </users>
1207 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001208 private void writeUserListLILP() {
1209 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001210 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001211 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001212 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001213 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001214 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1215
1216 // XmlSerializer serializer = XmlUtils.serializerInstance();
1217 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001218 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219 serializer.startDocument(null, true);
1220 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1221
1222 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001223 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001224 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001225
Adam Lesinskieddeb492014-09-08 17:50:03 -07001226 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001227 UserRestrictionsUtils
1228 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301229 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 int[] userIdsToWrite;
1231 synchronized (mUsersLock) {
1232 userIdsToWrite = new int[mUsers.size()];
1233 for (int i = 0; i < userIdsToWrite.length; i++) {
1234 UserInfo user = mUsers.valueAt(i);
1235 userIdsToWrite[i] = user.id;
1236 }
1237 }
1238 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001240 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001241 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001242 }
1243
1244 serializer.endTag(null, TAG_USERS);
1245
1246 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001247 userListFile.finishWrite(fos);
1248 } catch (Exception e) {
1249 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001250 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001251 }
1252 }
1253
Fyodor Kupolov82402752015-10-28 14:54:51 -07001254 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001255 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001256 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001258 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001259 long creationTime = 0L;
1260 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001261 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001262 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001263 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001264 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001265 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001266
1267 FileInputStream fis = null;
1268 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001269 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001270 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001271 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001272 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001273 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001274 int type;
1275 while ((type = parser.next()) != XmlPullParser.START_TAG
1276 && type != XmlPullParser.END_DOCUMENT) {
1277 ;
1278 }
1279
1280 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001281 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001282 return null;
1283 }
1284
1285 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001286 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1287 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001288 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001289 return null;
1290 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001291 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1292 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001293 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001294 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1295 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001296 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1297 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001298 restrictedProfileParentId = readIntAttribute(parser,
1299 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001300 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1301 if ("true".equals(valueString)) {
1302 partial = true;
1303 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001304 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1305 if ("true".equals(valueString)) {
1306 guestToRemove = true;
1307 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001308
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001309 int outerDepth = parser.getDepth();
1310 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1311 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1312 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1313 continue;
1314 }
1315 String tag = parser.getName();
1316 if (TAG_NAME.equals(tag)) {
1317 type = parser.next();
1318 if (type == XmlPullParser.TEXT) {
1319 name = parser.getText();
1320 }
1321 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001322 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001323 }
1324 }
1325 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001327 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001328 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001329 userInfo.creationTime = creationTime;
1330 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001331 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001332 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001333 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001334 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001335 synchronized (mRestrictionsLock) {
1336 mBaseUserRestrictions.append(id, restrictions);
1337 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001338 return userInfo;
1339
1340 } catch (IOException ioe) {
1341 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001342 } finally {
1343 if (fis != null) {
1344 try {
1345 fis.close();
1346 } catch (IOException e) {
1347 }
1348 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001349 }
1350 return null;
1351 }
1352
Amith Yamasani920ace02012-09-20 22:15:37 -07001353 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1354 String valueString = parser.getAttributeValue(null, attr);
1355 if (valueString == null) return defaultValue;
1356 try {
1357 return Integer.parseInt(valueString);
1358 } catch (NumberFormatException nfe) {
1359 return defaultValue;
1360 }
1361 }
1362
1363 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1364 String valueString = parser.getAttributeValue(null, attr);
1365 if (valueString == null) return defaultValue;
1366 try {
1367 return Long.parseLong(valueString);
1368 } catch (NumberFormatException nfe) {
1369 return defaultValue;
1370 }
1371 }
1372
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001373 private boolean isPackageInstalled(String pkg, int userId) {
1374 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1375 PackageManager.GET_UNINSTALLED_PACKAGES,
1376 userId);
1377 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1378 return false;
1379 }
1380 return true;
1381 }
1382
Amith Yamasanib82add22013-07-09 11:24:44 -07001383 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001384 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001385 * Does not do any permissions checking.
1386 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001387 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001388 synchronized (mPackagesLock) {
1389 File dir = Environment.getUserSystemDirectory(userId);
1390 String[] files = dir.list();
1391 if (files == null) return;
1392 for (String fileName : files) {
1393 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1394 File resFile = new File(dir, fileName);
1395 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001396 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001397 }
1398 }
1399 }
1400 }
1401 }
1402
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001403 /**
1404 * Removes the app restrictions file for a specific package and user id, if it exists.
1405 */
1406 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1407 synchronized (mPackagesLock) {
1408 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001409 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001410 if (resFile.exists()) {
1411 resFile.delete();
1412 }
1413 }
1414 }
1415
Kenny Guya52dc3e2014-02-11 15:33:14 +00001416 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001417 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001418 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001419 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001420 }
1421
Amith Yamasani258848d2012-08-10 17:06:33 -07001422 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001423 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001424 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001425 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001426 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001427
Jessica Hummelbe81c802014-04-22 15:49:22 +01001428 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001429 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1430 UserManager.DISALLOW_ADD_USER, false)) {
1431 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1432 return null;
1433 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001434 if (ActivityManager.isLowRamDeviceStatic()) {
1435 return null;
1436 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001437 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001438 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001439 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001440 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001441 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001442 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001443 try {
1444 synchronized (mInstallLock) {
1445 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001446 UserInfo parent = null;
1447 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001448 synchronized (mUsersLock) {
1449 parent = getUserInfoLU(parentId);
1450 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001451 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001452 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001453 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1454 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001455 return null;
1456 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001457 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001458 // If we're not adding a guest user or a managed profile and the limit has
1459 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001460 return null;
1461 }
1462 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001463 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001464 return null;
1465 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001466 // In legacy mode, restricted profile's parent can only be the owner user
1467 if (isRestricted && !UserManager.isSplitSystemUser()
1468 && (parentId != UserHandle.USER_SYSTEM)) {
1469 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1470 return null;
1471 }
1472 if (isRestricted && UserManager.isSplitSystemUser()) {
1473 if (parent == null) {
1474 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1475 + "specified");
1476 return null;
1477 }
1478 if (!parent.canHaveProfile()) {
1479 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1480 + "created for the specified parent user id " + parentId);
1481 return null;
1482 }
1483 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001484 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001485 // And if there is no device owner, we also assign the admin flag to primary
1486 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001487 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001488 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001489 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001490 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1491 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1492 if (devicePolicyManager == null
1493 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001494 flags |= UserInfo.FLAG_ADMIN;
1495 }
1496 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001497 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001498 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001499 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001500 long now = System.currentTimeMillis();
1501 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001502 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001503 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001504 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001505 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001506 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001507 if (isManagedProfile) {
1508 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1509 parent.profileGroupId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001510 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001511 }
1512 userInfo.profileGroupId = parent.profileGroupId;
1513 } else if (isRestricted) {
1514 if (!parent.canHaveProfile()) {
1515 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1516 }
1517 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1518 parent.restrictedProfileParentId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001519 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001520 }
1521 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001522 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001523 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001524 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1525 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1526 final String volumeUuid = vol.getFsUuid();
1527 try {
1528 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1529 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001530 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001531 enforceSerialNumber(userDir, userInfo.serialNumber);
1532 } catch (IOException e) {
1533 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1534 }
1535 }
1536 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001537 userInfo.partial = false;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001538 scheduleWriteUserLP(userInfo);
1539 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001540 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001541 synchronized (mRestrictionsLock) {
1542 mBaseUserRestrictions.append(userId, restrictions);
1543 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001544 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001545 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001546 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001547 if (userInfo != null) {
1548 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1549 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1550 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1551 android.Manifest.permission.MANAGE_USERS);
1552 }
1553 } finally {
1554 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001555 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001556 return userInfo;
1557 }
1558
Amith Yamasani0b285492011-04-14 17:35:23 -07001559 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001560 * @hide
1561 */
1562 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1563 checkManageUsersPermission("setupRestrictedProfile");
1564 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1565 if (user == null) {
1566 return null;
1567 }
1568 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1569 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1570 // the putIntForUser() will fail.
1571 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1572 android.provider.Settings.Secure.LOCATION_MODE,
1573 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1574 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1575 return user;
1576 }
1577
1578 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001579 * Find the current guest user. If the Guest user is partial,
1580 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001581 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001582 private UserInfo findCurrentGuestUser() {
1583 synchronized (mUsersLock) {
1584 final int size = mUsers.size();
1585 for (int i = 0; i < size; i++) {
1586 final UserInfo user = mUsers.valueAt(i);
1587 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1588 return user;
1589 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001590 }
1591 }
1592 return null;
1593 }
1594
1595 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001596 * Mark this guest user for deletion to allow us to create another guest
1597 * and switch to that user before actually removing this guest.
1598 * @param userHandle the userid of the current guest
1599 * @return whether the user could be marked for deletion
1600 */
1601 public boolean markGuestForDeletion(int userHandle) {
1602 checkManageUsersPermission("Only the system can remove users");
1603 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1604 UserManager.DISALLOW_REMOVE_USER, false)) {
1605 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1606 return false;
1607 }
1608
1609 long ident = Binder.clearCallingIdentity();
1610 try {
1611 final UserInfo user;
1612 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001613 synchronized (mUsersLock) {
1614 user = mUsers.get(userHandle);
1615 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1616 return false;
1617 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001618 }
1619 if (!user.isGuest()) {
1620 return false;
1621 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001622 // We set this to a guest user that is to be removed. This is a temporary state
1623 // where we are allowed to add new Guest users, even if this one is still not
1624 // removed. This user will still show up in getUserInfo() calls.
1625 // If we don't get around to removing this Guest user, it will be purged on next
1626 // startup.
1627 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001628 // Mark it as disabled, so that it isn't returned any more when
1629 // profiles are queried.
1630 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001631 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001632 }
1633 } finally {
1634 Binder.restoreCallingIdentity(ident);
1635 }
1636 return true;
1637 }
1638
1639 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001640 * Removes a user and all data directories created for that user. This method should be called
1641 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001642 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001643 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001644 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001645 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001646 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1647 UserManager.DISALLOW_REMOVE_USER, false)) {
1648 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1649 return false;
1650 }
1651
Kenny Guyee58b4f2014-05-23 15:19:53 +01001652 long ident = Binder.clearCallingIdentity();
1653 try {
1654 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001655 int currentUser = ActivityManager.getCurrentUser();
1656 if (currentUser == userHandle) {
1657 Log.w(LOG_TAG, "Current user cannot be removed");
1658 return false;
1659 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001660 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001661 synchronized (mUsersLock) {
1662 user = mUsers.get(userHandle);
1663 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1664 return false;
1665 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001666
Fyodor Kupolov82402752015-10-28 14:54:51 -07001667 // We remember deleted user IDs to prevent them from being
1668 // reused during the current boot; they can still be reused
1669 // after a reboot.
1670 mRemovingUserIds.put(userHandle, true);
1671 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001672
Kenny Guyee58b4f2014-05-23 15:19:53 +01001673 try {
1674 mAppOpsService.removeUser(userHandle);
1675 } catch (RemoteException e) {
1676 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1677 }
1678 // Set this to a partially created user, so that the user will be purged
1679 // on next startup, in case the runtime stops now before stopping and
1680 // removing the user completely.
1681 user.partial = true;
1682 // Mark it as disabled, so that it isn't returned any more when
1683 // profiles are queried.
1684 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001685 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001686 }
1687
1688 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1689 && user.isManagedProfile()) {
1690 // Send broadcast to notify system that the user removed was a
1691 // managed user.
1692 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1693 }
1694
1695 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1696 int res;
1697 try {
1698 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1699 new IStopUserCallback.Stub() {
1700 @Override
1701 public void userStopped(int userId) {
1702 finishRemoveUser(userId);
1703 }
1704 @Override
1705 public void userStopAborted(int userId) {
1706 }
1707 });
1708 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001709 return false;
1710 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001711 return res == ActivityManager.USER_OP_SUCCESS;
1712 } finally {
1713 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001714 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001715 }
1716
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001717 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001718 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001719 // Let other services shutdown any activity and clean up their state before completely
1720 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001721 long ident = Binder.clearCallingIdentity();
1722 try {
1723 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1724 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001725 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1726 android.Manifest.permission.MANAGE_USERS,
1727
1728 new BroadcastReceiver() {
1729 @Override
1730 public void onReceive(Context context, Intent intent) {
1731 if (DBG) {
1732 Slog.i(LOG_TAG,
1733 "USER_REMOVED broadcast sent, cleaning up user data "
1734 + userHandle);
1735 }
1736 new Thread() {
1737 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001738 // Clean up any ActivityManager state
1739 LocalServices.getService(ActivityManagerInternal.class)
1740 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001741 synchronized (mInstallLock) {
1742 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001743 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001744 }
1745 }
1746 }
1747 }.start();
1748 }
1749 },
1750
1751 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001752 } finally {
1753 Binder.restoreCallingIdentity(ident);
1754 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001755 }
1756
Fyodor Kupolov82402752015-10-28 14:54:51 -07001757 private void removeUserStateLILP(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001758 mContext.getSystemService(StorageManager.class)
1759 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001760 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001761 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001762
1763 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001764 synchronized (mUsersLock) {
1765 mUsers.remove(userHandle);
1766 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001767 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001768 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001769 userFile.delete();
1770 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001771 writeUserListLILP();
1772 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001773 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1774 }
1775
Amith Yamasani61f57372012-08-31 12:12:28 -07001776 private void removeDirectoryRecursive(File parent) {
1777 if (parent.isDirectory()) {
1778 String[] files = parent.list();
1779 for (String filename : files) {
1780 File child = new File(parent, filename);
1781 removeDirectoryRecursive(child);
1782 }
1783 }
1784 parent.delete();
1785 }
1786
Kenny Guyf8d3a232014-05-15 16:09:52 +01001787 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001788 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001789 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1790 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001791 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1792 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001793 }
1794
Amith Yamasani2a003292012-08-14 18:25:45 -07001795 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001796 public Bundle getApplicationRestrictions(String packageName) {
1797 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1798 }
1799
1800 @Override
1801 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001802 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001803 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001804 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001805 }
1806 synchronized (mPackagesLock) {
1807 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001808 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001809 }
1810 }
1811
1812 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001813 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001814 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001815 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001816 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001817 if (restrictions == null || restrictions.isEmpty()) {
1818 cleanAppRestrictionsForPackage(packageName, userId);
1819 } else {
1820 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001821 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001822 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001823 }
Robin Lee66e5d962014-04-09 16:44:21 +01001824
Kenny Guyd21b2182014-07-17 16:38:55 +01001825 if (isPackageInstalled(packageName, userId)) {
1826 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1827 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1828 changeIntent.setPackage(packageName);
1829 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1830 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1831 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001832 }
1833
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001834 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001835 mHandler.post(new Runnable() {
1836 @Override
1837 public void run() {
1838 List<ApplicationInfo> apps =
1839 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1840 userHandle).getList();
1841 final long ident = Binder.clearCallingIdentity();
1842 try {
1843 for (ApplicationInfo appInfo : apps) {
1844 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001845 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1846 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001847 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001848 userHandle);
1849 }
1850 }
1851 } finally {
1852 Binder.restoreCallingIdentity(ident);
1853 }
1854 }
1855 });
1856 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001857 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001858 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001859 try {
1860 return mContext.getPackageManager().getApplicationInfo(packageName,
1861 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1862 } catch (NameNotFoundException nnfe) {
1863 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001864 } finally {
1865 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001866 }
1867 }
1868
Fyodor Kupolov82402752015-10-28 14:54:51 -07001869 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001870 AtomicFile restrictionsFile =
1871 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1872 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001873 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001874 }
1875
1876 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001877 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001878 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001879 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001880 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001881 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001882 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001883
1884 FileInputStream fis = null;
1885 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001886 fis = restrictionsFile.openRead();
1887 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001888 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001889 XmlUtils.nextElement(parser);
1890 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001891 Slog.e(LOG_TAG, "Unable to read restrictions file "
1892 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001893 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001894 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001895 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1896 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001897 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001898 } catch (IOException|XmlPullParserException e) {
1899 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001901 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001902 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001903 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001904 }
1905
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001906 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1907 XmlPullParser parser) throws XmlPullParserException, IOException {
1908 int type = parser.getEventType();
1909 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1910 String key = parser.getAttributeValue(null, ATTR_KEY);
1911 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1912 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1913 if (multiple != null) {
1914 values.clear();
1915 int count = Integer.parseInt(multiple);
1916 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1917 if (type == XmlPullParser.START_TAG
1918 && parser.getName().equals(TAG_VALUE)) {
1919 values.add(parser.nextText().trim());
1920 count--;
1921 }
1922 }
1923 String [] valueStrings = new String[values.size()];
1924 values.toArray(valueStrings);
1925 restrictions.putStringArray(key, valueStrings);
1926 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1927 restrictions.putBundle(key, readBundleEntry(parser, values));
1928 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1929 final int outerDepth = parser.getDepth();
1930 ArrayList<Bundle> bundleList = new ArrayList<>();
1931 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1932 Bundle childBundle = readBundleEntry(parser, values);
1933 bundleList.add(childBundle);
1934 }
1935 restrictions.putParcelableArray(key,
1936 bundleList.toArray(new Bundle[bundleList.size()]));
1937 } else {
1938 String value = parser.nextText().trim();
1939 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1940 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1941 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1942 restrictions.putInt(key, Integer.parseInt(value));
1943 } else {
1944 restrictions.putString(key, value);
1945 }
1946 }
1947 }
1948 }
1949
1950 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1951 throws IOException, XmlPullParserException {
1952 Bundle childBundle = new Bundle();
1953 final int outerDepth = parser.getDepth();
1954 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1955 readEntry(childBundle, values, parser);
1956 }
1957 return childBundle;
1958 }
1959
Fyodor Kupolov82402752015-10-28 14:54:51 -07001960 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001961 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001962 AtomicFile restrictionsFile = new AtomicFile(
1963 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001964 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001965 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001966 }
1967
1968 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001969 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001970 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001971 try {
1972 fos = restrictionsFile.startWrite();
1973 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1974
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001975 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001976 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001977 serializer.startDocument(null, true);
1978 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1979
1980 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001981 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001982 serializer.endTag(null, TAG_RESTRICTIONS);
1983
1984 serializer.endDocument();
1985 restrictionsFile.finishWrite(fos);
1986 } catch (Exception e) {
1987 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001988 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1989 }
1990 }
1991
1992 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1993 throws IOException {
1994 for (String key : restrictions.keySet()) {
1995 Object value = restrictions.get(key);
1996 serializer.startTag(null, TAG_ENTRY);
1997 serializer.attribute(null, ATTR_KEY, key);
1998
1999 if (value instanceof Boolean) {
2000 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2001 serializer.text(value.toString());
2002 } else if (value instanceof Integer) {
2003 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2004 serializer.text(value.toString());
2005 } else if (value == null || value instanceof String) {
2006 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2007 serializer.text(value != null ? (String) value : "");
2008 } else if (value instanceof Bundle) {
2009 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2010 writeBundle((Bundle) value, serializer);
2011 } else if (value instanceof Parcelable[]) {
2012 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2013 Parcelable[] array = (Parcelable[]) value;
2014 for (Parcelable parcelable : array) {
2015 if (!(parcelable instanceof Bundle)) {
2016 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2017 }
2018 serializer.startTag(null, TAG_ENTRY);
2019 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2020 writeBundle((Bundle) parcelable, serializer);
2021 serializer.endTag(null, TAG_ENTRY);
2022 }
2023 } else {
2024 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2025 String[] values = (String[]) value;
2026 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2027 for (String choice : values) {
2028 serializer.startTag(null, TAG_VALUE);
2029 serializer.text(choice != null ? choice : "");
2030 serializer.endTag(null, TAG_VALUE);
2031 }
2032 }
2033 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002034 }
2035 }
2036
2037 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002038 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002039 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002040 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002041 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002042 }
2043 }
2044
2045 @Override
2046 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002047 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002048 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002049 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002050 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002051 }
2052 // Not found
2053 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002054 }
2055 }
2056
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002057 @Override
2058 public long getUserCreationTime(int userHandle) {
2059 int callingUserId = UserHandle.getCallingUserId();
2060 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002061 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002062 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002063 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002064 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002065 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002066 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002067 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002068 }
2069 }
2070 }
2071 if (userInfo == null) {
2072 throw new SecurityException("userHandle can only be the calling user or a managed "
2073 + "profile associated with this user");
2074 }
2075 return userInfo.creationTime;
2076 }
2077
Amith Yamasani0b285492011-04-14 17:35:23 -07002078 /**
2079 * Caches the list of user ids in an array, adjusting the array size when necessary.
2080 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002081 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002082 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002083 synchronized (mUsersLock) {
2084 final int userSize = mUsers.size();
2085 for (int i = 0; i < userSize; i++) {
2086 if (!mUsers.valueAt(i).partial) {
2087 num++;
2088 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002089 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002090 final int[] newUsers = new int[num];
2091 int n = 0;
2092 for (int i = 0; i < userSize; i++) {
2093 if (!mUsers.valueAt(i).partial) {
2094 newUsers[n++] = mUsers.keyAt(i);
2095 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002096 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002097 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002098 }
2099 }
2100
2101 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002102 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002103 * @param userId the user that was just foregrounded
2104 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002105 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002106 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002107 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002108 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002109 if (user == null || user.partial) {
2110 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2111 return;
2112 }
2113 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002114 user.lastLoggedInTime = now;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002115 scheduleWriteUserLP(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002116 }
2117 }
2118 }
2119
2120 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002121 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002122 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2123 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002124 * @return
2125 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 private int getNextAvailableId() {
2127 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002128 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002129 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002130 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002131 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002132 }
2133 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002134 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002136 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002137 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002138
Amith Yamasanifc95e702013-09-26 13:20:17 -07002139 private String packageToRestrictionsFileName(String packageName) {
2140 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2141 }
2142
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002143 /**
2144 * Create new {@code /data/user/[id]} directory and sets default
2145 * permissions.
2146 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002147 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2148 final StorageManager storage = context.getSystemService(StorageManager.class);
2149 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2150 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002151 }
2152
2153 /**
2154 * Enforce that serial number stored in user directory inode matches the
2155 * given expected value. Gracefully sets the serial number if currently
2156 * undefined.
2157 *
2158 * @throws IOException when problem extracting serial number, or serial
2159 * number is mismatched.
2160 */
2161 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2162 final int foundSerial = getSerialNumber(file);
2163 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2164
2165 if (foundSerial == -1) {
2166 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2167 try {
2168 setSerialNumber(file, serialNumber);
2169 } catch (IOException e) {
2170 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2171 }
2172
2173 } else if (foundSerial != serialNumber) {
2174 throw new IOException("Found serial number " + foundSerial
2175 + " doesn't match expected " + serialNumber);
2176 }
2177 }
2178
2179 /**
2180 * Set serial number stored in user directory inode.
2181 *
2182 * @throws IOException if serial number was already set
2183 */
2184 private static void setSerialNumber(File file, int serialNumber)
2185 throws IOException {
2186 try {
2187 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2188 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2189 } catch (ErrnoException e) {
2190 throw e.rethrowAsIOException();
2191 }
2192 }
2193
2194 /**
2195 * Return serial number stored in user directory inode.
2196 *
2197 * @return parsed serial number, or -1 if not set
2198 */
2199 private static int getSerialNumber(File file) throws IOException {
2200 try {
2201 final byte[] buf = new byte[256];
2202 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2203 final String serial = new String(buf, 0, len);
2204 try {
2205 return Integer.parseInt(serial);
2206 } catch (NumberFormatException e) {
2207 throw new IOException("Bad serial number: " + serial);
2208 }
2209 } catch (ErrnoException e) {
2210 if (e.errno == OsConstants.ENODATA) {
2211 return -1;
2212 } else {
2213 throw e.rethrowAsIOException();
2214 }
2215 }
2216 }
2217
Amith Yamasani920ace02012-09-20 22:15:37 -07002218 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002219 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2220 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2221 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2222 }
2223
2224 int onShellCommand(Shell shell, String cmd) {
2225 if (cmd == null) {
2226 return shell.handleDefaultCommands(cmd);
2227 }
2228
2229 final PrintWriter pw = shell.getOutPrintWriter();
2230 try {
2231 switch(cmd) {
2232 case "list":
2233 return runList(pw);
2234 }
2235 } catch (RemoteException e) {
2236 pw.println("Remote exception: " + e);
2237 }
2238 return -1;
2239 }
2240
2241 private int runList(PrintWriter pw) throws RemoteException {
2242 final IActivityManager am = ActivityManagerNative.getDefault();
2243 final List<UserInfo> users = getUsers(false);
2244 if (users == null) {
2245 pw.println("Error: couldn't get users");
2246 return 1;
2247 } else {
2248 pw.println("Users:");
2249 for (int i = 0; i < users.size(); i++) {
2250 String running = am.isUserRunning(users.get(i).id, false) ? " running" : "";
2251 pw.println("\t" + users.get(i).toString() + running);
2252 }
2253 return 0;
2254 }
2255 }
2256
2257 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002258 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2259 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2260 != PackageManager.PERMISSION_GRANTED) {
2261 pw.println("Permission Denial: can't dump UserManager from from pid="
2262 + Binder.getCallingPid()
2263 + ", uid=" + Binder.getCallingUid()
2264 + " without permission "
2265 + android.Manifest.permission.DUMP);
2266 return;
2267 }
2268
2269 long now = System.currentTimeMillis();
2270 StringBuilder sb = new StringBuilder();
2271 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002272 synchronized (mUsersLock) {
2273 pw.println("Users:");
2274 for (int i = 0; i < mUsers.size(); i++) {
2275 UserInfo user = mUsers.valueAt(i);
2276 if (user == null) {
2277 continue;
2278 }
2279 pw.print(" "); pw.print(user);
2280 pw.print(" serialNo="); pw.print(user.serialNumber);
2281 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2282 pw.print(" <removing> ");
2283 }
2284 if (user.partial) {
2285 pw.print(" <partial>");
2286 }
2287 pw.println();
2288 pw.print(" Created: ");
2289 if (user.creationTime == 0) {
2290 pw.println("<unknown>");
2291 } else {
2292 sb.setLength(0);
2293 TimeUtils.formatDuration(now - user.creationTime, sb);
2294 sb.append(" ago");
2295 pw.println(sb);
2296 }
2297 pw.print(" Last logged in: ");
2298 if (user.lastLoggedInTime == 0) {
2299 pw.println("<unknown>");
2300 } else {
2301 sb.setLength(0);
2302 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2303 sb.append(" ago");
2304 pw.println(sb);
2305 }
2306 pw.println(" Restrictions:");
2307 synchronized (mRestrictionsLock) {
2308 UserRestrictionsUtils.dumpRestrictions(
2309 pw, " ", mBaseUserRestrictions.get(user.id));
2310 pw.println(" Effective restrictions:");
2311 UserRestrictionsUtils.dumpRestrictions(
2312 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2313 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002314 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002315 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002316 pw.println();
2317 pw.println("Guest restrictions:");
2318 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002319 }
2320 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002321
2322 final class MainHandler extends Handler {
2323
2324 @Override
2325 public void handleMessage(Message msg) {
2326 switch (msg.what) {
2327 case WRITE_USER_MSG:
2328 removeMessages(WRITE_USER_MSG, msg.obj);
2329 synchronized (mPackagesLock) {
2330 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002331 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002332 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002333 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002334 }
2335 }
2336 }
2337 }
2338 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002339
2340 /**
2341 * @param userId
2342 * @return whether the user has been initialized yet
2343 */
2344 boolean isInitialized(int userId) {
2345 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2346 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002347
2348 private class LocalService extends UserManagerInternal {
2349
2350 @Override
2351 public Object getUserRestrictionsLock() {
2352 return mRestrictionsLock;
2353 }
2354
2355 @Override
2356 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002357 public void updateEffectiveUserRestrictionsLR(int userId) {
2358 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002359 }
2360
2361 @Override
2362 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002363 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2364 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002365 }
2366
2367 @Override
2368 public Bundle getBaseUserRestrictions(int userId) {
2369 synchronized (mRestrictionsLock) {
2370 return mBaseUserRestrictions.get(userId);
2371 }
2372 }
2373
2374 @Override
2375 public void setBaseUserRestrictionsByDpmsForMigration(
2376 int userId, Bundle baseRestrictions) {
2377 synchronized (mRestrictionsLock) {
2378 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002379 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002380 }
2381
Fyodor Kupolov82402752015-10-28 14:54:51 -07002382 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002383 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002384 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002385 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002386 } else {
2387 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2388 }
2389 }
2390 }
2391 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002392
2393 private class Shell extends ShellCommand {
2394 @Override
2395 public int onCommand(String cmd) {
2396 return onShellCommand(this, cmd);
2397 }
2398
2399 @Override
2400 public void onHelp() {
2401 final PrintWriter pw = getOutPrintWriter();
2402 pw.println("User manager (user) commands:");
2403 pw.println(" help");
2404 pw.println(" Print this help text.");
2405 pw.println("");
2406 pw.println(" list");
2407 pw.println(" Prints all users on the system.");
2408 }
2409 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002410}