blob: ce6b3693c2d71661a71f6cefef1b25ee44cb61c6 [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
Clara Bayarria1771112015-12-18 16:29:18 +0000279 private final LockPatternUtils mLockPatternUtils;
280
Amith Yamasani258848d2012-08-10 17:06:33 -0700281 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700282
Dianne Hackborn4428e172012-08-24 17:43:05 -0700283 public static UserManagerService getInstance() {
284 synchronized (UserManagerService.class) {
285 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700286 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700287 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700288
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800289 @VisibleForTesting
290 UserManagerService(File dataDir) {
291 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700292 }
293
Dianne Hackborn4428e172012-08-24 17:43:05 -0700294 /**
295 * Called by package manager to create the service. This is closely
296 * associated with the package manager, and the given lock is the
297 * package manager's own lock.
298 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800299 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
300 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700301 }
302
Dianne Hackborn4428e172012-08-24 17:43:05 -0700303 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800304 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700305 mContext = context;
306 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700307 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800308 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800309 synchronized (mPackagesLock) {
310 mUsersDir = new File(dataDir, USER_INFO_DIR);
311 mUsersDir.mkdirs();
312 // Make zeroth user directory, for services to migrate their files to that location
313 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
314 userZeroDir.mkdirs();
315 FileUtils.setPermissions(mUsersDir.toString(),
316 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
317 -1, -1);
318 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
319 initDefaultGuestRestrictions();
320 readUserListLP();
321 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700322 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700323 mLocalService = new LocalService();
324 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000325 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700326 }
327
328 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100329 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800330 ArrayList<UserInfo> partials = new ArrayList<>();
331 synchronized (mUsersLock) {
332 final int userSize = mUsers.size();
333 for (int i = 0; i < userSize; i++) {
334 UserInfo ui = mUsers.valueAt(i);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100335 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700337 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700338 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700339 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800340 final int partialsSize = partials.size();
341 for (int i = 0; i < partialsSize; i++) {
342 UserInfo ui = partials.get(i);
343 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
344 + " (name=" + ui.name + ")");
345 removeUserState(ui.id);
346 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800347
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700348 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800349
Jason Monk62062992014-05-06 09:55:28 -0400350 mAppOpsService = IAppOpsService.Stub.asInterface(
351 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800352
353 synchronized (mRestrictionsLock) {
354 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400355 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700356 }
357
358 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800359 public String getUserAccount(int userId) {
360 checkManageUserAndAcrossUsersFullPermission("get user account");
361 synchronized (mUsersLock) {
362 return mUserAccounts.get(userId);
363 }
364 }
365
366 @Override
367 public void setUserAccount(int userId, String accountName) {
368 checkManageUserAndAcrossUsersFullPermission("set user account");
369 UserInfo userToUpdate = null;
370 synchronized (mPackagesLock) {
371 synchronized (mUsersLock) {
372 String currentAccount = mUserAccounts.get(userId);
373 if (!Objects.equal(currentAccount, accountName)) {
374 mUserAccounts.put(userId, accountName);
375 userToUpdate = mUsers.get(userId);
376 }
377 }
378
379 if (userToUpdate != null) {
380 writeUserLP(userToUpdate);
381 }
382 }
383 }
384
385 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700386 public UserInfo getPrimaryUser() {
387 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700388 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700389 final int userSize = mUsers.size();
390 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700391 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800392 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700393 return ui;
394 }
395 }
396 }
397 return null;
398 }
399
400 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700401 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700402 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700403 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700404 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700405 final int userSize = mUsers.size();
406 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700407 UserInfo ui = mUsers.valueAt(i);
408 if (ui.partial) {
409 continue;
410 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800411 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700412 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700413 }
Amith Yamasani13593602012-03-22 16:16:17 -0700414 }
415 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700416 }
Amith Yamasani13593602012-03-22 16:16:17 -0700417 }
418
Amith Yamasani258848d2012-08-10 17:06:33 -0700419 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100420 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800421 if (userId != UserHandle.getCallingUserId()) {
422 checkManageUsersPermission("getting profiles related to user " + userId);
423 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700424 final long ident = Binder.clearCallingIdentity();
425 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700426 synchronized (mUsersLock) {
427 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100428 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700429 } finally {
430 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000431 }
432 }
433
Amith Yamasanibe465322014-04-24 13:45:17 -0700434 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700435 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
436 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700437 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700438 if (user == null) {
439 // Probably a dying user
440 return users;
441 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700442 final int userSize = mUsers.size();
443 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700444 UserInfo profile = mUsers.valueAt(i);
445 if (!isProfileOf(user, profile)) {
446 continue;
447 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100448 if (enabledOnly && !profile.isEnabled()) {
449 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700450 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700451 if (mRemovingUserIds.get(profile.id)) {
452 continue;
453 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700454 users.add(profile);
455 }
456 return users;
457 }
458
Jessica Hummelbe81c802014-04-22 15:49:22 +0100459 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700460 public int getCredentialOwnerProfile(int userHandle) {
461 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000462 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700463 synchronized (mUsersLock) {
464 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700465 if (profileParent != null) {
466 return profileParent.id;
467 }
468 }
469 }
470
471 return userHandle;
472 }
473
474 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700475 public boolean isSameProfileGroup(int userId, int otherUserId) {
476 if (userId == otherUserId) return true;
477 checkManageUsersPermission("check if in the same profile group");
478 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700479 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700480 }
481 }
482
Fyodor Kupolov82402752015-10-28 14:54:51 -0700483 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
484 synchronized (mUsersLock) {
485 UserInfo userInfo = getUserInfoLU(userId);
486 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
487 return false;
488 }
489 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
490 if (otherUserInfo == null
491 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
492 return false;
493 }
494 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700495 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700496 }
497
498 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100499 public UserInfo getProfileParent(int userHandle) {
500 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700501 synchronized (mUsersLock) {
502 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700503 }
504 }
505
Fyodor Kupolov82402752015-10-28 14:54:51 -0700506 private UserInfo getProfileParentLU(int userHandle) {
507 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700508 if (profile == null) {
509 return null;
510 }
511 int parentUserId = profile.profileGroupId;
512 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
513 return null;
514 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700515 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100516 }
517 }
518
Fyodor Kupolov82402752015-10-28 14:54:51 -0700519 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100520 return user.id == profile.id ||
521 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
522 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000523 }
524
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000525 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
526 UserHandle parentHandle, Bundle extras) {
527 // Send intent to profile
528 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
529 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
530 intent.putExtras(extras);
531 mContext.sendBroadcastAsUser(intent, profileHandle);
532
533 // Send intent to parent
534 if (parentHandle != null) {
535 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
536 intent.putExtra(Intent.EXTRA_USER, profileHandle);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700537 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000538 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
539 intent.putExtras(extras);
540 mContext.sendBroadcastAsUser(intent, parentHandle);
541 }
542 }
543
544 @Override
545 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
546 checkManageUsersPermission("silence profile");
547 boolean changed = false;
548 UserInfo profile, parent;
549 synchronized (mPackagesLock) {
550 synchronized (mUsersLock) {
551 profile = getUserInfoLU(userHandle);
552 parent = getProfileParentLU(userHandle);
553
554 }
555 if (profile == null || !profile.isManagedProfile()) {
556 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
557 }
558 if (profile.isQuietModeEnabled() != enableQuietMode) {
559 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
560 writeUserLP(profile);
561 changed = true;
562 }
563 }
564 if (changed) {
565 Bundle extras = new Bundle();
566 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
567 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
568 parent != null ? parent.getUserHandle() : null, extras);
569 }
570 }
571
572 @Override
573 public boolean isQuietModeEnabled(int userHandle) {
574 synchronized (mPackagesLock) {
575 UserInfo info;
576 synchronized (mUsersLock) {
577 info = getUserInfoLU(userHandle);
578 }
579 if (info == null || !info.isManagedProfile()) {
580 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
581 }
582 return info.isQuietModeEnabled();
583 }
584 }
585
Kenny Guya52dc3e2014-02-11 15:33:14 +0000586 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100587 public void setUserEnabled(int userId) {
588 checkManageUsersPermission("enable user");
589 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700590 UserInfo info;
591 synchronized (mUsersLock) {
592 info = getUserInfoLU(userId);
593 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100594 if (info != null && !info.isEnabled()) {
595 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700596 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100597 }
598 }
599 }
600
601 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700602 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700603 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 synchronized (mUsersLock) {
605 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700606 }
607 }
608
Amith Yamasani71e6c692013-03-24 17:39:28 -0700609 @Override
610 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700611 synchronized (mUsersLock) {
612 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700613 }
614 }
615
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700616 @Override
617 public boolean canHaveRestrictedProfile(int userId) {
618 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 synchronized (mUsersLock) {
620 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700621 if (userInfo == null || !userInfo.canHaveProfile()) {
622 return false;
623 }
624 if (!userInfo.isAdmin()) {
625 return false;
626 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800627 // restricted profile can be created if there is no DO set and the admin user has no PO;
628 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700629 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700630 }
631
Amith Yamasani195263742012-08-21 15:40:12 -0700632 /*
633 * Should be locked on mUsers before calling this.
634 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700635 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700636 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700637 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800638 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700639 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
640 return null;
641 }
642 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700643 }
644
Fyodor Kupolov82402752015-10-28 14:54:51 -0700645 /**
646 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
647 * <p>No permissions checking or any addition checks are made</p>
648 */
649 private UserInfo getUserInfoNoChecks(int userId) {
650 synchronized (mUsersLock) {
651 return mUsers.get(userId);
652 }
653 }
654
Amith Yamasani236b2b52015-08-18 14:32:14 -0700655 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700656 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700658 }
659
Amith Yamasani258848d2012-08-10 17:06:33 -0700660 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700661 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700662 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700663 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700664 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700665 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700666 if (info == null || info.partial) {
667 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
668 return;
669 }
Amith Yamasani13593602012-03-22 16:16:17 -0700670 if (name != null && !name.equals(info.name)) {
671 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700672 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700673 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700674 }
675 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700676 if (changed) {
677 sendUserInfoChangedBroadcast(userId);
678 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700679 }
680
Amith Yamasani258848d2012-08-10 17:06:33 -0700681 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700682 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700683 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400684 long ident = Binder.clearCallingIdentity();
685 try {
686 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700687 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400688 if (info == null || info.partial) {
689 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
690 return;
691 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700692 writeBitmapLP(info, bitmap);
693 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700694 }
Jason Monk9a944532014-07-08 09:31:21 -0400695 sendUserInfoChangedBroadcast(userId);
696 } finally {
697 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700698 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700699 }
700
701 private void sendUserInfoChangedBroadcast(int userId) {
702 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
703 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
704 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700705 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700706 }
707
Amith Yamasani258848d2012-08-10 17:06:33 -0700708 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100709 public ParcelFileDescriptor getUserIcon(int userId) {
710 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700711 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700713 if (info == null || info.partial) {
714 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
715 return null;
716 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100718 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
719 || callingGroupId != info.profileGroupId) {
720 checkManageUsersPermission("get the icon of a user who is not related");
721 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700722 if (info.iconPath == null) {
723 return null;
724 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100725 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700726 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100727
728 try {
729 return ParcelFileDescriptor.open(
730 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
731 } catch (FileNotFoundException e) {
732 Log.e(LOG_TAG, "Couldn't find icon file", e);
733 }
734 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700735 }
736
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700737 public void makeInitialized(int userId) {
738 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800739 boolean scheduleWriteUser = false;
740 UserInfo info;
741 synchronized (mUsersLock) {
742 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700743 if (info == null || info.partial) {
744 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800745 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700746 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800747 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700748 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800749 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700750 }
751 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800752 if (scheduleWriteUser) {
753 scheduleWriteUser(info);
754 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700755 }
756
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700757 /**
758 * If default guest restrictions haven't been initialized yet, add the basic
759 * restrictions.
760 */
761 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800762 synchronized (mGuestRestrictions) {
763 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800764 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800765 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
766 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
767 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700768 }
769 }
770
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800771 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530772 public Bundle getDefaultGuestRestrictions() {
773 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800774 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530775 return new Bundle(mGuestRestrictions);
776 }
777 }
778
779 @Override
780 public void setDefaultGuestRestrictions(Bundle restrictions) {
781 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800782 synchronized (mGuestRestrictions) {
783 mGuestRestrictions.clear();
784 mGuestRestrictions.putAll(restrictions);
785 }
786 synchronized (mPackagesLock) {
787 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530788 }
789 }
790
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800791 /**
792 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
793 */
794 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
795 @Nullable Bundle global) {
796 Preconditions.checkNotNull(local);
797 boolean globalChanged = false;
798 boolean localChanged;
799 synchronized (mRestrictionsLock) {
800 if (global != null) {
801 // Update global.
802 globalChanged = !UserRestrictionsUtils.areEqual(
803 mDevicePolicyGlobalUserRestrictions, global);
804 if (globalChanged) {
805 mDevicePolicyGlobalUserRestrictions = global;
806 }
807 }
808 {
809 // Update local.
810 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
811 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
812 if (localChanged) {
813 mDevicePolicyLocalUserRestrictions.put(userId, local);
814 }
815 }
816 }
817 if (DBG) {
818 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
819 + " global=" + global + (globalChanged ? " (changed)" : "")
820 + " local=" + local + (localChanged ? " (changed)" : "")
821 );
822 }
823 // Don't call them within the mRestrictionsLock.
824 synchronized (mPackagesLock) {
825 if (globalChanged) {
826 writeUserListLP();
827 }
828 if (localChanged) {
829 writeUserLP(getUserInfoNoChecks(userId));
830 }
831 }
832
833 synchronized (mRestrictionsLock) {
834 if (globalChanged) {
835 applyUserRestrictionsForAllUsersLR();
836 } else if (localChanged) {
837 applyUserRestrictionsLR(userId);
838 }
839 }
840 }
841
Makoto Onuki068c54a2015-10-13 14:34:03 -0700842 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800844 final Bundle baseRestrictions =
845 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
846 final Bundle global = mDevicePolicyGlobalUserRestrictions;
847 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700848
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800849 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
850 // Common case first.
851 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700852 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800853 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
854 UserRestrictionsUtils.merge(effective, global);
855 UserRestrictionsUtils.merge(effective, local);
856
Makoto Onuki068c54a2015-10-13 14:34:03 -0700857 return effective;
858 }
859
860 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700861 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700862 if (DBG) {
863 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
864 }
865 mCachedEffectiveUserRestrictions.remove(userId);
866 }
867
868 private Bundle getEffectiveUserRestrictions(int userId) {
869 synchronized (mRestrictionsLock) {
870 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
871 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700873 mCachedEffectiveUserRestrictions.put(userId, restrictions);
874 }
875 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700876 }
877 }
878
Makoto Onuki068c54a2015-10-13 14:34:03 -0700879 /** @return a specific user restriction that's in effect currently. */
880 @Override
881 public boolean hasUserRestriction(String restrictionKey, int userId) {
882 Bundle restrictions = getEffectiveUserRestrictions(userId);
883 return restrictions != null && restrictions.getBoolean(restrictionKey);
884 }
885
886 /**
887 * @return UserRestrictions that are in effect currently. This always returns a new
888 * {@link Bundle}.
889 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700890 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800891 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800892 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800893 }
894
895 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000896 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
897 checkManageUsersPermission("hasBaseUserRestriction");
898 synchronized (mRestrictionsLock) {
899 Bundle bundle = mBaseUserRestrictions.get(userId);
900 return (bundle != null && bundle.getBoolean(restrictionKey, false));
901 }
902 }
903
904 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700905 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700906 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700907 synchronized (mRestrictionsLock) {
908 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
909 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800910 final Bundle newRestrictions = UserRestrictionsUtils.clone(
911 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700912 newRestrictions.putBoolean(key, value);
913
Fyodor Kupolov82402752015-10-28 14:54:51 -0700914 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700915 }
916 }
917
Makoto Onuki068c54a2015-10-13 14:34:03 -0700918 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800919 * Optionally updating user restrictions, calculate the effective user restrictions and also
920 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700921 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800922 * @param newRestrictions User restrictions to set.
923 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700924 * @param userId target user ID.
925 */
926 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700927 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700928 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800929
930 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
931 mAppliedUserRestrictions.get(userId));
932
933 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700934 if (newRestrictions != null) {
935 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800936 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
937
938 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700939 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
940 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800941
942 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
943 mBaseUserRestrictions.put(userId, newRestrictions);
944 scheduleWriteUser(getUserInfoNoChecks(userId));
945 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700946 }
947
Fyodor Kupolov82402752015-10-28 14:54:51 -0700948 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700949
Makoto Onuki759a7632015-10-28 16:43:10 -0700950 mCachedEffectiveUserRestrictions.put(userId, effective);
951
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800952 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700953 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800954 debug("Applying user restrictions: userId=" + userId
955 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700956 }
957
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800958 if (mAppOpsService != null) { // We skip it until system-ready.
959 final long token = Binder.clearCallingIdentity();
960 try {
961 mAppOpsService.setUserRestrictions(effective, userId);
962 } catch (RemoteException e) {
963 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
964 } finally {
965 Binder.restoreCallingIdentity(token);
966 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700967 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700968
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800969 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700970
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800971 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 }
973
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800974 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800975 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800976 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
977 // actually, but we still need some kind of synchronization otherwise we might end up
978 // calling listeners out-of-order, thus "LR".
979
980 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
981 return;
982 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800983
984 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
985 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
986
987 mHandler.post(new Runnable() {
988 @Override
989 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700990 UserRestrictionsUtils.applyUserRestrictions(
991 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800992
Makoto Onukid45a4a22015-11-02 17:17:38 -0800993 final UserRestrictionsListener[] listeners;
994 synchronized (mUserRestrictionsListeners) {
995 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
996 mUserRestrictionsListeners.toArray(listeners);
997 }
998 for (int i = 0; i < listeners.length; i++) {
999 listeners[i].onUserRestrictionsChanged(userId,
1000 newRestrictionsFinal, prevRestrictionsFinal);
1001 }
1002 }
1003 });
1004 }
1005
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001006 // Package private for the inner class.
1007 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001008 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001009 }
1010
1011 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 // Package private for the inner class.
1013 void applyUserRestrictionsForAllUsersLR() {
1014 if (DBG) {
1015 debug("applyUserRestrictionsForAllUsersLR");
1016 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001017 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001018 mCachedEffectiveUserRestrictions.clear();
1019
Makoto Onuki068c54a2015-10-13 14:34:03 -07001020 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1021 // it on a handler.
1022 final Runnable r = new Runnable() {
1023 @Override
1024 public void run() {
1025 // Then get the list of running users.
1026 final int[] runningUsers;
1027 try {
1028 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1029 } catch (RemoteException e) {
1030 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1031 return;
1032 }
1033 // Then re-calculate the effective restrictions and apply, only for running users.
1034 // It's okay if a new user has started after the getRunningUserIds() call,
1035 // because we'll do the same thing (re-calculate the restrictions and apply)
1036 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001037 synchronized (mRestrictionsLock) {
1038 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001039 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001040 }
1041 }
1042 }
1043 };
1044 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001045 }
1046
Amith Yamasani258848d2012-08-10 17:06:33 -07001047 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001048 * Check if we've hit the limit of how many users can be created.
1049 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001050 private boolean isUserLimitReached() {
1051 int count;
1052 synchronized (mUsersLock) {
1053 count = getAliveUsersExcludingGuestsCountLU();
1054 }
1055 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001056 }
1057
1058 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001059 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001060 checkManageUsersPermission("check if more managed profiles can be added.");
1061 if (ActivityManager.isLowRamDeviceStatic()) {
1062 return false;
1063 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001064 if (!mContext.getPackageManager().hasSystemFeature(
1065 PackageManager.FEATURE_MANAGED_USERS)) {
1066 return false;
1067 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001068 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001069 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1070 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1071 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001072 return false;
1073 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001074 synchronized(mUsersLock) {
1075 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001076 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001077 return false;
1078 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001079 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1080 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001081 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001082 return usersCountAfterRemoving == 1
1083 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001084 }
1085 }
1086
Fyodor Kupolov82402752015-10-28 14:54:51 -07001087 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001088 int aliveUserCount = 0;
1089 final int totalUserCount = mUsers.size();
1090 // Skip over users being removed
1091 for (int i = 0; i < totalUserCount; i++) {
1092 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001093 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001094 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001095 aliveUserCount++;
1096 }
1097 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001098 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001099 }
1100
1101 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001102 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001103 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1104 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1105 * permissions can make certain calls to the UserManager.
1106 *
1107 * @param message used as message if SecurityException is thrown
1108 * @throws SecurityException if the caller does not have enough privilege.
1109 */
1110 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1111 final int uid = Binder.getCallingUid();
1112 if (uid != Process.SYSTEM_UID && uid != 0
1113 && ActivityManager.checkComponentPermission(
1114 Manifest.permission.MANAGE_USERS,
1115 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1116 && ActivityManager.checkComponentPermission(
1117 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1118 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1119 throw new SecurityException(
1120 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1121 + message);
1122 }
1123 }
1124
1125 /**
1126 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001127 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001128 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001129 *
1130 * @param message used as message if SecurityException is thrown
1131 * @throws SecurityException if the caller is not system or root
1132 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001133 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001134 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001135 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001136 && ActivityManager.checkComponentPermission(
1137 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001138 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1139 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1140 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001141 }
1142
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001143 /**
1144 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1145 * UserManager.
1146 *
1147 * @param message used as message if SecurityException is thrown
1148 * @throws SecurityException if the caller is not system or root
1149 */
1150 private static void checkSystemOrRoot(String message) {
1151 final int uid = Binder.getCallingUid();
1152 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1153 throw new SecurityException("Only system may: " + message);
1154 }
1155 }
1156
Fyodor Kupolov82402752015-10-28 14:54:51 -07001157 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001158 try {
1159 File dir = new File(mUsersDir, Integer.toString(info.id));
1160 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001161 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001162 if (!dir.exists()) {
1163 dir.mkdir();
1164 FileUtils.setPermissions(
1165 dir.getPath(),
1166 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1167 -1, -1);
1168 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001169 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001170 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1171 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001172 info.iconPath = file.getAbsolutePath();
1173 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001174 try {
1175 os.close();
1176 } catch (IOException ioe) {
1177 // What the ... !
1178 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001179 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001180 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001181 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001182 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001183 }
1184
Amith Yamasani0b285492011-04-14 17:35:23 -07001185 /**
1186 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1187 * cache it elsewhere.
1188 * @return the array of user ids.
1189 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001190 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001191 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001192 return mUserIds;
1193 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001194 }
1195
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001196 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001197 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001198 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001199 return;
1200 }
1201 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001202 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001203 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001204 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001205 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001206 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001207 int type;
1208 while ((type = parser.next()) != XmlPullParser.START_TAG
1209 && type != XmlPullParser.END_DOCUMENT) {
1210 ;
1211 }
1212
1213 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001214 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001215 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001216 return;
1217 }
1218
Amith Yamasani2a003292012-08-14 18:25:45 -07001219 mNextSerialNumber = -1;
1220 if (parser.getName().equals(TAG_USERS)) {
1221 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1222 if (lastSerialNumber != null) {
1223 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1224 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001225 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1226 if (versionNumber != null) {
1227 mUserVersion = Integer.parseInt(versionNumber);
1228 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001229 }
1230
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1232
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001233 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301234 if (type == XmlPullParser.START_TAG) {
1235 final String name = parser.getName();
1236 if (name.equals(TAG_USER)) {
1237 String id = parser.getAttributeValue(null, ATTR_ID);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001238 Pair<UserInfo, String> userPair = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001239
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001240 if (userPair != null) {
1241 UserInfo user = userPair.first;
1242 String account = userPair.second;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001243 synchronized (mUsersLock) {
1244 mUsers.put(user.id, user);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001245 mUserAccounts.put(user.id, account);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001246 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1247 mNextSerialNumber = user.id + 1;
1248 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301249 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301251 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001252 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1253 && type != XmlPullParser.END_TAG) {
1254 if (type == XmlPullParser.START_TAG) {
1255 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 synchronized (mGuestRestrictions) {
1257 UserRestrictionsUtils
1258 .readRestrictions(parser, mGuestRestrictions);
1259 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001260 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1261 ) {
1262 UserRestrictionsUtils.readRestrictions(parser,
1263 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001264 }
1265 break;
1266 }
1267 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001268 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001269 }
1270 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001271 synchronized (mRestrictionsLock) {
1272 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1273 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001274 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001275 upgradeIfNecessaryLP();
1276 } catch (IOException | XmlPullParserException e) {
1277 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001278 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001279 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001280 }
1281 }
1282
Amith Yamasani6f34b412012-10-22 18:19:27 -07001283 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001284 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001285 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001286 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001287 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001288 int userVersion = mUserVersion;
1289 if (userVersion < 1) {
1290 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001291 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001292 if ("Primary".equals(user.name)) {
1293 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001294 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001295 }
1296 userVersion = 1;
1297 }
1298
Amith Yamasanibc9625052012-11-15 14:39:18 -08001299 if (userVersion < 2) {
1300 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001301 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001302 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1303 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001304 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001305 }
1306 userVersion = 2;
1307 }
1308
Amith Yamasani350962c2013-08-06 11:18:53 -07001309
Amith Yamasani5e486f52013-08-07 11:06:44 -07001310 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001311 userVersion = 4;
1312 }
1313
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001314 if (userVersion < 5) {
1315 initDefaultGuestRestrictions();
1316 userVersion = 5;
1317 }
1318
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001319 if (userVersion < 6) {
1320 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001321 synchronized (mUsersLock) {
1322 for (int i = 0; i < mUsers.size(); i++) {
1323 UserInfo user = mUsers.valueAt(i);
1324 // In non-split mode, only user 0 can have restricted profiles
1325 if (!splitSystemUser && user.isRestricted()
1326 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1327 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001328 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001329 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001330 }
1331 }
1332 userVersion = 6;
1333 }
1334
Amith Yamasani6f34b412012-10-22 18:19:27 -07001335 if (userVersion < USER_VERSION) {
1336 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1337 + USER_VERSION);
1338 } else {
1339 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340
1341 if (originalVersion < mUserVersion) {
1342 writeUserListLP();
1343 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001344 }
1345 }
1346
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001347 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001348 int flags = UserInfo.FLAG_INITIALIZED;
1349 // In split system user mode, the admin and primary flags are assigned to the first human
1350 // user.
1351 if (!UserManager.isSplitSystemUser()) {
1352 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1353 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001354 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001355 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001356 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001357 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001358 synchronized (mUsersLock) {
1359 mUsers.put(system.id, system);
1360 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001361 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001362 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001363
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001364 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001365 synchronized (mRestrictionsLock) {
1366 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1367 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001368
Fyodor Kupolov82402752015-10-28 14:54:51 -07001369 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001370 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001371
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001372 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001373 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001374 }
1375
Makoto Onuki9e935a32015-11-06 14:24:24 -08001376 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001377 if (DBG) {
1378 debug("scheduleWriteUser");
1379 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001380 // No need to wrap it within a lock -- worst case, we'll just post the same message
1381 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001382 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1383 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1384 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1385 }
1386 }
1387
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001388 /*
1389 * Writes the user file in this format:
1390 *
1391 * <user flags="20039023" id="0">
1392 * <name>Primary</name>
1393 * </user>
1394 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001395 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001396 if (DBG) {
1397 debug("writeUserLP " + userInfo);
1398 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001399 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001400 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001401 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001402 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001403 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1404
1405 // XmlSerializer serializer = XmlUtils.serializerInstance();
1406 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001407 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001408 serializer.startDocument(null, true);
1409 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1410
1411 serializer.startTag(null, TAG_USER);
1412 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001413 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001414 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001415 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1416 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1417 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001418 if (userInfo.iconPath != null) {
1419 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1420 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001421 if (userInfo.partial) {
1422 serializer.attribute(null, ATTR_PARTIAL, "true");
1423 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001424 if (userInfo.guestToRemove) {
1425 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1426 }
Kenny Guy2a764942014-04-02 13:29:20 +01001427 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1428 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1429 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001430 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001431 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1432 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1433 Integer.toString(userInfo.restrictedProfileParentId));
1434 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001435 serializer.startTag(null, TAG_NAME);
1436 serializer.text(userInfo.name);
1437 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001438 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 UserRestrictionsUtils.writeRestrictions(serializer,
1440 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1441 UserRestrictionsUtils.writeRestrictions(serializer,
1442 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1443 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001444 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001445 // Update the account field if it is set.
1446 String account;
1447 synchronized (mUsersLock) {
1448 account = mUserAccounts.get(userInfo.id);
1449 }
1450 if (account != null) {
1451 serializer.startTag(null, TAG_ACCOUNT);
1452 serializer.text(account);
1453 serializer.endTag(null, TAG_ACCOUNT);
1454 }
1455
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456 serializer.endTag(null, TAG_USER);
1457
1458 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001459 userFile.finishWrite(fos);
1460 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001461 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001462 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001463 }
1464 }
1465
1466 /*
1467 * Writes the user list file in this format:
1468 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001469 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001470 * <user id="0"></user>
1471 * <user id="2"></user>
1472 * </users>
1473 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001474 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001475 if (DBG) {
1476 debug("writeUserList");
1477 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001478 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001479 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001480 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001481 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001482 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1483
1484 // XmlSerializer serializer = XmlUtils.serializerInstance();
1485 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001486 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001487 serializer.startDocument(null, true);
1488 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1489
1490 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001491 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001492 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001493
Adam Lesinskieddeb492014-09-08 17:50:03 -07001494 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001495 synchronized (mGuestRestrictions) {
1496 UserRestrictionsUtils
1497 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1498 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301499 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 synchronized (mRestrictionsLock) {
1501 UserRestrictionsUtils.writeRestrictions(serializer,
1502 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1503 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001504 int[] userIdsToWrite;
1505 synchronized (mUsersLock) {
1506 userIdsToWrite = new int[mUsers.size()];
1507 for (int i = 0; i < userIdsToWrite.length; i++) {
1508 UserInfo user = mUsers.valueAt(i);
1509 userIdsToWrite[i] = user.id;
1510 }
1511 }
1512 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001514 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001515 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001516 }
1517
1518 serializer.endTag(null, TAG_USERS);
1519
1520 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001521 userListFile.finishWrite(fos);
1522 } catch (Exception e) {
1523 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001524 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001525 }
1526 }
1527
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001528 private Pair<UserInfo, String> readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001529 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001530 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001531 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001532 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001533 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001534 long creationTime = 0L;
1535 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001536 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001537 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001538 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001539 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540 Bundle baseRestrictions = new Bundle();
1541 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001542
1543 FileInputStream fis = null;
1544 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001545 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001546 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001547 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001548 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001549 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001550 int type;
1551 while ((type = parser.next()) != XmlPullParser.START_TAG
1552 && type != XmlPullParser.END_DOCUMENT) {
1553 ;
1554 }
1555
1556 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001557 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001558 return null;
1559 }
1560
1561 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001562 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1563 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001564 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001565 return null;
1566 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001567 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1568 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001569 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001570 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1571 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001572 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1573 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001574 restrictedProfileParentId = readIntAttribute(parser,
1575 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001576 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1577 if ("true".equals(valueString)) {
1578 partial = true;
1579 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001580 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1581 if ("true".equals(valueString)) {
1582 guestToRemove = true;
1583 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001584
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001585 int outerDepth = parser.getDepth();
1586 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1587 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1588 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1589 continue;
1590 }
1591 String tag = parser.getName();
1592 if (TAG_NAME.equals(tag)) {
1593 type = parser.next();
1594 if (type == XmlPullParser.TEXT) {
1595 name = parser.getText();
1596 }
1597 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1599 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1600 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001601 } else if (TAG_ACCOUNT.equals(tag)) {
1602 type = parser.next();
1603 if (type == XmlPullParser.TEXT) {
1604 account = parser.getText();
1605 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606 }
1607 }
1608 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001609
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001610 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001612 userInfo.creationTime = creationTime;
1613 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001614 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001615 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001616 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001617 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001618 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619 mBaseUserRestrictions.put(id, baseRestrictions);
1620 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001621 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001622 return new Pair<>(userInfo, account);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623
1624 } catch (IOException ioe) {
1625 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001626 } finally {
1627 if (fis != null) {
1628 try {
1629 fis.close();
1630 } catch (IOException e) {
1631 }
1632 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001633 }
1634 return null;
1635 }
1636
Amith Yamasani920ace02012-09-20 22:15:37 -07001637 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1638 String valueString = parser.getAttributeValue(null, attr);
1639 if (valueString == null) return defaultValue;
1640 try {
1641 return Integer.parseInt(valueString);
1642 } catch (NumberFormatException nfe) {
1643 return defaultValue;
1644 }
1645 }
1646
1647 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1648 String valueString = parser.getAttributeValue(null, attr);
1649 if (valueString == null) return defaultValue;
1650 try {
1651 return Long.parseLong(valueString);
1652 } catch (NumberFormatException nfe) {
1653 return defaultValue;
1654 }
1655 }
1656
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001657 private boolean isPackageInstalled(String pkg, int userId) {
1658 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1659 PackageManager.GET_UNINSTALLED_PACKAGES,
1660 userId);
1661 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1662 return false;
1663 }
1664 return true;
1665 }
1666
Amith Yamasanib82add22013-07-09 11:24:44 -07001667 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001668 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001669 * Does not do any permissions checking.
1670 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001671 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001672 synchronized (mPackagesLock) {
1673 File dir = Environment.getUserSystemDirectory(userId);
1674 String[] files = dir.list();
1675 if (files == null) return;
1676 for (String fileName : files) {
1677 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1678 File resFile = new File(dir, fileName);
1679 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001680 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001681 }
1682 }
1683 }
1684 }
1685 }
1686
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001687 /**
1688 * Removes the app restrictions file for a specific package and user id, if it exists.
1689 */
1690 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1691 synchronized (mPackagesLock) {
1692 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001693 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001694 if (resFile.exists()) {
1695 resFile.delete();
1696 }
1697 }
1698 }
1699
Kenny Guya52dc3e2014-02-11 15:33:14 +00001700 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001701 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001702 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001703 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001704 }
1705
Amith Yamasani258848d2012-08-10 17:06:33 -07001706 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001707 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001708 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001709 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001710 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001711
Jessica Hummelbe81c802014-04-22 15:49:22 +01001712 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001713 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001714 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1715 return null;
1716 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001717 if (ActivityManager.isLowRamDeviceStatic()) {
1718 return null;
1719 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001720 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001721 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001722 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001723 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001724 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001725 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001726 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001727 synchronized (mPackagesLock) {
1728 UserInfo parent = null;
1729 if (parentId != UserHandle.USER_NULL) {
1730 synchronized (mUsersLock) {
1731 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001732 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001733 if (parent == null) return null;
1734 }
1735 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1736 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1737 return null;
1738 }
1739 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1740 // If we're not adding a guest user or a managed profile and the limit has
1741 // been reached, cannot add a user.
1742 return null;
1743 }
1744 // If we're adding a guest and there already exists one, bail.
1745 if (isGuest && findCurrentGuestUser() != null) {
1746 return null;
1747 }
1748 // In legacy mode, restricted profile's parent can only be the owner user
1749 if (isRestricted && !UserManager.isSplitSystemUser()
1750 && (parentId != UserHandle.USER_SYSTEM)) {
1751 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1752 return null;
1753 }
1754 if (isRestricted && UserManager.isSplitSystemUser()) {
1755 if (parent == null) {
1756 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1757 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001758 return null;
1759 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001760 if (!parent.canHaveProfile()) {
1761 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1762 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001763 return null;
1764 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001765 }
1766 // In split system user mode, we assign the first human user the primary flag.
1767 // And if there is no device owner, we also assign the admin flag to primary user.
1768 if (UserManager.isSplitSystemUser()
1769 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1770 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001771 synchronized (mUsersLock) {
1772 if (!mIsDeviceManaged) {
1773 flags |= UserInfo.FLAG_ADMIN;
1774 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001775 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001776 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001777
1778 if (parent != null && parent.isEphemeral()) {
1779 flags |= UserInfo.FLAG_EPHEMERAL;
1780 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001781 userId = getNextAvailableId();
1782 userInfo = new UserInfo(userId, name, null, flags);
1783 userInfo.serialNumber = mNextSerialNumber++;
1784 long now = System.currentTimeMillis();
1785 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1786 userInfo.partial = true;
1787 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1788 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001789 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001790 }
1791 writeUserListLP();
1792 if (parent != null) {
1793 if (isManagedProfile) {
1794 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1795 parent.profileGroupId = parent.id;
1796 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001797 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001798 userInfo.profileGroupId = parent.profileGroupId;
1799 } else if (isRestricted) {
1800 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1801 parent.restrictedProfileParentId = parent.id;
1802 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001803 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001804 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001805 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001806 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001807 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001808 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001809 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001810 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1811 final String volumeUuid = vol.getFsUuid();
1812 try {
1813 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001814 storage.prepareUserStorage(
1815 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001816 enforceSerialNumber(userDir, userInfo.serialNumber);
1817 } catch (IOException e) {
1818 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1819 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001820 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001821 mPm.createNewUser(userId);
1822 userInfo.partial = false;
1823 synchronized (mPackagesLock) {
1824 writeUserLP(userInfo);
1825 }
1826 updateUserIds();
1827 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001828 if (isGuest) {
1829 synchronized (mGuestRestrictions) {
1830 restrictions.putAll(mGuestRestrictions);
1831 }
1832 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001833 synchronized (mRestrictionsLock) {
1834 mBaseUserRestrictions.append(userId, restrictions);
1835 }
1836 mPm.newUserCreated(userId);
1837 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1838 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1839 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1840 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001841 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001842 } finally {
1843 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001844 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001845 return userInfo;
1846 }
1847
Amith Yamasani0b285492011-04-14 17:35:23 -07001848 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001849 * @hide
1850 */
1851 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1852 checkManageUsersPermission("setupRestrictedProfile");
1853 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1854 if (user == null) {
1855 return null;
1856 }
1857 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1858 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1859 // the putIntForUser() will fail.
1860 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1861 android.provider.Settings.Secure.LOCATION_MODE,
1862 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1863 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1864 return user;
1865 }
1866
1867 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001868 * Find the current guest user. If the Guest user is partial,
1869 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001870 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001871 private UserInfo findCurrentGuestUser() {
1872 synchronized (mUsersLock) {
1873 final int size = mUsers.size();
1874 for (int i = 0; i < size; i++) {
1875 final UserInfo user = mUsers.valueAt(i);
1876 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1877 return user;
1878 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001879 }
1880 }
1881 return null;
1882 }
1883
1884 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001885 * Mark this guest user for deletion to allow us to create another guest
1886 * and switch to that user before actually removing this guest.
1887 * @param userHandle the userid of the current guest
1888 * @return whether the user could be marked for deletion
1889 */
1890 public boolean markGuestForDeletion(int userHandle) {
1891 checkManageUsersPermission("Only the system can remove users");
1892 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1893 UserManager.DISALLOW_REMOVE_USER, false)) {
1894 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1895 return false;
1896 }
1897
1898 long ident = Binder.clearCallingIdentity();
1899 try {
1900 final UserInfo user;
1901 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001902 synchronized (mUsersLock) {
1903 user = mUsers.get(userHandle);
1904 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1905 return false;
1906 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001907 }
1908 if (!user.isGuest()) {
1909 return false;
1910 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001911 // We set this to a guest user that is to be removed. This is a temporary state
1912 // where we are allowed to add new Guest users, even if this one is still not
1913 // removed. This user will still show up in getUserInfo() calls.
1914 // If we don't get around to removing this Guest user, it will be purged on next
1915 // startup.
1916 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001917 // Mark it as disabled, so that it isn't returned any more when
1918 // profiles are queried.
1919 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001920 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001921 }
1922 } finally {
1923 Binder.restoreCallingIdentity(ident);
1924 }
1925 return true;
1926 }
1927
1928 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001929 * Removes a user and all data directories created for that user. This method should be called
1930 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001931 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001932 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001933 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001934 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001935 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1936 UserManager.DISALLOW_REMOVE_USER, false)) {
1937 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1938 return false;
1939 }
1940
Kenny Guyee58b4f2014-05-23 15:19:53 +01001941 long ident = Binder.clearCallingIdentity();
1942 try {
1943 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001944 int currentUser = ActivityManager.getCurrentUser();
1945 if (currentUser == userHandle) {
1946 Log.w(LOG_TAG, "Current user cannot be removed");
1947 return false;
1948 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001949 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 synchronized (mUsersLock) {
1951 user = mUsers.get(userHandle);
1952 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1953 return false;
1954 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001955
Fyodor Kupolov82402752015-10-28 14:54:51 -07001956 // We remember deleted user IDs to prevent them from being
1957 // reused during the current boot; they can still be reused
1958 // after a reboot.
1959 mRemovingUserIds.put(userHandle, true);
1960 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001961
Kenny Guyee58b4f2014-05-23 15:19:53 +01001962 try {
1963 mAppOpsService.removeUser(userHandle);
1964 } catch (RemoteException e) {
1965 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1966 }
1967 // Set this to a partially created user, so that the user will be purged
1968 // on next startup, in case the runtime stops now before stopping and
1969 // removing the user completely.
1970 user.partial = true;
1971 // Mark it as disabled, so that it isn't returned any more when
1972 // profiles are queried.
1973 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001974 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001975 }
1976
1977 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1978 && user.isManagedProfile()) {
1979 // Send broadcast to notify system that the user removed was a
1980 // managed user.
1981 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1982 }
1983
1984 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1985 int res;
1986 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001987 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1988 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001989 @Override
1990 public void userStopped(int userId) {
1991 finishRemoveUser(userId);
1992 }
1993 @Override
1994 public void userStopAborted(int userId) {
1995 }
1996 });
1997 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001998 return false;
1999 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002000 return res == ActivityManager.USER_OP_SUCCESS;
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002003 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002004 }
2005
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002006 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002007 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002008 // Let other services shutdown any activity and clean up their state before completely
2009 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002010 long ident = Binder.clearCallingIdentity();
2011 try {
2012 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2013 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002014 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2015 android.Manifest.permission.MANAGE_USERS,
2016
2017 new BroadcastReceiver() {
2018 @Override
2019 public void onReceive(Context context, Intent intent) {
2020 if (DBG) {
2021 Slog.i(LOG_TAG,
2022 "USER_REMOVED broadcast sent, cleaning up user data "
2023 + userHandle);
2024 }
2025 new Thread() {
2026 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002027 // Clean up any ActivityManager state
2028 LocalServices.getService(ActivityManagerInternal.class)
2029 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002030 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002031 }
2032 }.start();
2033 }
2034 },
2035
2036 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002040 }
2041
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002042 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002043 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002044 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002045 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002046
2047 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002048 synchronized (mUsersLock) {
2049 mUsers.remove(userHandle);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002050 mUserAccounts.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002051 mIsUserManaged.delete(userHandle);
2052 }
2053 synchronized (mRestrictionsLock) {
2054 mBaseUserRestrictions.remove(userHandle);
2055 mAppliedUserRestrictions.remove(userHandle);
2056 mCachedEffectiveUserRestrictions.remove(userHandle);
2057 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002058 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002059 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002060 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002061 userFile.delete();
2062 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002063 synchronized (mPackagesLock) {
2064 writeUserListLP();
2065 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002067 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
2068 }
2069
Amith Yamasani61f57372012-08-31 12:12:28 -07002070 private void removeDirectoryRecursive(File parent) {
2071 if (parent.isDirectory()) {
2072 String[] files = parent.list();
2073 for (String filename : files) {
2074 File child = new File(parent, filename);
2075 removeDirectoryRecursive(child);
2076 }
2077 }
2078 parent.delete();
2079 }
2080
Kenny Guyf8d3a232014-05-15 16:09:52 +01002081 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002082 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002083 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2084 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002085 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002086 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002087 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002088 }
2089
Amith Yamasani2a003292012-08-14 18:25:45 -07002090 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002091 public Bundle getApplicationRestrictions(String packageName) {
2092 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2093 }
2094
2095 @Override
2096 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002097 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002098 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002099 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002100 }
2101 synchronized (mPackagesLock) {
2102 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002103 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002104 }
2105 }
2106
2107 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002108 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002109 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002110 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002111 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002112 if (restrictions == null || restrictions.isEmpty()) {
2113 cleanAppRestrictionsForPackage(packageName, userId);
2114 } else {
2115 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002116 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002117 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002118 }
Robin Lee66e5d962014-04-09 16:44:21 +01002119
Kenny Guyd21b2182014-07-17 16:38:55 +01002120 if (isPackageInstalled(packageName, userId)) {
2121 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2122 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2123 changeIntent.setPackage(packageName);
2124 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2125 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2126 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002127 }
2128
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002129 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002130 mHandler.post(new Runnable() {
2131 @Override
2132 public void run() {
2133 List<ApplicationInfo> apps =
2134 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2135 userHandle).getList();
2136 final long ident = Binder.clearCallingIdentity();
2137 try {
2138 for (ApplicationInfo appInfo : apps) {
2139 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002140 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2141 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002142 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002143 userHandle);
2144 }
2145 }
2146 } finally {
2147 Binder.restoreCallingIdentity(ident);
2148 }
2149 }
2150 });
2151 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002152 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002153 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002154 try {
2155 return mContext.getPackageManager().getApplicationInfo(packageName,
2156 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2157 } catch (NameNotFoundException nnfe) {
2158 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002159 } finally {
2160 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002161 }
2162 }
2163
Fyodor Kupolov82402752015-10-28 14:54:51 -07002164 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002165 AtomicFile restrictionsFile =
2166 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2167 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002168 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002169 }
2170
2171 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002172 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002173 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002174 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002175 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002176 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002177 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002178
2179 FileInputStream fis = null;
2180 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002181 fis = restrictionsFile.openRead();
2182 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002183 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002184 XmlUtils.nextElement(parser);
2185 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002186 Slog.e(LOG_TAG, "Unable to read restrictions file "
2187 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002188 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002189 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002190 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2191 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002192 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002193 } catch (IOException|XmlPullParserException e) {
2194 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002195 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002196 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002197 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002198 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002199 }
2200
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002201 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2202 XmlPullParser parser) throws XmlPullParserException, IOException {
2203 int type = parser.getEventType();
2204 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2205 String key = parser.getAttributeValue(null, ATTR_KEY);
2206 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2207 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2208 if (multiple != null) {
2209 values.clear();
2210 int count = Integer.parseInt(multiple);
2211 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2212 if (type == XmlPullParser.START_TAG
2213 && parser.getName().equals(TAG_VALUE)) {
2214 values.add(parser.nextText().trim());
2215 count--;
2216 }
2217 }
2218 String [] valueStrings = new String[values.size()];
2219 values.toArray(valueStrings);
2220 restrictions.putStringArray(key, valueStrings);
2221 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2222 restrictions.putBundle(key, readBundleEntry(parser, values));
2223 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2224 final int outerDepth = parser.getDepth();
2225 ArrayList<Bundle> bundleList = new ArrayList<>();
2226 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2227 Bundle childBundle = readBundleEntry(parser, values);
2228 bundleList.add(childBundle);
2229 }
2230 restrictions.putParcelableArray(key,
2231 bundleList.toArray(new Bundle[bundleList.size()]));
2232 } else {
2233 String value = parser.nextText().trim();
2234 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2235 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2236 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2237 restrictions.putInt(key, Integer.parseInt(value));
2238 } else {
2239 restrictions.putString(key, value);
2240 }
2241 }
2242 }
2243 }
2244
2245 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2246 throws IOException, XmlPullParserException {
2247 Bundle childBundle = new Bundle();
2248 final int outerDepth = parser.getDepth();
2249 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2250 readEntry(childBundle, values, parser);
2251 }
2252 return childBundle;
2253 }
2254
Fyodor Kupolov82402752015-10-28 14:54:51 -07002255 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002256 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002257 AtomicFile restrictionsFile = new AtomicFile(
2258 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002259 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002260 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002261 }
2262
2263 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002264 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002265 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002266 try {
2267 fos = restrictionsFile.startWrite();
2268 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2269
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002270 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002271 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002272 serializer.startDocument(null, true);
2273 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2274
2275 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002276 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002277 serializer.endTag(null, TAG_RESTRICTIONS);
2278
2279 serializer.endDocument();
2280 restrictionsFile.finishWrite(fos);
2281 } catch (Exception e) {
2282 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002283 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2284 }
2285 }
2286
2287 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2288 throws IOException {
2289 for (String key : restrictions.keySet()) {
2290 Object value = restrictions.get(key);
2291 serializer.startTag(null, TAG_ENTRY);
2292 serializer.attribute(null, ATTR_KEY, key);
2293
2294 if (value instanceof Boolean) {
2295 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2296 serializer.text(value.toString());
2297 } else if (value instanceof Integer) {
2298 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2299 serializer.text(value.toString());
2300 } else if (value == null || value instanceof String) {
2301 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2302 serializer.text(value != null ? (String) value : "");
2303 } else if (value instanceof Bundle) {
2304 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2305 writeBundle((Bundle) value, serializer);
2306 } else if (value instanceof Parcelable[]) {
2307 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2308 Parcelable[] array = (Parcelable[]) value;
2309 for (Parcelable parcelable : array) {
2310 if (!(parcelable instanceof Bundle)) {
2311 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2312 }
2313 serializer.startTag(null, TAG_ENTRY);
2314 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2315 writeBundle((Bundle) parcelable, serializer);
2316 serializer.endTag(null, TAG_ENTRY);
2317 }
2318 } else {
2319 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2320 String[] values = (String[]) value;
2321 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2322 for (String choice : values) {
2323 serializer.startTag(null, TAG_VALUE);
2324 serializer.text(choice != null ? choice : "");
2325 serializer.endTag(null, TAG_VALUE);
2326 }
2327 }
2328 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 }
2330 }
2331
2332 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002333 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002334 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002335 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002336 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002337 }
2338 }
2339
2340 @Override
2341 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002342 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002343 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002344 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002345 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002346 }
2347 // Not found
2348 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002349 }
2350 }
2351
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002352 @Override
2353 public long getUserCreationTime(int userHandle) {
2354 int callingUserId = UserHandle.getCallingUserId();
2355 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002356 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002357 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002358 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002359 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002360 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002361 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002362 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002363 }
2364 }
2365 }
2366 if (userInfo == null) {
2367 throw new SecurityException("userHandle can only be the calling user or a managed "
2368 + "profile associated with this user");
2369 }
2370 return userInfo.creationTime;
2371 }
2372
Amith Yamasani0b285492011-04-14 17:35:23 -07002373 /**
2374 * Caches the list of user ids in an array, adjusting the array size when necessary.
2375 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002376 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002377 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002378 synchronized (mUsersLock) {
2379 final int userSize = mUsers.size();
2380 for (int i = 0; i < userSize; i++) {
2381 if (!mUsers.valueAt(i).partial) {
2382 num++;
2383 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002384 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002385 final int[] newUsers = new int[num];
2386 int n = 0;
2387 for (int i = 0; i < userSize; i++) {
2388 if (!mUsers.valueAt(i).partial) {
2389 newUsers[n++] = mUsers.keyAt(i);
2390 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002391 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002392 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002393 }
2394 }
2395
2396 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002397 * Called right before a user starts. This will not be called for the system user.
2398 */
2399 public void onBeforeStartUser(int userId) {
2400 synchronized (mRestrictionsLock) {
2401 applyUserRestrictionsLR(userId);
2402 }
2403 }
2404
2405 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002406 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002407 * @param userId the user that was just foregrounded
2408 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002409 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002410 UserInfo user = getUserInfoNoChecks(userId);
2411 if (user == null || user.partial) {
2412 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2413 return;
2414 }
2415 long now = System.currentTimeMillis();
2416 if (now > EPOCH_PLUS_30_YEARS) {
2417 user.lastLoggedInTime = now;
2418 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002419 }
2420 }
2421
2422 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002423 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002424 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2425 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002426 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002427 private int getNextAvailableId() {
2428 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002429 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002430 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002431 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002432 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002433 }
2434 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002435 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002436 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002437 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002438 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002439
Amith Yamasanifc95e702013-09-26 13:20:17 -07002440 private String packageToRestrictionsFileName(String packageName) {
2441 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2442 }
2443
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002444 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002445 * Enforce that serial number stored in user directory inode matches the
2446 * given expected value. Gracefully sets the serial number if currently
2447 * undefined.
2448 *
2449 * @throws IOException when problem extracting serial number, or serial
2450 * number is mismatched.
2451 */
2452 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2453 final int foundSerial = getSerialNumber(file);
2454 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2455
2456 if (foundSerial == -1) {
2457 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2458 try {
2459 setSerialNumber(file, serialNumber);
2460 } catch (IOException e) {
2461 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2462 }
2463
2464 } else if (foundSerial != serialNumber) {
2465 throw new IOException("Found serial number " + foundSerial
2466 + " doesn't match expected " + serialNumber);
2467 }
2468 }
2469
2470 /**
2471 * Set serial number stored in user directory inode.
2472 *
2473 * @throws IOException if serial number was already set
2474 */
2475 private static void setSerialNumber(File file, int serialNumber)
2476 throws IOException {
2477 try {
2478 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2479 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2480 } catch (ErrnoException e) {
2481 throw e.rethrowAsIOException();
2482 }
2483 }
2484
2485 /**
2486 * Return serial number stored in user directory inode.
2487 *
2488 * @return parsed serial number, or -1 if not set
2489 */
2490 private static int getSerialNumber(File file) throws IOException {
2491 try {
2492 final byte[] buf = new byte[256];
2493 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2494 final String serial = new String(buf, 0, len);
2495 try {
2496 return Integer.parseInt(serial);
2497 } catch (NumberFormatException e) {
2498 throw new IOException("Bad serial number: " + serial);
2499 }
2500 } catch (ErrnoException e) {
2501 if (e.errno == OsConstants.ENODATA) {
2502 return -1;
2503 } else {
2504 throw e.rethrowAsIOException();
2505 }
2506 }
2507 }
2508
Amith Yamasani920ace02012-09-20 22:15:37 -07002509 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002510 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2511 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2512 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2513 }
2514
2515 int onShellCommand(Shell shell, String cmd) {
2516 if (cmd == null) {
2517 return shell.handleDefaultCommands(cmd);
2518 }
2519
2520 final PrintWriter pw = shell.getOutPrintWriter();
2521 try {
2522 switch(cmd) {
2523 case "list":
2524 return runList(pw);
2525 }
2526 } catch (RemoteException e) {
2527 pw.println("Remote exception: " + e);
2528 }
2529 return -1;
2530 }
2531
2532 private int runList(PrintWriter pw) throws RemoteException {
2533 final IActivityManager am = ActivityManagerNative.getDefault();
2534 final List<UserInfo> users = getUsers(false);
2535 if (users == null) {
2536 pw.println("Error: couldn't get users");
2537 return 1;
2538 } else {
2539 pw.println("Users:");
2540 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002541 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002542 pw.println("\t" + users.get(i).toString() + running);
2543 }
2544 return 0;
2545 }
2546 }
2547
2548 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002549 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2550 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2551 != PackageManager.PERMISSION_GRANTED) {
2552 pw.println("Permission Denial: can't dump UserManager from from pid="
2553 + Binder.getCallingPid()
2554 + ", uid=" + Binder.getCallingUid()
2555 + " without permission "
2556 + android.Manifest.permission.DUMP);
2557 return;
2558 }
2559
2560 long now = System.currentTimeMillis();
2561 StringBuilder sb = new StringBuilder();
2562 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002563 synchronized (mUsersLock) {
2564 pw.println("Users:");
2565 for (int i = 0; i < mUsers.size(); i++) {
2566 UserInfo user = mUsers.valueAt(i);
2567 if (user == null) {
2568 continue;
2569 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002570 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002571 pw.print(" "); pw.print(user);
2572 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002573 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002574 pw.print(" <removing> ");
2575 }
2576 if (user.partial) {
2577 pw.print(" <partial>");
2578 }
2579 pw.println();
2580 pw.print(" Created: ");
2581 if (user.creationTime == 0) {
2582 pw.println("<unknown>");
2583 } else {
2584 sb.setLength(0);
2585 TimeUtils.formatDuration(now - user.creationTime, sb);
2586 sb.append(" ago");
2587 pw.println(sb);
2588 }
2589 pw.print(" Last logged in: ");
2590 if (user.lastLoggedInTime == 0) {
2591 pw.println("<unknown>");
2592 } else {
2593 sb.setLength(0);
2594 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2595 sb.append(" ago");
2596 pw.println(sb);
2597 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002598 pw.print(" Has profile owner: ");
2599 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002600 pw.println(" Restrictions:");
2601 synchronized (mRestrictionsLock) {
2602 UserRestrictionsUtils.dumpRestrictions(
2603 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002604 pw.println(" Device policy local restrictions:");
2605 UserRestrictionsUtils.dumpRestrictions(
2606 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 pw.println(" Effective restrictions:");
2608 UserRestrictionsUtils.dumpRestrictions(
2609 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2610 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002611 pw.println();
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002612 String accountName = mUserAccounts.get(userId);
2613 if (accountName != null) {
2614 pw.print(" Account name: " + accountName);
2615 pw.println();
2616 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002617 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002618 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002619 pw.println(" Device policy global restrictions:");
2620 synchronized (mRestrictionsLock) {
2621 UserRestrictionsUtils
2622 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2623 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002624 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002625 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002626 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002627 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002628 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002629 synchronized (mUsersLock) {
2630 pw.println();
2631 pw.println(" Device managed: " + mIsDeviceManaged);
2632 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002633 }
2634 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002635
2636 final class MainHandler extends Handler {
2637
2638 @Override
2639 public void handleMessage(Message msg) {
2640 switch (msg.what) {
2641 case WRITE_USER_MSG:
2642 removeMessages(WRITE_USER_MSG, msg.obj);
2643 synchronized (mPackagesLock) {
2644 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002645 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002646 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002647 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002648 }
2649 }
2650 }
2651 }
2652 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002653
2654 /**
2655 * @param userId
2656 * @return whether the user has been initialized yet
2657 */
2658 boolean isInitialized(int userId) {
2659 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2660 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002661
2662 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002663 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002664 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2665 @Nullable Bundle globalRestrictions) {
2666 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2667 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002668 }
2669
2670 @Override
2671 public Bundle getBaseUserRestrictions(int userId) {
2672 synchronized (mRestrictionsLock) {
2673 return mBaseUserRestrictions.get(userId);
2674 }
2675 }
2676
2677 @Override
2678 public void setBaseUserRestrictionsByDpmsForMigration(
2679 int userId, Bundle baseRestrictions) {
2680 synchronized (mRestrictionsLock) {
2681 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002683 }
2684
Fyodor Kupolov82402752015-10-28 14:54:51 -07002685 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002686 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002687 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002688 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002689 } else {
2690 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2691 }
2692 }
2693 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002694
2695 @Override
2696 public boolean getUserRestriction(int userId, String key) {
2697 return getUserRestrictions(userId).getBoolean(key);
2698 }
2699
2700 @Override
2701 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2702 synchronized (mUserRestrictionsListeners) {
2703 mUserRestrictionsListeners.add(listener);
2704 }
2705 }
2706
2707 @Override
2708 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2709 synchronized (mUserRestrictionsListeners) {
2710 mUserRestrictionsListeners.remove(listener);
2711 }
2712 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002713
2714 @Override
2715 public void setDeviceManaged(boolean isManaged) {
2716 synchronized (mUsersLock) {
2717 mIsDeviceManaged = isManaged;
2718 }
2719 }
2720
2721 @Override
2722 public void setUserManaged(int userId, boolean isManaged) {
2723 synchronized (mUsersLock) {
2724 mIsUserManaged.put(userId, isManaged);
2725 }
2726 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002727 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002728
2729 private class Shell extends ShellCommand {
2730 @Override
2731 public int onCommand(String cmd) {
2732 return onShellCommand(this, cmd);
2733 }
2734
2735 @Override
2736 public void onHelp() {
2737 final PrintWriter pw = getOutPrintWriter();
2738 pw.println("User manager (user) commands:");
2739 pw.println(" help");
2740 pw.println(" Print this help text.");
2741 pw.println("");
2742 pw.println(" list");
2743 pw.println(" Prints all users on the system.");
2744 }
2745 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002746
2747 private static void debug(String message) {
2748 Log.d(LOG_TAG, message +
2749 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2750 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002751}