blob: 3d614a35c13b4b02e7168460aa6a5a26b8359685 [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 Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080038import android.os.Debug;
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;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070052import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070053import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080054import android.os.UserManagerInternal.UserRestrictionsListener;
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;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080062import android.util.Pair;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Slog;
64import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Xml;
68
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040071import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080072import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080073import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070075import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000076import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070077import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080078
79import org.xmlpull.v1.XmlPullParser;
80import org.xmlpull.v1.XmlPullParserException;
81import org.xmlpull.v1.XmlSerializer;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.BufferedOutputStream;
84import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.io.FileOutputStream;
89import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070090import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010091import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092import java.util.ArrayList;
93import java.util.List;
94
Fyodor Kupolov262f9952015-03-23 18:55:11 -070095import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080096import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097
Makoto Onuki068c54a2015-10-13 14:34:03 -070098/**
99 * Service for {@link UserManager}.
100 *
101 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700102 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800103 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700104 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
105 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
106 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700107 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700108public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700109 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800110 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
111 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700112
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800114 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700116 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700118 private static final String ATTR_CREATION_TIME = "created";
119 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700120 private static final String ATTR_SERIAL_NO = "serialNumber";
121 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700122 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700123 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700124 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100125 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700126 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530127 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800130 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800131 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800132 private static final String TAG_ENTRY = "entry";
133 private static final String TAG_VALUE = "value";
134 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700135 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800136 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700138 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
139 private static final String ATTR_TYPE_STRING = "s";
140 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700141 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700142 private static final String ATTR_TYPE_BUNDLE = "B";
143 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700144
Amith Yamasani0b285492011-04-14 17:35:23 -0700145 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700147 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100148 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800150 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700151 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800152
Amith Yamasani634cf312012-10-04 17:34:21 -0700153 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700154 // We need to keep process uid within Integer.MAX_VALUE.
155 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700156
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700157 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700158
Amith Yamasani920ace02012-09-20 22:15:37 -0700159 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
160
Nicolas Prevotb8186812015-08-06 15:00:03 +0100161 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700162 // without first making sure that the rest of the framework is prepared for it.
163 private static final int MAX_MANAGED_PROFILES = 1;
164
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800165 static final int WRITE_USER_MSG = 1;
166 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530167
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700168 private static final String XATTR_SERIAL = "user.serial";
169
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800170 // Tron counters
171 private static final String TRON_GUEST_CREATED = "users_guest_created";
172 private static final String TRON_USER_CREATED = "users_user_created";
173
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174 private final Context mContext;
175 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700177 // Short-term lock for internal state, when interaction/sync with PM is not required
178 private final Object mUsersLock = new Object();
179 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800181 private final Handler mHandler;
182
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183 private final File mUsersDir;
184 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700185
Fyodor Kupolov82402752015-10-28 14:54:51 -0700186 @GuardedBy("mUsersLock")
187 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700188
189 /**
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800190 * This collection contains each user's account name if the user chose to set one up
191 * during the initial user creation process. Keeping this information separate from mUsers
192 * to avoid accidentally leak it.
193 */
194 @GuardedBy("mUsersLock")
195 private final SparseArray<String> mUserAccounts = new SparseArray<>();
196
197 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700198 * User restrictions set via UserManager. This doesn't include restrictions set by
199 * device owner / profile owners.
200 *
201 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
202 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
203 * maybe shared between {@link #mBaseUserRestrictions} and
204 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
205 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700206 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700207 */
208 @GuardedBy("mRestrictionsLock")
209 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
210
211 /**
212 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
213 * with device / profile owner restrictions. We'll initialize it lazily; use
214 * {@link #getEffectiveUserRestrictions} to access it.
215 *
216 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
217 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
218 * maybe shared between {@link #mBaseUserRestrictions} and
219 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
220 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700221 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700222 */
223 @GuardedBy("mRestrictionsLock")
224 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
225
Makoto Onuki4f160732015-10-27 17:15:38 -0700226 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800227 * User restrictions that have already been applied in
228 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
229 * that have changed since the last
230 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700231 */
232 @GuardedBy("mRestrictionsLock")
233 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
234
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800235 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800236 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
237 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800238 */
239 @GuardedBy("mRestrictionsLock")
240 private Bundle mDevicePolicyGlobalUserRestrictions;
241
242 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800243 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
244 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800245 */
246 @GuardedBy("mRestrictionsLock")
247 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
248
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800249 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530250 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800251
252 /**
253 * Set of user IDs being actively removed. Removed IDs linger in this set
254 * for several seconds to work around a VFS caching issue.
255 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700256 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800257 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700258
Fyodor Kupolov82402752015-10-28 14:54:51 -0700259 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700260 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800261 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700262 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700263 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700264
Jason Monk62062992014-05-06 09:55:28 -0400265 private IAppOpsService mAppOpsService;
266
Makoto Onuki068c54a2015-10-13 14:34:03 -0700267 private final LocalService mLocalService;
268
Makoto Onukie7927da2015-11-25 10:05:17 -0800269 @GuardedBy("mUsersLock")
270 private boolean mIsDeviceManaged;
271
272 @GuardedBy("mUsersLock")
273 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
274
Makoto Onukid45a4a22015-11-02 17:17:38 -0800275 @GuardedBy("mUserRestrictionsListeners")
276 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
277 new ArrayList<>();
278
Amith Yamasani258848d2012-08-10 17:06:33 -0700279 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700280
Dianne Hackborn4428e172012-08-24 17:43:05 -0700281 public static UserManagerService getInstance() {
282 synchronized (UserManagerService.class) {
283 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700284 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700285 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700286
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800287 @VisibleForTesting
288 UserManagerService(File dataDir) {
289 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700290 }
291
Dianne Hackborn4428e172012-08-24 17:43:05 -0700292 /**
293 * Called by package manager to create the service. This is closely
294 * associated with the package manager, and the given lock is the
295 * package manager's own lock.
296 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800297 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
298 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700299 }
300
Dianne Hackborn4428e172012-08-24 17:43:05 -0700301 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800302 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700303 mContext = context;
304 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700305 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800306 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800307 synchronized (mPackagesLock) {
308 mUsersDir = new File(dataDir, USER_INFO_DIR);
309 mUsersDir.mkdirs();
310 // Make zeroth user directory, for services to migrate their files to that location
311 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
312 userZeroDir.mkdirs();
313 FileUtils.setPermissions(mUsersDir.toString(),
314 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
315 -1, -1);
316 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
317 initDefaultGuestRestrictions();
318 readUserListLP();
319 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700320 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700321 mLocalService = new LocalService();
322 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700323 }
324
325 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100326 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800327 ArrayList<UserInfo> partials = new ArrayList<>();
328 synchronized (mUsersLock) {
329 final int userSize = mUsers.size();
330 for (int i = 0; i < userSize; i++) {
331 UserInfo ui = mUsers.valueAt(i);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100332 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700334 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700335 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700336 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800337 final int partialsSize = partials.size();
338 for (int i = 0; i < partialsSize; i++) {
339 UserInfo ui = partials.get(i);
340 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
341 + " (name=" + ui.name + ")");
342 removeUserState(ui.id);
343 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800344
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700345 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800346
Jason Monk62062992014-05-06 09:55:28 -0400347 mAppOpsService = IAppOpsService.Stub.asInterface(
348 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800349
350 synchronized (mRestrictionsLock) {
351 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400352 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700353 }
354
355 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800356 public String getUserAccount(int userId) {
357 checkManageUserAndAcrossUsersFullPermission("get user account");
358 synchronized (mUsersLock) {
359 return mUserAccounts.get(userId);
360 }
361 }
362
363 @Override
364 public void setUserAccount(int userId, String accountName) {
365 checkManageUserAndAcrossUsersFullPermission("set user account");
366 UserInfo userToUpdate = null;
367 synchronized (mPackagesLock) {
368 synchronized (mUsersLock) {
369 String currentAccount = mUserAccounts.get(userId);
370 if (!Objects.equal(currentAccount, accountName)) {
371 mUserAccounts.put(userId, accountName);
372 userToUpdate = mUsers.get(userId);
373 }
374 }
375
376 if (userToUpdate != null) {
377 writeUserLP(userToUpdate);
378 }
379 }
380 }
381
382 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700383 public UserInfo getPrimaryUser() {
384 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700385 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700386 final int userSize = mUsers.size();
387 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700388 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800389 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700390 return ui;
391 }
392 }
393 }
394 return null;
395 }
396
397 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700398 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700399 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700400 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700401 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700402 final int userSize = mUsers.size();
403 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700404 UserInfo ui = mUsers.valueAt(i);
405 if (ui.partial) {
406 continue;
407 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800408 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700409 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700410 }
Amith Yamasani13593602012-03-22 16:16:17 -0700411 }
412 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700413 }
Amith Yamasani13593602012-03-22 16:16:17 -0700414 }
415
Amith Yamasani258848d2012-08-10 17:06:33 -0700416 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100417 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800418 if (userId != UserHandle.getCallingUserId()) {
419 checkManageUsersPermission("getting profiles related to user " + userId);
420 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700421 final long ident = Binder.clearCallingIdentity();
422 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700423 synchronized (mUsersLock) {
424 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100425 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700426 } finally {
427 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000428 }
429 }
430
Amith Yamasanibe465322014-04-24 13:45:17 -0700431 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700432 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
433 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700434 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700435 if (user == null) {
436 // Probably a dying user
437 return users;
438 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700439 final int userSize = mUsers.size();
440 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700441 UserInfo profile = mUsers.valueAt(i);
442 if (!isProfileOf(user, profile)) {
443 continue;
444 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100445 if (enabledOnly && !profile.isEnabled()) {
446 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700447 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700448 if (mRemovingUserIds.get(profile.id)) {
449 continue;
450 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700451 users.add(profile);
452 }
453 return users;
454 }
455
Jessica Hummelbe81c802014-04-22 15:49:22 +0100456 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700457 public int getCredentialOwnerProfile(int userHandle) {
458 checkManageUsersPermission("get the credential owner");
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000459 if (!LockPatternUtils.isSeparateWorkChallengeEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700460 synchronized (mUsersLock) {
461 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700462 if (profileParent != null) {
463 return profileParent.id;
464 }
465 }
466 }
467
468 return userHandle;
469 }
470
471 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700472 public boolean isSameProfileGroup(int userId, int otherUserId) {
473 if (userId == otherUserId) return true;
474 checkManageUsersPermission("check if in the same profile group");
475 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700476 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700477 }
478 }
479
Fyodor Kupolov82402752015-10-28 14:54:51 -0700480 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
481 synchronized (mUsersLock) {
482 UserInfo userInfo = getUserInfoLU(userId);
483 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
484 return false;
485 }
486 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
487 if (otherUserInfo == null
488 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
489 return false;
490 }
491 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700492 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700493 }
494
495 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100496 public UserInfo getProfileParent(int userHandle) {
497 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700498 synchronized (mUsersLock) {
499 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700500 }
501 }
502
Fyodor Kupolov82402752015-10-28 14:54:51 -0700503 private UserInfo getProfileParentLU(int userHandle) {
504 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700505 if (profile == null) {
506 return null;
507 }
508 int parentUserId = profile.profileGroupId;
509 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
510 return null;
511 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700512 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100513 }
514 }
515
Fyodor Kupolov82402752015-10-28 14:54:51 -0700516 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100517 return user.id == profile.id ||
518 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
519 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000520 }
521
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000522 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
523 UserHandle parentHandle, Bundle extras) {
524 // Send intent to profile
525 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
526 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
527 intent.putExtras(extras);
528 mContext.sendBroadcastAsUser(intent, profileHandle);
529
530 // Send intent to parent
531 if (parentHandle != null) {
532 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
533 intent.putExtra(Intent.EXTRA_USER, profileHandle);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700534 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000535 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
536 intent.putExtras(extras);
537 mContext.sendBroadcastAsUser(intent, parentHandle);
538 }
539 }
540
541 @Override
542 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
543 checkManageUsersPermission("silence profile");
544 boolean changed = false;
545 UserInfo profile, parent;
546 synchronized (mPackagesLock) {
547 synchronized (mUsersLock) {
548 profile = getUserInfoLU(userHandle);
549 parent = getProfileParentLU(userHandle);
550
551 }
552 if (profile == null || !profile.isManagedProfile()) {
553 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
554 }
555 if (profile.isQuietModeEnabled() != enableQuietMode) {
556 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
557 writeUserLP(profile);
558 changed = true;
559 }
560 }
561 if (changed) {
562 Bundle extras = new Bundle();
563 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
564 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
565 parent != null ? parent.getUserHandle() : null, extras);
566 }
567 }
568
569 @Override
570 public boolean isQuietModeEnabled(int userHandle) {
571 synchronized (mPackagesLock) {
572 UserInfo info;
573 synchronized (mUsersLock) {
574 info = getUserInfoLU(userHandle);
575 }
576 if (info == null || !info.isManagedProfile()) {
577 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
578 }
579 return info.isQuietModeEnabled();
580 }
581 }
582
Kenny Guya52dc3e2014-02-11 15:33:14 +0000583 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100584 public void setUserEnabled(int userId) {
585 checkManageUsersPermission("enable user");
586 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700587 UserInfo info;
588 synchronized (mUsersLock) {
589 info = getUserInfoLU(userId);
590 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100591 if (info != null && !info.isEnabled()) {
592 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700593 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100594 }
595 }
596 }
597
598 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700600 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700601 synchronized (mUsersLock) {
602 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700603 }
604 }
605
Amith Yamasani71e6c692013-03-24 17:39:28 -0700606 @Override
607 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 synchronized (mUsersLock) {
609 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700610 }
611 }
612
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700613 @Override
614 public boolean canHaveRestrictedProfile(int userId) {
615 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700616 synchronized (mUsersLock) {
617 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700618 if (userInfo == null || !userInfo.canHaveProfile()) {
619 return false;
620 }
621 if (!userInfo.isAdmin()) {
622 return false;
623 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800624 // restricted profile can be created if there is no DO set and the admin user has no PO;
625 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700626 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700627 }
628
Amith Yamasani195263742012-08-21 15:40:12 -0700629 /*
630 * Should be locked on mUsers before calling this.
631 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700632 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700633 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700634 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800635 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700636 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
637 return null;
638 }
639 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700640 }
641
Fyodor Kupolov82402752015-10-28 14:54:51 -0700642 /**
643 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
644 * <p>No permissions checking or any addition checks are made</p>
645 */
646 private UserInfo getUserInfoNoChecks(int userId) {
647 synchronized (mUsersLock) {
648 return mUsers.get(userId);
649 }
650 }
651
Amith Yamasani236b2b52015-08-18 14:32:14 -0700652 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700653 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700654 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700655 }
656
Amith Yamasani258848d2012-08-10 17:06:33 -0700657 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700658 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700659 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700660 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700661 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700662 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700663 if (info == null || info.partial) {
664 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
665 return;
666 }
Amith Yamasani13593602012-03-22 16:16:17 -0700667 if (name != null && !name.equals(info.name)) {
668 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700669 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700670 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700671 }
672 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700673 if (changed) {
674 sendUserInfoChangedBroadcast(userId);
675 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700676 }
677
Amith Yamasani258848d2012-08-10 17:06:33 -0700678 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700679 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700680 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400681 long ident = Binder.clearCallingIdentity();
682 try {
683 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700684 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400685 if (info == null || info.partial) {
686 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
687 return;
688 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700689 writeBitmapLP(info, bitmap);
690 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700691 }
Jason Monk9a944532014-07-08 09:31:21 -0400692 sendUserInfoChangedBroadcast(userId);
693 } finally {
694 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700695 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700696 }
697
698 private void sendUserInfoChangedBroadcast(int userId) {
699 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
700 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
701 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700702 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700703 }
704
Amith Yamasani258848d2012-08-10 17:06:33 -0700705 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100706 public ParcelFileDescriptor getUserIcon(int userId) {
707 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700708 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700709 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700710 if (info == null || info.partial) {
711 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
712 return null;
713 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700714 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100715 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
716 || callingGroupId != info.profileGroupId) {
717 checkManageUsersPermission("get the icon of a user who is not related");
718 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700719 if (info.iconPath == null) {
720 return null;
721 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100722 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700723 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100724
725 try {
726 return ParcelFileDescriptor.open(
727 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
728 } catch (FileNotFoundException e) {
729 Log.e(LOG_TAG, "Couldn't find icon file", e);
730 }
731 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700732 }
733
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700734 public void makeInitialized(int userId) {
735 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800736 boolean scheduleWriteUser = false;
737 UserInfo info;
738 synchronized (mUsersLock) {
739 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700740 if (info == null || info.partial) {
741 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800742 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700743 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800744 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700745 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800746 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700747 }
748 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800749 if (scheduleWriteUser) {
750 scheduleWriteUser(info);
751 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700752 }
753
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700754 /**
755 * If default guest restrictions haven't been initialized yet, add the basic
756 * restrictions.
757 */
758 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800759 synchronized (mGuestRestrictions) {
760 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800761 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800762 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
763 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
764 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700765 }
766 }
767
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800768 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530769 public Bundle getDefaultGuestRestrictions() {
770 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800771 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530772 return new Bundle(mGuestRestrictions);
773 }
774 }
775
776 @Override
777 public void setDefaultGuestRestrictions(Bundle restrictions) {
778 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800779 synchronized (mGuestRestrictions) {
780 mGuestRestrictions.clear();
781 mGuestRestrictions.putAll(restrictions);
782 }
783 synchronized (mPackagesLock) {
784 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530785 }
786 }
787
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800788 /**
789 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
790 */
791 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
792 @Nullable Bundle global) {
793 Preconditions.checkNotNull(local);
794 boolean globalChanged = false;
795 boolean localChanged;
796 synchronized (mRestrictionsLock) {
797 if (global != null) {
798 // Update global.
799 globalChanged = !UserRestrictionsUtils.areEqual(
800 mDevicePolicyGlobalUserRestrictions, global);
801 if (globalChanged) {
802 mDevicePolicyGlobalUserRestrictions = global;
803 }
804 }
805 {
806 // Update local.
807 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
808 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
809 if (localChanged) {
810 mDevicePolicyLocalUserRestrictions.put(userId, local);
811 }
812 }
813 }
814 if (DBG) {
815 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
816 + " global=" + global + (globalChanged ? " (changed)" : "")
817 + " local=" + local + (localChanged ? " (changed)" : "")
818 );
819 }
820 // Don't call them within the mRestrictionsLock.
821 synchronized (mPackagesLock) {
822 if (globalChanged) {
823 writeUserListLP();
824 }
825 if (localChanged) {
826 writeUserLP(getUserInfoNoChecks(userId));
827 }
828 }
829
830 synchronized (mRestrictionsLock) {
831 if (globalChanged) {
832 applyUserRestrictionsForAllUsersLR();
833 } else if (localChanged) {
834 applyUserRestrictionsLR(userId);
835 }
836 }
837 }
838
Makoto Onuki068c54a2015-10-13 14:34:03 -0700839 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700840 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800841 final Bundle baseRestrictions =
842 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
843 final Bundle global = mDevicePolicyGlobalUserRestrictions;
844 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700845
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800846 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
847 // Common case first.
848 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700849 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800850 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
851 UserRestrictionsUtils.merge(effective, global);
852 UserRestrictionsUtils.merge(effective, local);
853
Makoto Onuki068c54a2015-10-13 14:34:03 -0700854 return effective;
855 }
856
857 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700858 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700859 if (DBG) {
860 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
861 }
862 mCachedEffectiveUserRestrictions.remove(userId);
863 }
864
865 private Bundle getEffectiveUserRestrictions(int userId) {
866 synchronized (mRestrictionsLock) {
867 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
868 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700869 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700870 mCachedEffectiveUserRestrictions.put(userId, restrictions);
871 }
872 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700873 }
874 }
875
Makoto Onuki068c54a2015-10-13 14:34:03 -0700876 /** @return a specific user restriction that's in effect currently. */
877 @Override
878 public boolean hasUserRestriction(String restrictionKey, int userId) {
879 Bundle restrictions = getEffectiveUserRestrictions(userId);
880 return restrictions != null && restrictions.getBoolean(restrictionKey);
881 }
882
883 /**
884 * @return UserRestrictions that are in effect currently. This always returns a new
885 * {@link Bundle}.
886 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700887 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800888 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800889 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800890 }
891
892 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000893 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
894 checkManageUsersPermission("hasBaseUserRestriction");
895 synchronized (mRestrictionsLock) {
896 Bundle bundle = mBaseUserRestrictions.get(userId);
897 return (bundle != null && bundle.getBoolean(restrictionKey, false));
898 }
899 }
900
901 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700902 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700903 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700904 synchronized (mRestrictionsLock) {
905 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
906 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800907 final Bundle newRestrictions = UserRestrictionsUtils.clone(
908 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700909 newRestrictions.putBoolean(key, value);
910
Fyodor Kupolov82402752015-10-28 14:54:51 -0700911 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700912 }
913 }
914
Makoto Onuki068c54a2015-10-13 14:34:03 -0700915 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800916 * Optionally updating user restrictions, calculate the effective user restrictions and also
917 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700918 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800919 * @param newRestrictions User restrictions to set.
920 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700921 * @param userId target user ID.
922 */
923 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700924 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700925 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800926
927 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
928 mAppliedUserRestrictions.get(userId));
929
930 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700931 if (newRestrictions != null) {
932 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800933 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
934
935 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700936 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
937 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800938
939 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
940 mBaseUserRestrictions.put(userId, newRestrictions);
941 scheduleWriteUser(getUserInfoNoChecks(userId));
942 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700943 }
944
Fyodor Kupolov82402752015-10-28 14:54:51 -0700945 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700946
Makoto Onuki759a7632015-10-28 16:43:10 -0700947 mCachedEffectiveUserRestrictions.put(userId, effective);
948
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800949 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700950 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800951 debug("Applying user restrictions: userId=" + userId
952 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700953 }
954
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800955 if (mAppOpsService != null) { // We skip it until system-ready.
956 final long token = Binder.clearCallingIdentity();
957 try {
958 mAppOpsService.setUserRestrictions(effective, userId);
959 } catch (RemoteException e) {
960 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
961 } finally {
962 Binder.restoreCallingIdentity(token);
963 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700964 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700965
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800966 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700967
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800968 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969 }
970
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800971 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800972 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800973 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
974 // actually, but we still need some kind of synchronization otherwise we might end up
975 // calling listeners out-of-order, thus "LR".
976
977 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
978 return;
979 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800980
981 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
982 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
983
984 mHandler.post(new Runnable() {
985 @Override
986 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700987 UserRestrictionsUtils.applyUserRestrictions(
988 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800989
Makoto Onukid45a4a22015-11-02 17:17:38 -0800990 final UserRestrictionsListener[] listeners;
991 synchronized (mUserRestrictionsListeners) {
992 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
993 mUserRestrictionsListeners.toArray(listeners);
994 }
995 for (int i = 0; i < listeners.length; i++) {
996 listeners[i].onUserRestrictionsChanged(userId,
997 newRestrictionsFinal, prevRestrictionsFinal);
998 }
999 }
1000 });
1001 }
1002
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 // Package private for the inner class.
1004 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001005 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001006 }
1007
1008 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001009 // Package private for the inner class.
1010 void applyUserRestrictionsForAllUsersLR() {
1011 if (DBG) {
1012 debug("applyUserRestrictionsForAllUsersLR");
1013 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001014 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001015 mCachedEffectiveUserRestrictions.clear();
1016
Makoto Onuki068c54a2015-10-13 14:34:03 -07001017 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1018 // it on a handler.
1019 final Runnable r = new Runnable() {
1020 @Override
1021 public void run() {
1022 // Then get the list of running users.
1023 final int[] runningUsers;
1024 try {
1025 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1026 } catch (RemoteException e) {
1027 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1028 return;
1029 }
1030 // Then re-calculate the effective restrictions and apply, only for running users.
1031 // It's okay if a new user has started after the getRunningUserIds() call,
1032 // because we'll do the same thing (re-calculate the restrictions and apply)
1033 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001034 synchronized (mRestrictionsLock) {
1035 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001036 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001037 }
1038 }
1039 }
1040 };
1041 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001042 }
1043
Amith Yamasani258848d2012-08-10 17:06:33 -07001044 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001045 * Check if we've hit the limit of how many users can be created.
1046 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001047 private boolean isUserLimitReached() {
1048 int count;
1049 synchronized (mUsersLock) {
1050 count = getAliveUsersExcludingGuestsCountLU();
1051 }
1052 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001053 }
1054
1055 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001056 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001057 checkManageUsersPermission("check if more managed profiles can be added.");
1058 if (ActivityManager.isLowRamDeviceStatic()) {
1059 return false;
1060 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001061 if (!mContext.getPackageManager().hasSystemFeature(
1062 PackageManager.FEATURE_MANAGED_USERS)) {
1063 return false;
1064 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001065 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001066 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1067 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1068 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001069 return false;
1070 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001071 synchronized(mUsersLock) {
1072 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001073 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001074 return false;
1075 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001076 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1077 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001078 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001079 return usersCountAfterRemoving == 1
1080 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001081 }
1082 }
1083
Fyodor Kupolov82402752015-10-28 14:54:51 -07001084 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001085 int aliveUserCount = 0;
1086 final int totalUserCount = mUsers.size();
1087 // Skip over users being removed
1088 for (int i = 0; i < totalUserCount; i++) {
1089 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001090 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001091 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001092 aliveUserCount++;
1093 }
1094 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001095 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001096 }
1097
1098 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001099 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001100 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1101 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1102 * permissions can make certain calls to the UserManager.
1103 *
1104 * @param message used as message if SecurityException is thrown
1105 * @throws SecurityException if the caller does not have enough privilege.
1106 */
1107 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1108 final int uid = Binder.getCallingUid();
1109 if (uid != Process.SYSTEM_UID && uid != 0
1110 && ActivityManager.checkComponentPermission(
1111 Manifest.permission.MANAGE_USERS,
1112 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1113 && ActivityManager.checkComponentPermission(
1114 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1115 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1116 throw new SecurityException(
1117 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1118 + message);
1119 }
1120 }
1121
1122 /**
1123 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001124 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001125 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001126 *
1127 * @param message used as message if SecurityException is thrown
1128 * @throws SecurityException if the caller is not system or root
1129 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001130 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001131 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001132 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001133 && ActivityManager.checkComponentPermission(
1134 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001135 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1136 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1137 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001138 }
1139
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001140 /**
1141 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1142 * UserManager.
1143 *
1144 * @param message used as message if SecurityException is thrown
1145 * @throws SecurityException if the caller is not system or root
1146 */
1147 private static void checkSystemOrRoot(String message) {
1148 final int uid = Binder.getCallingUid();
1149 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1150 throw new SecurityException("Only system may: " + message);
1151 }
1152 }
1153
Fyodor Kupolov82402752015-10-28 14:54:51 -07001154 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001155 try {
1156 File dir = new File(mUsersDir, Integer.toString(info.id));
1157 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001158 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001159 if (!dir.exists()) {
1160 dir.mkdir();
1161 FileUtils.setPermissions(
1162 dir.getPath(),
1163 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1164 -1, -1);
1165 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001166 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001167 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1168 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001169 info.iconPath = file.getAbsolutePath();
1170 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001171 try {
1172 os.close();
1173 } catch (IOException ioe) {
1174 // What the ... !
1175 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001176 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001177 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001178 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001179 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001180 }
1181
Amith Yamasani0b285492011-04-14 17:35:23 -07001182 /**
1183 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1184 * cache it elsewhere.
1185 * @return the array of user ids.
1186 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001187 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001188 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001189 return mUserIds;
1190 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001191 }
1192
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001193 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001194 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001195 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001196 return;
1197 }
1198 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001199 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001201 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001202 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001203 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001204 int type;
1205 while ((type = parser.next()) != XmlPullParser.START_TAG
1206 && type != XmlPullParser.END_DOCUMENT) {
1207 ;
1208 }
1209
1210 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001211 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001212 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001213 return;
1214 }
1215
Amith Yamasani2a003292012-08-14 18:25:45 -07001216 mNextSerialNumber = -1;
1217 if (parser.getName().equals(TAG_USERS)) {
1218 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1219 if (lastSerialNumber != null) {
1220 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1221 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001222 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1223 if (versionNumber != null) {
1224 mUserVersion = Integer.parseInt(versionNumber);
1225 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001226 }
1227
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001228 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1229
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001230 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301231 if (type == XmlPullParser.START_TAG) {
1232 final String name = parser.getName();
1233 if (name.equals(TAG_USER)) {
1234 String id = parser.getAttributeValue(null, ATTR_ID);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001235 Pair<UserInfo, String> userPair = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001236
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001237 if (userPair != null) {
1238 UserInfo user = userPair.first;
1239 String account = userPair.second;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001240 synchronized (mUsersLock) {
1241 mUsers.put(user.id, user);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001242 mUserAccounts.put(user.id, account);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001243 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1244 mNextSerialNumber = user.id + 1;
1245 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301246 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001247 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301248 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001249 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1250 && type != XmlPullParser.END_TAG) {
1251 if (type == XmlPullParser.START_TAG) {
1252 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001253 synchronized (mGuestRestrictions) {
1254 UserRestrictionsUtils
1255 .readRestrictions(parser, mGuestRestrictions);
1256 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001257 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1258 ) {
1259 UserRestrictionsUtils.readRestrictions(parser,
1260 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001261 }
1262 break;
1263 }
1264 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001265 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001266 }
1267 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001268 synchronized (mRestrictionsLock) {
1269 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1270 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001271 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001272 upgradeIfNecessaryLP();
1273 } catch (IOException | XmlPullParserException e) {
1274 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001275 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001276 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001277 }
1278 }
1279
Amith Yamasani6f34b412012-10-22 18:19:27 -07001280 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001281 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001282 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001283 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001284 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001285 int userVersion = mUserVersion;
1286 if (userVersion < 1) {
1287 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001288 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001289 if ("Primary".equals(user.name)) {
1290 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001291 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001292 }
1293 userVersion = 1;
1294 }
1295
Amith Yamasanibc9625052012-11-15 14:39:18 -08001296 if (userVersion < 2) {
1297 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001298 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001299 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1300 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001301 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001302 }
1303 userVersion = 2;
1304 }
1305
Amith Yamasani350962c2013-08-06 11:18:53 -07001306
Amith Yamasani5e486f52013-08-07 11:06:44 -07001307 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001308 userVersion = 4;
1309 }
1310
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001311 if (userVersion < 5) {
1312 initDefaultGuestRestrictions();
1313 userVersion = 5;
1314 }
1315
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001316 if (userVersion < 6) {
1317 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001318 synchronized (mUsersLock) {
1319 for (int i = 0; i < mUsers.size(); i++) {
1320 UserInfo user = mUsers.valueAt(i);
1321 // In non-split mode, only user 0 can have restricted profiles
1322 if (!splitSystemUser && user.isRestricted()
1323 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1324 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001325 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001326 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001327 }
1328 }
1329 userVersion = 6;
1330 }
1331
Amith Yamasani6f34b412012-10-22 18:19:27 -07001332 if (userVersion < USER_VERSION) {
1333 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1334 + USER_VERSION);
1335 } else {
1336 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337
1338 if (originalVersion < mUserVersion) {
1339 writeUserListLP();
1340 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001341 }
1342 }
1343
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001344 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001345 int flags = UserInfo.FLAG_INITIALIZED;
1346 // In split system user mode, the admin and primary flags are assigned to the first human
1347 // user.
1348 if (!UserManager.isSplitSystemUser()) {
1349 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1350 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001351 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001352 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001353 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001354 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001355 synchronized (mUsersLock) {
1356 mUsers.put(system.id, system);
1357 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001358 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001359 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001360
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001361 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001362 synchronized (mRestrictionsLock) {
1363 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1364 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001365
Fyodor Kupolov82402752015-10-28 14:54:51 -07001366 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001367 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001368
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001369 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001370 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001371 }
1372
Makoto Onuki9e935a32015-11-06 14:24:24 -08001373 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001374 if (DBG) {
1375 debug("scheduleWriteUser");
1376 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001377 // No need to wrap it within a lock -- worst case, we'll just post the same message
1378 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001379 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1380 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1381 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1382 }
1383 }
1384
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 /*
1386 * Writes the user file in this format:
1387 *
1388 * <user flags="20039023" id="0">
1389 * <name>Primary</name>
1390 * </user>
1391 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001392 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001393 if (DBG) {
1394 debug("writeUserLP " + userInfo);
1395 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001396 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001397 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001398 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001399 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001400 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1401
1402 // XmlSerializer serializer = XmlUtils.serializerInstance();
1403 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001404 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001405 serializer.startDocument(null, true);
1406 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1407
1408 serializer.startTag(null, TAG_USER);
1409 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001410 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001411 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001412 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1413 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1414 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001415 if (userInfo.iconPath != null) {
1416 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1417 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001418 if (userInfo.partial) {
1419 serializer.attribute(null, ATTR_PARTIAL, "true");
1420 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001421 if (userInfo.guestToRemove) {
1422 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1423 }
Kenny Guy2a764942014-04-02 13:29:20 +01001424 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1425 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1426 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001427 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001428 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1429 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1430 Integer.toString(userInfo.restrictedProfileParentId));
1431 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001432 serializer.startTag(null, TAG_NAME);
1433 serializer.text(userInfo.name);
1434 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001435 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 UserRestrictionsUtils.writeRestrictions(serializer,
1437 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1438 UserRestrictionsUtils.writeRestrictions(serializer,
1439 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1440 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001441 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001442 // Update the account field if it is set.
1443 String account;
1444 synchronized (mUsersLock) {
1445 account = mUserAccounts.get(userInfo.id);
1446 }
1447 if (account != null) {
1448 serializer.startTag(null, TAG_ACCOUNT);
1449 serializer.text(account);
1450 serializer.endTag(null, TAG_ACCOUNT);
1451 }
1452
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001453 serializer.endTag(null, TAG_USER);
1454
1455 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001456 userFile.finishWrite(fos);
1457 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001458 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001459 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001460 }
1461 }
1462
1463 /*
1464 * Writes the user list file in this format:
1465 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001466 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001467 * <user id="0"></user>
1468 * <user id="2"></user>
1469 * </users>
1470 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001471 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 if (DBG) {
1473 debug("writeUserList");
1474 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001475 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001476 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001477 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001478 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001479 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1480
1481 // XmlSerializer serializer = XmlUtils.serializerInstance();
1482 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001483 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001484 serializer.startDocument(null, true);
1485 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1486
1487 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001488 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001489 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001490
Adam Lesinskieddeb492014-09-08 17:50:03 -07001491 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001492 synchronized (mGuestRestrictions) {
1493 UserRestrictionsUtils
1494 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1495 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301496 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001497 synchronized (mRestrictionsLock) {
1498 UserRestrictionsUtils.writeRestrictions(serializer,
1499 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1500 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001501 int[] userIdsToWrite;
1502 synchronized (mUsersLock) {
1503 userIdsToWrite = new int[mUsers.size()];
1504 for (int i = 0; i < userIdsToWrite.length; i++) {
1505 UserInfo user = mUsers.valueAt(i);
1506 userIdsToWrite[i] = user.id;
1507 }
1508 }
1509 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001510 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001511 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001512 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 }
1514
1515 serializer.endTag(null, TAG_USERS);
1516
1517 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001518 userListFile.finishWrite(fos);
1519 } catch (Exception e) {
1520 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001521 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001522 }
1523 }
1524
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001525 private Pair<UserInfo, String> readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001526 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001527 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001528 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001529 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001530 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001531 long creationTime = 0L;
1532 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001533 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001534 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001535 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001536 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 Bundle baseRestrictions = new Bundle();
1538 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001539
1540 FileInputStream fis = null;
1541 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001542 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001543 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001544 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001545 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001546 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001547 int type;
1548 while ((type = parser.next()) != XmlPullParser.START_TAG
1549 && type != XmlPullParser.END_DOCUMENT) {
1550 ;
1551 }
1552
1553 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001554 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001555 return null;
1556 }
1557
1558 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001559 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1560 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001561 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001562 return null;
1563 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001564 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1565 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001566 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001567 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1568 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001569 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1570 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001571 restrictedProfileParentId = readIntAttribute(parser,
1572 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001573 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1574 if ("true".equals(valueString)) {
1575 partial = true;
1576 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001577 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1578 if ("true".equals(valueString)) {
1579 guestToRemove = true;
1580 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001581
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001582 int outerDepth = parser.getDepth();
1583 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1584 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1585 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1586 continue;
1587 }
1588 String tag = parser.getName();
1589 if (TAG_NAME.equals(tag)) {
1590 type = parser.next();
1591 if (type == XmlPullParser.TEXT) {
1592 name = parser.getText();
1593 }
1594 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1596 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1597 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001598 } else if (TAG_ACCOUNT.equals(tag)) {
1599 type = parser.next();
1600 if (type == XmlPullParser.TEXT) {
1601 account = parser.getText();
1602 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001603 }
1604 }
1605 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001607 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001608 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001609 userInfo.creationTime = creationTime;
1610 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001611 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001612 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001613 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001614 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001615 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001616 mBaseUserRestrictions.put(id, baseRestrictions);
1617 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001618 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001619 return new Pair<>(userInfo, account);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620
1621 } catch (IOException ioe) {
1622 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001623 } finally {
1624 if (fis != null) {
1625 try {
1626 fis.close();
1627 } catch (IOException e) {
1628 }
1629 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001630 }
1631 return null;
1632 }
1633
Amith Yamasani920ace02012-09-20 22:15:37 -07001634 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1635 String valueString = parser.getAttributeValue(null, attr);
1636 if (valueString == null) return defaultValue;
1637 try {
1638 return Integer.parseInt(valueString);
1639 } catch (NumberFormatException nfe) {
1640 return defaultValue;
1641 }
1642 }
1643
1644 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1645 String valueString = parser.getAttributeValue(null, attr);
1646 if (valueString == null) return defaultValue;
1647 try {
1648 return Long.parseLong(valueString);
1649 } catch (NumberFormatException nfe) {
1650 return defaultValue;
1651 }
1652 }
1653
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001654 private boolean isPackageInstalled(String pkg, int userId) {
1655 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1656 PackageManager.GET_UNINSTALLED_PACKAGES,
1657 userId);
1658 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1659 return false;
1660 }
1661 return true;
1662 }
1663
Amith Yamasanib82add22013-07-09 11:24:44 -07001664 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001665 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001666 * Does not do any permissions checking.
1667 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001668 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001669 synchronized (mPackagesLock) {
1670 File dir = Environment.getUserSystemDirectory(userId);
1671 String[] files = dir.list();
1672 if (files == null) return;
1673 for (String fileName : files) {
1674 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1675 File resFile = new File(dir, fileName);
1676 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001677 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001678 }
1679 }
1680 }
1681 }
1682 }
1683
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001684 /**
1685 * Removes the app restrictions file for a specific package and user id, if it exists.
1686 */
1687 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1688 synchronized (mPackagesLock) {
1689 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001690 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001691 if (resFile.exists()) {
1692 resFile.delete();
1693 }
1694 }
1695 }
1696
Kenny Guya52dc3e2014-02-11 15:33:14 +00001697 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001698 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001699 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001700 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001701 }
1702
Amith Yamasani258848d2012-08-10 17:06:33 -07001703 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001704 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001705 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001706 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001707 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001708
Jessica Hummelbe81c802014-04-22 15:49:22 +01001709 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001710 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001711 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1712 return null;
1713 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001714 if (ActivityManager.isLowRamDeviceStatic()) {
1715 return null;
1716 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001717 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001718 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001719 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001720 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001721 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001722 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001723 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001724 synchronized (mPackagesLock) {
1725 UserInfo parent = null;
1726 if (parentId != UserHandle.USER_NULL) {
1727 synchronized (mUsersLock) {
1728 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001729 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001730 if (parent == null) return null;
1731 }
1732 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1733 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1734 return null;
1735 }
1736 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1737 // If we're not adding a guest user or a managed profile and the limit has
1738 // been reached, cannot add a user.
1739 return null;
1740 }
1741 // If we're adding a guest and there already exists one, bail.
1742 if (isGuest && findCurrentGuestUser() != null) {
1743 return null;
1744 }
1745 // In legacy mode, restricted profile's parent can only be the owner user
1746 if (isRestricted && !UserManager.isSplitSystemUser()
1747 && (parentId != UserHandle.USER_SYSTEM)) {
1748 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1749 return null;
1750 }
1751 if (isRestricted && UserManager.isSplitSystemUser()) {
1752 if (parent == null) {
1753 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1754 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001755 return null;
1756 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001757 if (!parent.canHaveProfile()) {
1758 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1759 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001760 return null;
1761 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001762 }
1763 // In split system user mode, we assign the first human user the primary flag.
1764 // And if there is no device owner, we also assign the admin flag to primary user.
1765 if (UserManager.isSplitSystemUser()
1766 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1767 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001768 synchronized (mUsersLock) {
1769 if (!mIsDeviceManaged) {
1770 flags |= UserInfo.FLAG_ADMIN;
1771 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001772 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001773 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001774
1775 if (parent != null && parent.isEphemeral()) {
1776 flags |= UserInfo.FLAG_EPHEMERAL;
1777 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001778 userId = getNextAvailableId();
1779 userInfo = new UserInfo(userId, name, null, flags);
1780 userInfo.serialNumber = mNextSerialNumber++;
1781 long now = System.currentTimeMillis();
1782 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1783 userInfo.partial = true;
1784 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1785 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001786 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001787 }
1788 writeUserListLP();
1789 if (parent != null) {
1790 if (isManagedProfile) {
1791 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1792 parent.profileGroupId = parent.id;
1793 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001794 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001795 userInfo.profileGroupId = parent.profileGroupId;
1796 } else if (isRestricted) {
1797 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1798 parent.restrictedProfileParentId = parent.id;
1799 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001800 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001801 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001802 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001803 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001804 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001805 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001806 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001807 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1808 final String volumeUuid = vol.getFsUuid();
1809 try {
1810 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001811 storage.prepareUserStorage(
1812 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001813 enforceSerialNumber(userDir, userInfo.serialNumber);
1814 } catch (IOException e) {
1815 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1816 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001817 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001818 mPm.createNewUser(userId);
1819 userInfo.partial = false;
1820 synchronized (mPackagesLock) {
1821 writeUserLP(userInfo);
1822 }
1823 updateUserIds();
1824 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001825 if (isGuest) {
1826 synchronized (mGuestRestrictions) {
1827 restrictions.putAll(mGuestRestrictions);
1828 }
1829 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001830 synchronized (mRestrictionsLock) {
1831 mBaseUserRestrictions.append(userId, restrictions);
1832 }
1833 mPm.newUserCreated(userId);
1834 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1835 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1836 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1837 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001838 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001839 } finally {
1840 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001841 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001842 return userInfo;
1843 }
1844
Amith Yamasani0b285492011-04-14 17:35:23 -07001845 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001846 * @hide
1847 */
1848 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1849 checkManageUsersPermission("setupRestrictedProfile");
1850 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1851 if (user == null) {
1852 return null;
1853 }
1854 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1855 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1856 // the putIntForUser() will fail.
1857 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1858 android.provider.Settings.Secure.LOCATION_MODE,
1859 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1860 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1861 return user;
1862 }
1863
1864 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001865 * Find the current guest user. If the Guest user is partial,
1866 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001867 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001868 private UserInfo findCurrentGuestUser() {
1869 synchronized (mUsersLock) {
1870 final int size = mUsers.size();
1871 for (int i = 0; i < size; i++) {
1872 final UserInfo user = mUsers.valueAt(i);
1873 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1874 return user;
1875 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001876 }
1877 }
1878 return null;
1879 }
1880
1881 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001882 * Mark this guest user for deletion to allow us to create another guest
1883 * and switch to that user before actually removing this guest.
1884 * @param userHandle the userid of the current guest
1885 * @return whether the user could be marked for deletion
1886 */
1887 public boolean markGuestForDeletion(int userHandle) {
1888 checkManageUsersPermission("Only the system can remove users");
1889 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1890 UserManager.DISALLOW_REMOVE_USER, false)) {
1891 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1892 return false;
1893 }
1894
1895 long ident = Binder.clearCallingIdentity();
1896 try {
1897 final UserInfo user;
1898 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001899 synchronized (mUsersLock) {
1900 user = mUsers.get(userHandle);
1901 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1902 return false;
1903 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001904 }
1905 if (!user.isGuest()) {
1906 return false;
1907 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001908 // We set this to a guest user that is to be removed. This is a temporary state
1909 // where we are allowed to add new Guest users, even if this one is still not
1910 // removed. This user will still show up in getUserInfo() calls.
1911 // If we don't get around to removing this Guest user, it will be purged on next
1912 // startup.
1913 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001914 // Mark it as disabled, so that it isn't returned any more when
1915 // profiles are queried.
1916 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001917 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001918 }
1919 } finally {
1920 Binder.restoreCallingIdentity(ident);
1921 }
1922 return true;
1923 }
1924
1925 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001926 * Removes a user and all data directories created for that user. This method should be called
1927 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001928 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001929 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001930 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001931 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001932 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1933 UserManager.DISALLOW_REMOVE_USER, false)) {
1934 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1935 return false;
1936 }
1937
Kenny Guyee58b4f2014-05-23 15:19:53 +01001938 long ident = Binder.clearCallingIdentity();
1939 try {
1940 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001941 int currentUser = ActivityManager.getCurrentUser();
1942 if (currentUser == userHandle) {
1943 Log.w(LOG_TAG, "Current user cannot be removed");
1944 return false;
1945 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001946 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001947 synchronized (mUsersLock) {
1948 user = mUsers.get(userHandle);
1949 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1950 return false;
1951 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001952
Fyodor Kupolov82402752015-10-28 14:54:51 -07001953 // We remember deleted user IDs to prevent them from being
1954 // reused during the current boot; they can still be reused
1955 // after a reboot.
1956 mRemovingUserIds.put(userHandle, true);
1957 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001958
Kenny Guyee58b4f2014-05-23 15:19:53 +01001959 try {
1960 mAppOpsService.removeUser(userHandle);
1961 } catch (RemoteException e) {
1962 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1963 }
1964 // Set this to a partially created user, so that the user will be purged
1965 // on next startup, in case the runtime stops now before stopping and
1966 // removing the user completely.
1967 user.partial = true;
1968 // Mark it as disabled, so that it isn't returned any more when
1969 // profiles are queried.
1970 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001971 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001972 }
1973
1974 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1975 && user.isManagedProfile()) {
1976 // Send broadcast to notify system that the user removed was a
1977 // managed user.
1978 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1979 }
1980
1981 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1982 int res;
1983 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001984 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1985 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001986 @Override
1987 public void userStopped(int userId) {
1988 finishRemoveUser(userId);
1989 }
1990 @Override
1991 public void userStopAborted(int userId) {
1992 }
1993 });
1994 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001995 return false;
1996 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001997 return res == ActivityManager.USER_OP_SUCCESS;
1998 } finally {
1999 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002000 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002001 }
2002
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002003 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002004 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002005 // Let other services shutdown any activity and clean up their state before completely
2006 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002007 long ident = Binder.clearCallingIdentity();
2008 try {
2009 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2010 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002011 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2012 android.Manifest.permission.MANAGE_USERS,
2013
2014 new BroadcastReceiver() {
2015 @Override
2016 public void onReceive(Context context, Intent intent) {
2017 if (DBG) {
2018 Slog.i(LOG_TAG,
2019 "USER_REMOVED broadcast sent, cleaning up user data "
2020 + userHandle);
2021 }
2022 new Thread() {
2023 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002024 // Clean up any ActivityManager state
2025 LocalServices.getService(ActivityManagerInternal.class)
2026 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002027 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002028 }
2029 }.start();
2030 }
2031 },
2032
2033 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002037 }
2038
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002039 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002040 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002041 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002042 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002043
2044 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002045 synchronized (mUsersLock) {
2046 mUsers.remove(userHandle);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002047 mUserAccounts.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002048 mIsUserManaged.delete(userHandle);
2049 }
2050 synchronized (mRestrictionsLock) {
2051 mBaseUserRestrictions.remove(userHandle);
2052 mAppliedUserRestrictions.remove(userHandle);
2053 mCachedEffectiveUserRestrictions.remove(userHandle);
2054 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002055 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002056 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002057 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002058 userFile.delete();
2059 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002060 synchronized (mPackagesLock) {
2061 writeUserListLP();
2062 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002063 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002064 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
2065 }
2066
Amith Yamasani61f57372012-08-31 12:12:28 -07002067 private void removeDirectoryRecursive(File parent) {
2068 if (parent.isDirectory()) {
2069 String[] files = parent.list();
2070 for (String filename : files) {
2071 File child = new File(parent, filename);
2072 removeDirectoryRecursive(child);
2073 }
2074 }
2075 parent.delete();
2076 }
2077
Kenny Guyf8d3a232014-05-15 16:09:52 +01002078 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002079 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002080 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2081 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002082 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002083 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002084 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002085 }
2086
Amith Yamasani2a003292012-08-14 18:25:45 -07002087 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002088 public Bundle getApplicationRestrictions(String packageName) {
2089 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2090 }
2091
2092 @Override
2093 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002094 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002095 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002096 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002097 }
2098 synchronized (mPackagesLock) {
2099 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002100 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002101 }
2102 }
2103
2104 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002105 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002106 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002107 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002108 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002109 if (restrictions == null || restrictions.isEmpty()) {
2110 cleanAppRestrictionsForPackage(packageName, userId);
2111 } else {
2112 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002113 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002114 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002115 }
Robin Lee66e5d962014-04-09 16:44:21 +01002116
Kenny Guyd21b2182014-07-17 16:38:55 +01002117 if (isPackageInstalled(packageName, userId)) {
2118 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2119 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2120 changeIntent.setPackage(packageName);
2121 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2122 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2123 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002124 }
2125
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002126 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002127 mHandler.post(new Runnable() {
2128 @Override
2129 public void run() {
2130 List<ApplicationInfo> apps =
2131 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2132 userHandle).getList();
2133 final long ident = Binder.clearCallingIdentity();
2134 try {
2135 for (ApplicationInfo appInfo : apps) {
2136 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002137 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2138 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002139 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002140 userHandle);
2141 }
2142 }
2143 } finally {
2144 Binder.restoreCallingIdentity(ident);
2145 }
2146 }
2147 });
2148 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002149 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002150 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002151 try {
2152 return mContext.getPackageManager().getApplicationInfo(packageName,
2153 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2154 } catch (NameNotFoundException nnfe) {
2155 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002156 } finally {
2157 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002158 }
2159 }
2160
Fyodor Kupolov82402752015-10-28 14:54:51 -07002161 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002162 AtomicFile restrictionsFile =
2163 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2164 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002166 }
2167
2168 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002169 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002170 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002171 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002172 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002173 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002174 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002175
2176 FileInputStream fis = null;
2177 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002178 fis = restrictionsFile.openRead();
2179 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002180 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002181 XmlUtils.nextElement(parser);
2182 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002183 Slog.e(LOG_TAG, "Unable to read restrictions file "
2184 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002185 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002186 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002187 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2188 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002189 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002190 } catch (IOException|XmlPullParserException e) {
2191 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002192 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002193 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002194 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002195 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002196 }
2197
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002198 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2199 XmlPullParser parser) throws XmlPullParserException, IOException {
2200 int type = parser.getEventType();
2201 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2202 String key = parser.getAttributeValue(null, ATTR_KEY);
2203 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2204 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2205 if (multiple != null) {
2206 values.clear();
2207 int count = Integer.parseInt(multiple);
2208 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2209 if (type == XmlPullParser.START_TAG
2210 && parser.getName().equals(TAG_VALUE)) {
2211 values.add(parser.nextText().trim());
2212 count--;
2213 }
2214 }
2215 String [] valueStrings = new String[values.size()];
2216 values.toArray(valueStrings);
2217 restrictions.putStringArray(key, valueStrings);
2218 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2219 restrictions.putBundle(key, readBundleEntry(parser, values));
2220 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2221 final int outerDepth = parser.getDepth();
2222 ArrayList<Bundle> bundleList = new ArrayList<>();
2223 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2224 Bundle childBundle = readBundleEntry(parser, values);
2225 bundleList.add(childBundle);
2226 }
2227 restrictions.putParcelableArray(key,
2228 bundleList.toArray(new Bundle[bundleList.size()]));
2229 } else {
2230 String value = parser.nextText().trim();
2231 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2232 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2233 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2234 restrictions.putInt(key, Integer.parseInt(value));
2235 } else {
2236 restrictions.putString(key, value);
2237 }
2238 }
2239 }
2240 }
2241
2242 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2243 throws IOException, XmlPullParserException {
2244 Bundle childBundle = new Bundle();
2245 final int outerDepth = parser.getDepth();
2246 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2247 readEntry(childBundle, values, parser);
2248 }
2249 return childBundle;
2250 }
2251
Fyodor Kupolov82402752015-10-28 14:54:51 -07002252 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002253 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002254 AtomicFile restrictionsFile = new AtomicFile(
2255 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002256 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002257 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002258 }
2259
2260 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002261 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002262 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002263 try {
2264 fos = restrictionsFile.startWrite();
2265 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2266
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002267 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002268 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002269 serializer.startDocument(null, true);
2270 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2271
2272 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002273 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002274 serializer.endTag(null, TAG_RESTRICTIONS);
2275
2276 serializer.endDocument();
2277 restrictionsFile.finishWrite(fos);
2278 } catch (Exception e) {
2279 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002280 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2281 }
2282 }
2283
2284 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2285 throws IOException {
2286 for (String key : restrictions.keySet()) {
2287 Object value = restrictions.get(key);
2288 serializer.startTag(null, TAG_ENTRY);
2289 serializer.attribute(null, ATTR_KEY, key);
2290
2291 if (value instanceof Boolean) {
2292 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2293 serializer.text(value.toString());
2294 } else if (value instanceof Integer) {
2295 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2296 serializer.text(value.toString());
2297 } else if (value == null || value instanceof String) {
2298 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2299 serializer.text(value != null ? (String) value : "");
2300 } else if (value instanceof Bundle) {
2301 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2302 writeBundle((Bundle) value, serializer);
2303 } else if (value instanceof Parcelable[]) {
2304 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2305 Parcelable[] array = (Parcelable[]) value;
2306 for (Parcelable parcelable : array) {
2307 if (!(parcelable instanceof Bundle)) {
2308 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2309 }
2310 serializer.startTag(null, TAG_ENTRY);
2311 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2312 writeBundle((Bundle) parcelable, serializer);
2313 serializer.endTag(null, TAG_ENTRY);
2314 }
2315 } else {
2316 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2317 String[] values = (String[]) value;
2318 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2319 for (String choice : values) {
2320 serializer.startTag(null, TAG_VALUE);
2321 serializer.text(choice != null ? choice : "");
2322 serializer.endTag(null, TAG_VALUE);
2323 }
2324 }
2325 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002326 }
2327 }
2328
2329 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002330 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002331 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002332 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002333 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002334 }
2335 }
2336
2337 @Override
2338 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002339 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002340 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002341 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002342 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002343 }
2344 // Not found
2345 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002346 }
2347 }
2348
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002349 @Override
2350 public long getUserCreationTime(int userHandle) {
2351 int callingUserId = UserHandle.getCallingUserId();
2352 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002353 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002354 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002355 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002356 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002357 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002358 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002359 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002360 }
2361 }
2362 }
2363 if (userInfo == null) {
2364 throw new SecurityException("userHandle can only be the calling user or a managed "
2365 + "profile associated with this user");
2366 }
2367 return userInfo.creationTime;
2368 }
2369
Amith Yamasani0b285492011-04-14 17:35:23 -07002370 /**
2371 * Caches the list of user ids in an array, adjusting the array size when necessary.
2372 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002373 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002374 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002375 synchronized (mUsersLock) {
2376 final int userSize = mUsers.size();
2377 for (int i = 0; i < userSize; i++) {
2378 if (!mUsers.valueAt(i).partial) {
2379 num++;
2380 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002381 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002382 final int[] newUsers = new int[num];
2383 int n = 0;
2384 for (int i = 0; i < userSize; i++) {
2385 if (!mUsers.valueAt(i).partial) {
2386 newUsers[n++] = mUsers.keyAt(i);
2387 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002388 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002389 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002390 }
2391 }
2392
2393 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002394 * Called right before a user starts. This will not be called for the system user.
2395 */
2396 public void onBeforeStartUser(int userId) {
2397 synchronized (mRestrictionsLock) {
2398 applyUserRestrictionsLR(userId);
2399 }
2400 }
2401
2402 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002403 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002404 * @param userId the user that was just foregrounded
2405 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002406 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002407 UserInfo user = getUserInfoNoChecks(userId);
2408 if (user == null || user.partial) {
2409 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2410 return;
2411 }
2412 long now = System.currentTimeMillis();
2413 if (now > EPOCH_PLUS_30_YEARS) {
2414 user.lastLoggedInTime = now;
2415 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002416 }
2417 }
2418
2419 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002420 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002421 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2422 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002423 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 private int getNextAvailableId() {
2425 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002426 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002427 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002428 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002429 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002430 }
2431 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002432 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002433 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002434 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002435 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002436
Amith Yamasanifc95e702013-09-26 13:20:17 -07002437 private String packageToRestrictionsFileName(String packageName) {
2438 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2439 }
2440
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002441 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002442 * Enforce that serial number stored in user directory inode matches the
2443 * given expected value. Gracefully sets the serial number if currently
2444 * undefined.
2445 *
2446 * @throws IOException when problem extracting serial number, or serial
2447 * number is mismatched.
2448 */
2449 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2450 final int foundSerial = getSerialNumber(file);
2451 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2452
2453 if (foundSerial == -1) {
2454 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2455 try {
2456 setSerialNumber(file, serialNumber);
2457 } catch (IOException e) {
2458 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2459 }
2460
2461 } else if (foundSerial != serialNumber) {
2462 throw new IOException("Found serial number " + foundSerial
2463 + " doesn't match expected " + serialNumber);
2464 }
2465 }
2466
2467 /**
2468 * Set serial number stored in user directory inode.
2469 *
2470 * @throws IOException if serial number was already set
2471 */
2472 private static void setSerialNumber(File file, int serialNumber)
2473 throws IOException {
2474 try {
2475 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2476 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2477 } catch (ErrnoException e) {
2478 throw e.rethrowAsIOException();
2479 }
2480 }
2481
2482 /**
2483 * Return serial number stored in user directory inode.
2484 *
2485 * @return parsed serial number, or -1 if not set
2486 */
2487 private static int getSerialNumber(File file) throws IOException {
2488 try {
2489 final byte[] buf = new byte[256];
2490 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2491 final String serial = new String(buf, 0, len);
2492 try {
2493 return Integer.parseInt(serial);
2494 } catch (NumberFormatException e) {
2495 throw new IOException("Bad serial number: " + serial);
2496 }
2497 } catch (ErrnoException e) {
2498 if (e.errno == OsConstants.ENODATA) {
2499 return -1;
2500 } else {
2501 throw e.rethrowAsIOException();
2502 }
2503 }
2504 }
2505
Amith Yamasani920ace02012-09-20 22:15:37 -07002506 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002507 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2508 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2509 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2510 }
2511
2512 int onShellCommand(Shell shell, String cmd) {
2513 if (cmd == null) {
2514 return shell.handleDefaultCommands(cmd);
2515 }
2516
2517 final PrintWriter pw = shell.getOutPrintWriter();
2518 try {
2519 switch(cmd) {
2520 case "list":
2521 return runList(pw);
2522 }
2523 } catch (RemoteException e) {
2524 pw.println("Remote exception: " + e);
2525 }
2526 return -1;
2527 }
2528
2529 private int runList(PrintWriter pw) throws RemoteException {
2530 final IActivityManager am = ActivityManagerNative.getDefault();
2531 final List<UserInfo> users = getUsers(false);
2532 if (users == null) {
2533 pw.println("Error: couldn't get users");
2534 return 1;
2535 } else {
2536 pw.println("Users:");
2537 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002538 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002539 pw.println("\t" + users.get(i).toString() + running);
2540 }
2541 return 0;
2542 }
2543 }
2544
2545 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002546 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2547 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2548 != PackageManager.PERMISSION_GRANTED) {
2549 pw.println("Permission Denial: can't dump UserManager from from pid="
2550 + Binder.getCallingPid()
2551 + ", uid=" + Binder.getCallingUid()
2552 + " without permission "
2553 + android.Manifest.permission.DUMP);
2554 return;
2555 }
2556
2557 long now = System.currentTimeMillis();
2558 StringBuilder sb = new StringBuilder();
2559 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002560 synchronized (mUsersLock) {
2561 pw.println("Users:");
2562 for (int i = 0; i < mUsers.size(); i++) {
2563 UserInfo user = mUsers.valueAt(i);
2564 if (user == null) {
2565 continue;
2566 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002567 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002568 pw.print(" "); pw.print(user);
2569 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002570 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002571 pw.print(" <removing> ");
2572 }
2573 if (user.partial) {
2574 pw.print(" <partial>");
2575 }
2576 pw.println();
2577 pw.print(" Created: ");
2578 if (user.creationTime == 0) {
2579 pw.println("<unknown>");
2580 } else {
2581 sb.setLength(0);
2582 TimeUtils.formatDuration(now - user.creationTime, sb);
2583 sb.append(" ago");
2584 pw.println(sb);
2585 }
2586 pw.print(" Last logged in: ");
2587 if (user.lastLoggedInTime == 0) {
2588 pw.println("<unknown>");
2589 } else {
2590 sb.setLength(0);
2591 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2592 sb.append(" ago");
2593 pw.println(sb);
2594 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002595 pw.print(" Has profile owner: ");
2596 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002597 pw.println(" Restrictions:");
2598 synchronized (mRestrictionsLock) {
2599 UserRestrictionsUtils.dumpRestrictions(
2600 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002601 pw.println(" Device policy local restrictions:");
2602 UserRestrictionsUtils.dumpRestrictions(
2603 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002604 pw.println(" Effective restrictions:");
2605 UserRestrictionsUtils.dumpRestrictions(
2606 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2607 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002608 pw.println();
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002609 String accountName = mUserAccounts.get(userId);
2610 if (accountName != null) {
2611 pw.print(" Account name: " + accountName);
2612 pw.println();
2613 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002614 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002615 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002616 pw.println(" Device policy global restrictions:");
2617 synchronized (mRestrictionsLock) {
2618 UserRestrictionsUtils
2619 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2620 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002621 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002622 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002623 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002624 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002625 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002626 synchronized (mUsersLock) {
2627 pw.println();
2628 pw.println(" Device managed: " + mIsDeviceManaged);
2629 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002630 }
2631 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002632
2633 final class MainHandler extends Handler {
2634
2635 @Override
2636 public void handleMessage(Message msg) {
2637 switch (msg.what) {
2638 case WRITE_USER_MSG:
2639 removeMessages(WRITE_USER_MSG, msg.obj);
2640 synchronized (mPackagesLock) {
2641 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002642 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002643 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002644 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002645 }
2646 }
2647 }
2648 }
2649 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002650
2651 /**
2652 * @param userId
2653 * @return whether the user has been initialized yet
2654 */
2655 boolean isInitialized(int userId) {
2656 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2657 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002658
2659 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002660 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002661 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2662 @Nullable Bundle globalRestrictions) {
2663 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2664 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002665 }
2666
2667 @Override
2668 public Bundle getBaseUserRestrictions(int userId) {
2669 synchronized (mRestrictionsLock) {
2670 return mBaseUserRestrictions.get(userId);
2671 }
2672 }
2673
2674 @Override
2675 public void setBaseUserRestrictionsByDpmsForMigration(
2676 int userId, Bundle baseRestrictions) {
2677 synchronized (mRestrictionsLock) {
2678 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002679 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002680 }
2681
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002683 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002684 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002685 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002686 } else {
2687 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2688 }
2689 }
2690 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002691
2692 @Override
2693 public boolean getUserRestriction(int userId, String key) {
2694 return getUserRestrictions(userId).getBoolean(key);
2695 }
2696
2697 @Override
2698 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2699 synchronized (mUserRestrictionsListeners) {
2700 mUserRestrictionsListeners.add(listener);
2701 }
2702 }
2703
2704 @Override
2705 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2706 synchronized (mUserRestrictionsListeners) {
2707 mUserRestrictionsListeners.remove(listener);
2708 }
2709 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002710
2711 @Override
2712 public void setDeviceManaged(boolean isManaged) {
2713 synchronized (mUsersLock) {
2714 mIsDeviceManaged = isManaged;
2715 }
2716 }
2717
2718 @Override
2719 public void setUserManaged(int userId, boolean isManaged) {
2720 synchronized (mUsersLock) {
2721 mIsUserManaged.put(userId, isManaged);
2722 }
2723 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002724 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002725
2726 private class Shell extends ShellCommand {
2727 @Override
2728 public int onCommand(String cmd) {
2729 return onShellCommand(this, cmd);
2730 }
2731
2732 @Override
2733 public void onHelp() {
2734 final PrintWriter pw = getOutPrintWriter();
2735 pw.println("User manager (user) commands:");
2736 pw.println(" help");
2737 pw.println(" Print this help text.");
2738 pw.println("");
2739 pw.println(" list");
2740 pw.println(" Prints all users on the system.");
2741 }
2742 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002743
2744 private static void debug(String message) {
2745 Log.d(LOG_TAG, message +
2746 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2747 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002748}