blob: 715f1e5e43459f7e410eb5334d9734fef0388b29 [file] [log] [blame]
Tony Mak8673b282016-03-21 21:10:59 +00001
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002/*
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.server.pm;
19
Xiaohui Chenb3b92582015-12-07 11:22:13 -080020import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070021import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070022import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070024import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070025import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070027import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070028import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010032import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070033import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070034import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080035import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010037import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070038import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080040import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080041import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.os.Environment;
43import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080044import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080045import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080047import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010048import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070049import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080050import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070051import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070053import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010054import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040055import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070056import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070057import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070058import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070059import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080060import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010061import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070062import android.os.storage.VolumeInfo;
63import android.system.ErrnoException;
64import android.system.Os;
65import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070066import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070067import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import android.util.Slog;
69import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080070import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070071import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import android.util.Xml;
73
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070075import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040076import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080077import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080078import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070079import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070080import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000081import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070082import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070083
84import libcore.io.IoUtils;
85import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080086
87import org.xmlpull.v1.XmlPullParser;
88import org.xmlpull.v1.XmlPullParserException;
89import org.xmlpull.v1.XmlSerializer;
90
Amith Yamasani4b2e9342011-03-31 12:38:53 -070091import java.io.BufferedOutputStream;
92import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070093import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070095import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096import java.io.FileOutputStream;
97import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070098import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010099import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100import java.util.ArrayList;
101import java.util.List;
102
Makoto Onuki068c54a2015-10-13 14:34:03 -0700103/**
104 * Service for {@link UserManager}.
105 *
106 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700107 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800108 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700109 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
110 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
111 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700112 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700113public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700114 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800115 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800116 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700117
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800119 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700121 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final String ATTR_CREATION_TIME = "created";
124 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700125 private static final String ATTR_SERIAL_NO = "serialNumber";
126 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700127 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700128 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700129 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100130 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700131 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800132 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
133 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530134 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800137 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800138 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800139 private static final String TAG_ENTRY = "entry";
140 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800141 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800142 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700143 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700146 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
147 private static final String ATTR_TYPE_STRING = "s";
148 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700149 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700150 private static final String ATTR_TYPE_BUNDLE = "B";
151 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700152
Amith Yamasani0b285492011-04-14 17:35:23 -0700153 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700155 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100156 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800158 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700159 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160
Amith Yamasani634cf312012-10-04 17:34:21 -0700161 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700162 // We need to keep process uid within Integer.MAX_VALUE.
163 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700164
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700165 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700166
Amith Yamasani920ace02012-09-20 22:15:37 -0700167 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
168
Nicolas Prevotb8186812015-08-06 15:00:03 +0100169 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700170 // without first making sure that the rest of the framework is prepared for it.
171 private static final int MAX_MANAGED_PROFILES = 1;
172
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800173 static final int WRITE_USER_MSG = 1;
174 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530175
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700176 private static final String XATTR_SERIAL = "user.serial";
177
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800178 // Tron counters
179 private static final String TRON_GUEST_CREATED = "users_guest_created";
180 private static final String TRON_USER_CREATED = "users_user_created";
181
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 private final Context mContext;
183 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700185 // Short-term lock for internal state, when interaction/sync with PM is not required
186 private final Object mUsersLock = new Object();
187 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800189 private final Handler mHandler;
190
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191 private final File mUsersDir;
192 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800194 private static final IBinder mUserRestriconToken = new Binder();
195
Makoto Onuki068c54a2015-10-13 14:34:03 -0700196 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800197 * User-related information that is used for persisting to flash. Only UserInfo is
198 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800199 */
Amith Yamasani12747872015-12-07 14:19:49 -0800200 private static class UserData {
201 // Basic user information and properties
202 UserInfo info;
203 // Account name used when there is a strong association between a user and an account
204 String account;
205 // Account information for seeding into a newly created user. This could also be
206 // used for login validation for an existing user, for updating their credentials.
207 // In the latter case, data may not need to be persisted as it is only valid for the
208 // current login session.
209 String seedAccountName;
210 String seedAccountType;
211 PersistableBundle seedAccountOptions;
212 // Whether to perist the seed account information to be available after a boot
213 boolean persistSeedData;
214
215 void clearSeedAccountData() {
216 seedAccountName = null;
217 seedAccountType = null;
218 seedAccountOptions = null;
219 persistSeedData = false;
220 }
221 }
222
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800223 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800224 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800225
226 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700227 * User restrictions set via UserManager. This doesn't include restrictions set by
228 * device owner / profile owners.
229 *
230 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
231 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
232 * maybe shared between {@link #mBaseUserRestrictions} and
233 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
234 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700236 */
237 @GuardedBy("mRestrictionsLock")
238 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
239
240 /**
241 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
242 * with device / profile owner restrictions. We'll initialize it lazily; use
243 * {@link #getEffectiveUserRestrictions} to access it.
244 *
245 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
246 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
247 * maybe shared between {@link #mBaseUserRestrictions} and
248 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
249 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700250 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700251 */
252 @GuardedBy("mRestrictionsLock")
253 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
254
Makoto Onuki4f160732015-10-27 17:15:38 -0700255 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800256 * User restrictions that have already been applied in
257 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
258 * that have changed since the last
259 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700260 */
261 @GuardedBy("mRestrictionsLock")
262 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
263
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800264 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800265 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
266 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800267 */
268 @GuardedBy("mRestrictionsLock")
269 private Bundle mDevicePolicyGlobalUserRestrictions;
270
271 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800272 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
273 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800274 */
275 @GuardedBy("mRestrictionsLock")
276 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
277
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800278 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530279 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800280
281 /**
282 * Set of user IDs being actively removed. Removed IDs linger in this set
283 * for several seconds to work around a VFS caching issue.
284 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700285 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800286 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700287
Fyodor Kupolov82402752015-10-28 14:54:51 -0700288 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700289 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800290 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700291 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700292 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700293
Jason Monk62062992014-05-06 09:55:28 -0400294 private IAppOpsService mAppOpsService;
295
Makoto Onuki068c54a2015-10-13 14:34:03 -0700296 private final LocalService mLocalService;
297
Makoto Onukie7927da2015-11-25 10:05:17 -0800298 @GuardedBy("mUsersLock")
299 private boolean mIsDeviceManaged;
300
301 @GuardedBy("mUsersLock")
302 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
303
Makoto Onukid45a4a22015-11-02 17:17:38 -0800304 @GuardedBy("mUserRestrictionsListeners")
305 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
306 new ArrayList<>();
307
Clara Bayarria1771112015-12-18 16:29:18 +0000308 private final LockPatternUtils mLockPatternUtils;
309
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100310 /**
311 * Whether all users should be created ephemeral.
312 */
313 @GuardedBy("mUsersLock")
314 private boolean mForceEphemeralUsers;
315
Amith Yamasani258848d2012-08-10 17:06:33 -0700316 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700317
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 public static UserManagerService getInstance() {
319 synchronized (UserManagerService.class) {
320 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700321 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700322 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700323
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800324 @VisibleForTesting
325 UserManagerService(File dataDir) {
326 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700327 }
328
Dianne Hackborn4428e172012-08-24 17:43:05 -0700329 /**
330 * Called by package manager to create the service. This is closely
331 * associated with the package manager, and the given lock is the
332 * package manager's own lock.
333 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800334 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
335 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700336 }
337
Dianne Hackborn4428e172012-08-24 17:43:05 -0700338 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800339 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700340 mContext = context;
341 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800343 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800344 synchronized (mPackagesLock) {
345 mUsersDir = new File(dataDir, USER_INFO_DIR);
346 mUsersDir.mkdirs();
347 // Make zeroth user directory, for services to migrate their files to that location
348 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
349 userZeroDir.mkdirs();
350 FileUtils.setPermissions(mUsersDir.toString(),
351 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
352 -1, -1);
353 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
354 initDefaultGuestRestrictions();
355 readUserListLP();
356 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700357 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700358 mLocalService = new LocalService();
359 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000360 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700361 }
362
363 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100364 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800365 ArrayList<UserInfo> partials = new ArrayList<>();
366 synchronized (mUsersLock) {
367 final int userSize = mUsers.size();
368 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800369 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100370 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800371 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700373 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700374 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800375 final int partialsSize = partials.size();
376 for (int i = 0; i < partialsSize; i++) {
377 UserInfo ui = partials.get(i);
378 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
379 + " (name=" + ui.name + ")");
380 removeUserState(ui.id);
381 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800382
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700383 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800384
Jason Monk62062992014-05-06 09:55:28 -0400385 mAppOpsService = IAppOpsService.Stub.asInterface(
386 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800387
388 synchronized (mRestrictionsLock) {
389 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400390 }
Samuel Tand9453b82016-03-14 15:57:02 -0700391
392 UserInfo currentGuestUser = findCurrentGuestUser();
393 if (currentGuestUser != null && !hasUserRestriction(
394 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
395 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
396 // to it, in case this guest was created in a previous version where this
397 // user restriction was not a default guest restriction.
398 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
399 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
401
402 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800403 public String getUserAccount(int userId) {
404 checkManageUserAndAcrossUsersFullPermission("get user account");
405 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800406 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800407 }
408 }
409
410 @Override
411 public void setUserAccount(int userId, String accountName) {
412 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800413 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800414 synchronized (mPackagesLock) {
415 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800416 final UserData userData = mUsers.get(userId);
417 if (userData == null) {
418 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
419 return;
420 }
421 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800422 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800423 userData.account = accountName;
424 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800425 }
426 }
427
428 if (userToUpdate != null) {
429 writeUserLP(userToUpdate);
430 }
431 }
432 }
433
434 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700435 public UserInfo getPrimaryUser() {
436 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700437 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700438 final int userSize = mUsers.size();
439 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800440 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800441 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700442 return ui;
443 }
444 }
445 }
446 return null;
447 }
448
449 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700450 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700453 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700454 final int userSize = mUsers.size();
455 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800456 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (ui.partial) {
458 continue;
459 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800460 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700461 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700462 }
Amith Yamasani13593602012-03-22 16:16:17 -0700463 }
464 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700465 }
Amith Yamasani13593602012-03-22 16:16:17 -0700466 }
467
Amith Yamasani258848d2012-08-10 17:06:33 -0700468 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100469 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800470 if (userId != UserHandle.getCallingUserId()) {
471 checkManageUsersPermission("getting profiles related to user " + userId);
472 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 final long ident = Binder.clearCallingIdentity();
474 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 synchronized (mUsersLock) {
476 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100477 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700478 } finally {
479 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000480 }
481 }
482
Amith Yamasanibe465322014-04-24 13:45:17 -0700483 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700484 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
485 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700486 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700487 if (user == null) {
488 // Probably a dying user
489 return users;
490 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700491 final int userSize = mUsers.size();
492 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800493 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700494 if (!isProfileOf(user, profile)) {
495 continue;
496 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100497 if (enabledOnly && !profile.isEnabled()) {
498 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700499 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700500 if (mRemovingUserIds.get(profile.id)) {
501 continue;
502 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700503 users.add(profile);
504 }
505 return users;
506 }
507
Jessica Hummelbe81c802014-04-22 15:49:22 +0100508 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700509 public int getCredentialOwnerProfile(int userHandle) {
510 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000511 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700512 synchronized (mUsersLock) {
513 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700514 if (profileParent != null) {
515 return profileParent.id;
516 }
517 }
518 }
519
520 return userHandle;
521 }
522
523 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700524 public boolean isSameProfileGroup(int userId, int otherUserId) {
525 if (userId == otherUserId) return true;
526 checkManageUsersPermission("check if in the same profile group");
527 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700528 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700529 }
530 }
531
Fyodor Kupolov82402752015-10-28 14:54:51 -0700532 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
533 synchronized (mUsersLock) {
534 UserInfo userInfo = getUserInfoLU(userId);
535 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
536 return false;
537 }
538 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
539 if (otherUserInfo == null
540 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
541 return false;
542 }
543 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700544 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700545 }
546
547 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100548 public UserInfo getProfileParent(int userHandle) {
549 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700550 synchronized (mUsersLock) {
551 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700552 }
553 }
554
Fyodor Kupolov82402752015-10-28 14:54:51 -0700555 private UserInfo getProfileParentLU(int userHandle) {
556 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700557 if (profile == null) {
558 return null;
559 }
560 int parentUserId = profile.profileGroupId;
561 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
562 return null;
563 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100565 }
566 }
567
Fyodor Kupolov82402752015-10-28 14:54:51 -0700568 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100569 return user.id == profile.id ||
570 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
571 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000572 }
573
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000574 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000575 UserHandle parentHandle, boolean inQuietMode) {
576 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
577 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
578 intent.putExtra(Intent.EXTRA_USER, profileHandle);
579 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000580 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000581 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000582 }
583
584 @Override
585 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
586 checkManageUsersPermission("silence profile");
587 boolean changed = false;
588 UserInfo profile, parent;
589 synchronized (mPackagesLock) {
590 synchronized (mUsersLock) {
591 profile = getUserInfoLU(userHandle);
592 parent = getProfileParentLU(userHandle);
593
594 }
595 if (profile == null || !profile.isManagedProfile()) {
596 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
597 }
598 if (profile.isQuietModeEnabled() != enableQuietMode) {
599 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800600 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000601 changed = true;
602 }
603 }
604 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000605 long identity = Binder.clearCallingIdentity();
606 try {
607 if (enableQuietMode) {
608 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
609 } else {
610 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
611 }
612 } catch (RemoteException e) {
613 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
614 } finally {
615 Binder.restoreCallingIdentity(identity);
616 }
617
618 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
619 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000620 }
621 }
622
623 @Override
624 public boolean isQuietModeEnabled(int userHandle) {
625 synchronized (mPackagesLock) {
626 UserInfo info;
627 synchronized (mUsersLock) {
628 info = getUserInfoLU(userHandle);
629 }
630 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000631 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000632 }
633 return info.isQuietModeEnabled();
634 }
635 }
636
Kenny Guya52dc3e2014-02-11 15:33:14 +0000637 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100638 public void setUserEnabled(int userId) {
639 checkManageUsersPermission("enable user");
640 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 UserInfo info;
642 synchronized (mUsersLock) {
643 info = getUserInfoLU(userId);
644 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100645 if (info != null && !info.isEnabled()) {
646 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800647 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100648 }
649 }
650 }
651
652 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700653 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000654 checkManageUsersPermission("query user");
655 synchronized (mUsersLock) {
656 return getUserInfoLU(userId);
657 }
658 }
659
660 @Override
661 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000662 int callingUserId = UserHandle.getCallingUserId();
663 if (callingUserId != userId && !hasManageUsersPermission()) {
664 synchronized (mPackagesLock) {
665 if (!isSameProfileGroupLP(callingUserId, userId)) {
666 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000667 "You need MANAGE_USERS permission to: check if specified user a " +
668 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000669 }
670 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000671 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700672 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000673 UserInfo userInfo = getUserInfoLU(userId);
674 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700675 }
676 }
677
Amith Yamasani71e6c692013-03-24 17:39:28 -0700678 @Override
679 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700680 synchronized (mUsersLock) {
681 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700682 }
683 }
684
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700685 @Override
686 public boolean canHaveRestrictedProfile(int userId) {
687 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700688 synchronized (mUsersLock) {
689 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700690 if (userInfo == null || !userInfo.canHaveProfile()) {
691 return false;
692 }
693 if (!userInfo.isAdmin()) {
694 return false;
695 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800696 // restricted profile can be created if there is no DO set and the admin user has no PO;
697 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700698 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700699 }
700
Amith Yamasani195263742012-08-21 15:40:12 -0700701 /*
702 * Should be locked on mUsers before calling this.
703 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700704 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800705 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700706 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800707 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700708 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
709 return null;
710 }
Amith Yamasani12747872015-12-07 14:19:49 -0800711 return userData != null ? userData.info : null;
712 }
713
714 private UserData getUserDataLU(int userId) {
715 final UserData userData = mUsers.get(userId);
716 // If it is partial and not in the process of being removed, return as unknown user.
717 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
718 return null;
719 }
720 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700721 }
722
Fyodor Kupolov82402752015-10-28 14:54:51 -0700723 /**
724 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
725 * <p>No permissions checking or any addition checks are made</p>
726 */
727 private UserInfo getUserInfoNoChecks(int userId) {
728 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800729 final UserData userData = mUsers.get(userId);
730 return userData != null ? userData.info : null;
731 }
732 }
733
734 /**
735 * Obtains {@link #mUsersLock} and return UserData from mUsers.
736 * <p>No permissions checking or any addition checks are made</p>
737 */
738 private UserData getUserDataNoChecks(int userId) {
739 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700740 return mUsers.get(userId);
741 }
742 }
743
Amith Yamasani236b2b52015-08-18 14:32:14 -0700744 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700745 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700746 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700747 }
748
Amith Yamasani258848d2012-08-10 17:06:33 -0700749 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700750 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700751 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700752 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700753 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800754 UserData userData = getUserDataNoChecks(userId);
755 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700756 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
757 return;
758 }
Amith Yamasani12747872015-12-07 14:19:49 -0800759 if (name != null && !name.equals(userData.info.name)) {
760 userData.info.name = name;
761 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700762 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700763 }
764 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700765 if (changed) {
766 sendUserInfoChangedBroadcast(userId);
767 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700768 }
769
Amith Yamasani258848d2012-08-10 17:06:33 -0700770 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700771 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700772 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100773 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
774 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
775 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700776 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100777 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700778 }
779
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100780
781
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700782 private void sendUserInfoChangedBroadcast(int userId) {
783 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
784 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
785 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700786 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700787 }
788
Amith Yamasani258848d2012-08-10 17:06:33 -0700789 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100790 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100791 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700792 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100793 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
794 if (targetUserInfo == null || targetUserInfo.partial) {
795 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700796 return null;
797 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100798
799 final int callingUserId = UserHandle.getCallingUserId();
800 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
801 final int targetGroupId = targetUserInfo.profileGroupId;
802 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
803 && callingGroupId == targetGroupId);
804 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100805 checkManageUsersPermission("get the icon of a user who is not related");
806 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100807
808 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700809 return null;
810 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100811 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700812 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100813
814 try {
815 return ParcelFileDescriptor.open(
816 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
817 } catch (FileNotFoundException e) {
818 Log.e(LOG_TAG, "Couldn't find icon file", e);
819 }
820 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700821 }
822
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700823 public void makeInitialized(int userId) {
824 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800825 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800826 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800827 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800828 userData = mUsers.get(userId);
829 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700830 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800831 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700832 }
Amith Yamasani12747872015-12-07 14:19:49 -0800833 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
834 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800835 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700836 }
837 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800838 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800839 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800840 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700841 }
842
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700843 /**
844 * If default guest restrictions haven't been initialized yet, add the basic
845 * restrictions.
846 */
847 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800848 synchronized (mGuestRestrictions) {
849 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700850 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800851 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800852 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
853 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
854 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700855 }
856 }
857
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800858 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530859 public Bundle getDefaultGuestRestrictions() {
860 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800861 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530862 return new Bundle(mGuestRestrictions);
863 }
864 }
865
866 @Override
867 public void setDefaultGuestRestrictions(Bundle restrictions) {
868 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800869 synchronized (mGuestRestrictions) {
870 mGuestRestrictions.clear();
871 mGuestRestrictions.putAll(restrictions);
872 }
873 synchronized (mPackagesLock) {
874 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530875 }
876 }
877
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800878 /**
879 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
880 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800881 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800882 @Nullable Bundle global) {
883 Preconditions.checkNotNull(local);
884 boolean globalChanged = false;
885 boolean localChanged;
886 synchronized (mRestrictionsLock) {
887 if (global != null) {
888 // Update global.
889 globalChanged = !UserRestrictionsUtils.areEqual(
890 mDevicePolicyGlobalUserRestrictions, global);
891 if (globalChanged) {
892 mDevicePolicyGlobalUserRestrictions = global;
893 }
894 }
895 {
896 // Update local.
897 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
898 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
899 if (localChanged) {
900 mDevicePolicyLocalUserRestrictions.put(userId, local);
901 }
902 }
903 }
904 if (DBG) {
905 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
906 + " global=" + global + (globalChanged ? " (changed)" : "")
907 + " local=" + local + (localChanged ? " (changed)" : "")
908 );
909 }
910 // Don't call them within the mRestrictionsLock.
911 synchronized (mPackagesLock) {
912 if (globalChanged) {
913 writeUserListLP();
914 }
915 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800916 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800917 }
918 }
919
920 synchronized (mRestrictionsLock) {
921 if (globalChanged) {
922 applyUserRestrictionsForAllUsersLR();
923 } else if (localChanged) {
924 applyUserRestrictionsLR(userId);
925 }
926 }
927 }
928
Makoto Onuki068c54a2015-10-13 14:34:03 -0700929 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700930 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800931 final Bundle baseRestrictions =
932 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
933 final Bundle global = mDevicePolicyGlobalUserRestrictions;
934 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700935
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800936 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
937 // Common case first.
938 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700939 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800940 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
941 UserRestrictionsUtils.merge(effective, global);
942 UserRestrictionsUtils.merge(effective, local);
943
Makoto Onuki068c54a2015-10-13 14:34:03 -0700944 return effective;
945 }
946
947 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700948 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700949 if (DBG) {
950 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
951 }
952 mCachedEffectiveUserRestrictions.remove(userId);
953 }
954
955 private Bundle getEffectiveUserRestrictions(int userId) {
956 synchronized (mRestrictionsLock) {
957 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
958 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700959 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700960 mCachedEffectiveUserRestrictions.put(userId, restrictions);
961 }
962 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700963 }
964 }
965
Makoto Onuki068c54a2015-10-13 14:34:03 -0700966 /** @return a specific user restriction that's in effect currently. */
967 @Override
968 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800969 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
970 return false;
971 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 Bundle restrictions = getEffectiveUserRestrictions(userId);
973 return restrictions != null && restrictions.getBoolean(restrictionKey);
974 }
975
976 /**
977 * @return UserRestrictions that are in effect currently. This always returns a new
978 * {@link Bundle}.
979 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700980 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800981 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800982 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800983 }
984
985 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000986 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
987 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800988 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
989 return false;
990 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000991 synchronized (mRestrictionsLock) {
992 Bundle bundle = mBaseUserRestrictions.get(userId);
993 return (bundle != null && bundle.getBoolean(restrictionKey, false));
994 }
995 }
996
997 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700998 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700999 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001000 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1001 return;
1002 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001003 synchronized (mRestrictionsLock) {
1004 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1005 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001006 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1007 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001008 newRestrictions.putBoolean(key, value);
1009
Fyodor Kupolov82402752015-10-28 14:54:51 -07001010 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001011 }
1012 }
1013
Makoto Onuki068c54a2015-10-13 14:34:03 -07001014 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001015 * Optionally updating user restrictions, calculate the effective user restrictions and also
1016 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001017 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001018 * @param newRestrictions User restrictions to set.
1019 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001020 * @param userId target user ID.
1021 */
1022 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001023 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001024 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001025
1026 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1027 mAppliedUserRestrictions.get(userId));
1028
1029 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001030 if (newRestrictions != null) {
1031 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001032 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1033
1034 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001035 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1036 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001037
1038 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1039 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001040 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001041 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001042 }
1043
Fyodor Kupolov82402752015-10-28 14:54:51 -07001044 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001045
Makoto Onuki759a7632015-10-28 16:43:10 -07001046 mCachedEffectiveUserRestrictions.put(userId, effective);
1047
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001048 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001049 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001050 debug("Applying user restrictions: userId=" + userId
1051 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001052 }
1053
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001054 if (mAppOpsService != null) { // We skip it until system-ready.
1055 final long token = Binder.clearCallingIdentity();
1056 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001057 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001058 } catch (RemoteException e) {
1059 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1060 } finally {
1061 Binder.restoreCallingIdentity(token);
1062 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001063 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001064
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001065 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001066
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001067 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001068 }
1069
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001070 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001071 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001072 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1073 // actually, but we still need some kind of synchronization otherwise we might end up
1074 // calling listeners out-of-order, thus "LR".
1075
1076 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1077 return;
1078 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001079
1080 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1081 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1082
1083 mHandler.post(new Runnable() {
1084 @Override
1085 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001086 UserRestrictionsUtils.applyUserRestrictions(
1087 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001088
Makoto Onukid45a4a22015-11-02 17:17:38 -08001089 final UserRestrictionsListener[] listeners;
1090 synchronized (mUserRestrictionsListeners) {
1091 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1092 mUserRestrictionsListeners.toArray(listeners);
1093 }
1094 for (int i = 0; i < listeners.length; i++) {
1095 listeners[i].onUserRestrictionsChanged(userId,
1096 newRestrictionsFinal, prevRestrictionsFinal);
1097 }
1098 }
1099 });
1100 }
1101
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001102 // Package private for the inner class.
1103 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001104 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001105 }
1106
1107 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108 // Package private for the inner class.
1109 void applyUserRestrictionsForAllUsersLR() {
1110 if (DBG) {
1111 debug("applyUserRestrictionsForAllUsersLR");
1112 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001113 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001114 mCachedEffectiveUserRestrictions.clear();
1115
Makoto Onuki068c54a2015-10-13 14:34:03 -07001116 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1117 // it on a handler.
1118 final Runnable r = new Runnable() {
1119 @Override
1120 public void run() {
1121 // Then get the list of running users.
1122 final int[] runningUsers;
1123 try {
1124 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1125 } catch (RemoteException e) {
1126 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1127 return;
1128 }
1129 // Then re-calculate the effective restrictions and apply, only for running users.
1130 // It's okay if a new user has started after the getRunningUserIds() call,
1131 // because we'll do the same thing (re-calculate the restrictions and apply)
1132 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001133 synchronized (mRestrictionsLock) {
1134 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001135 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001136 }
1137 }
1138 }
1139 };
1140 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001141 }
1142
Amith Yamasani258848d2012-08-10 17:06:33 -07001143 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001144 * Check if we've hit the limit of how many users can be created.
1145 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001146 private boolean isUserLimitReached() {
1147 int count;
1148 synchronized (mUsersLock) {
1149 count = getAliveUsersExcludingGuestsCountLU();
1150 }
1151 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001152 }
1153
1154 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001155 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001156 checkManageUsersPermission("check if more managed profiles can be added.");
1157 if (ActivityManager.isLowRamDeviceStatic()) {
1158 return false;
1159 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001160 if (!mContext.getPackageManager().hasSystemFeature(
1161 PackageManager.FEATURE_MANAGED_USERS)) {
1162 return false;
1163 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001164 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001165 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1166 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1167 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001168 return false;
1169 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001170 synchronized(mUsersLock) {
1171 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001172 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001173 return false;
1174 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001175 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1176 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001177 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001178 return usersCountAfterRemoving == 1
1179 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001180 }
1181 }
1182
Fyodor Kupolov82402752015-10-28 14:54:51 -07001183 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001184 int aliveUserCount = 0;
1185 final int totalUserCount = mUsers.size();
1186 // Skip over users being removed
1187 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001188 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001189 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001190 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001191 aliveUserCount++;
1192 }
1193 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001194 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001195 }
1196
1197 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001198 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001199 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1200 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1201 * permissions can make certain calls to the UserManager.
1202 *
1203 * @param message used as message if SecurityException is thrown
1204 * @throws SecurityException if the caller does not have enough privilege.
1205 */
1206 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1207 final int uid = Binder.getCallingUid();
1208 if (uid != Process.SYSTEM_UID && uid != 0
1209 && ActivityManager.checkComponentPermission(
1210 Manifest.permission.MANAGE_USERS,
1211 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1212 && ActivityManager.checkComponentPermission(
1213 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1214 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1215 throw new SecurityException(
1216 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1217 + message);
1218 }
1219 }
1220
1221 /**
1222 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001223 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001224 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001225 *
1226 * @param message used as message if SecurityException is thrown
1227 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001228 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001229 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001230 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001231 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001232 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1233 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001234 }
1235
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001236 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001237 * @return whether the calling UID is system UID or root's UID or the calling app has the
1238 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1239 */
1240 private static final boolean hasManageUsersPermission() {
1241 final int callingUid = Binder.getCallingUid();
1242 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1243 || callingUid == Process.ROOT_UID
1244 || ActivityManager.checkComponentPermission(
1245 android.Manifest.permission.MANAGE_USERS,
1246 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1247 }
1248
1249 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001250 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1251 * UserManager.
1252 *
1253 * @param message used as message if SecurityException is thrown
1254 * @throws SecurityException if the caller is not system or root
1255 */
1256 private static void checkSystemOrRoot(String message) {
1257 final int uid = Binder.getCallingUid();
1258 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1259 throw new SecurityException("Only system may: " + message);
1260 }
1261 }
1262
Fyodor Kupolov82402752015-10-28 14:54:51 -07001263 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001264 try {
1265 File dir = new File(mUsersDir, Integer.toString(info.id));
1266 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001267 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001268 if (!dir.exists()) {
1269 dir.mkdir();
1270 FileUtils.setPermissions(
1271 dir.getPath(),
1272 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1273 -1, -1);
1274 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001275 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001276 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001277 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001278 info.iconPath = file.getAbsolutePath();
1279 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001280 try {
1281 os.close();
1282 } catch (IOException ioe) {
1283 // What the ... !
1284 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001285 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001286 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001287 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001288 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001289 }
1290
Amith Yamasani0b285492011-04-14 17:35:23 -07001291 /**
1292 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1293 * cache it elsewhere.
1294 * @return the array of user ids.
1295 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001296 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001297 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001298 return mUserIds;
1299 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001300 }
1301
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001302 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001303 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001304 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001305 return;
1306 }
1307 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001308 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001310 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001312 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001313 int type;
1314 while ((type = parser.next()) != XmlPullParser.START_TAG
1315 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001316 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 }
1318
1319 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001320 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001321 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001322 return;
1323 }
1324
Amith Yamasani2a003292012-08-14 18:25:45 -07001325 mNextSerialNumber = -1;
1326 if (parser.getName().equals(TAG_USERS)) {
1327 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1328 if (lastSerialNumber != null) {
1329 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1330 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001331 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1332 if (versionNumber != null) {
1333 mUserVersion = Integer.parseInt(versionNumber);
1334 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001335 }
1336
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1338
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001339 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301340 if (type == XmlPullParser.START_TAG) {
1341 final String name = parser.getName();
1342 if (name.equals(TAG_USER)) {
1343 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001344
Amith Yamasani12747872015-12-07 14:19:49 -08001345 UserData userData = readUserLP(Integer.parseInt(id));
1346
1347 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001348 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001349 mUsers.put(userData.info.id, userData);
1350 if (mNextSerialNumber < 0
1351 || mNextSerialNumber <= userData.info.id) {
1352 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001353 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301354 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001355 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301356 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001357 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1358 && type != XmlPullParser.END_TAG) {
1359 if (type == XmlPullParser.START_TAG) {
1360 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001361 synchronized (mGuestRestrictions) {
1362 UserRestrictionsUtils
1363 .readRestrictions(parser, mGuestRestrictions);
1364 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001365 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1366 ) {
1367 UserRestrictionsUtils.readRestrictions(parser,
1368 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001369 }
1370 break;
1371 }
1372 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001373 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001374 }
1375 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001376 synchronized (mRestrictionsLock) {
1377 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1378 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001379 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001380 upgradeIfNecessaryLP();
1381 } catch (IOException | XmlPullParserException e) {
1382 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001383 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001384 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 }
1386 }
1387
Amith Yamasani6f34b412012-10-22 18:19:27 -07001388 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001389 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001390 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001391 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001392 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001393 int userVersion = mUserVersion;
1394 if (userVersion < 1) {
1395 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001396 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1397 if ("Primary".equals(userData.info.name)) {
1398 userData.info.name =
1399 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1400 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001401 }
1402 userVersion = 1;
1403 }
1404
Amith Yamasanibc9625052012-11-15 14:39:18 -08001405 if (userVersion < 2) {
1406 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001407 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1408 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1409 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1410 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001411 }
1412 userVersion = 2;
1413 }
1414
Amith Yamasani350962c2013-08-06 11:18:53 -07001415
Amith Yamasani5e486f52013-08-07 11:06:44 -07001416 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001417 userVersion = 4;
1418 }
1419
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001420 if (userVersion < 5) {
1421 initDefaultGuestRestrictions();
1422 userVersion = 5;
1423 }
1424
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001425 if (userVersion < 6) {
1426 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001427 synchronized (mUsersLock) {
1428 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001429 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001430 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001431 if (!splitSystemUser && userData.info.isRestricted()
1432 && (userData.info.restrictedProfileParentId
1433 == UserInfo.NO_PROFILE_GROUP_ID)) {
1434 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1435 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001436 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001437 }
1438 }
1439 userVersion = 6;
1440 }
1441
Amith Yamasani6f34b412012-10-22 18:19:27 -07001442 if (userVersion < USER_VERSION) {
1443 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1444 + USER_VERSION);
1445 } else {
1446 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447
1448 if (originalVersion < mUserVersion) {
1449 writeUserListLP();
1450 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001451 }
1452 }
1453
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001454 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001455 int flags = UserInfo.FLAG_INITIALIZED;
1456 // In split system user mode, the admin and primary flags are assigned to the first human
1457 // user.
1458 if (!UserManager.isSplitSystemUser()) {
1459 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1460 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001461 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001462 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001463 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001464 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001465 UserData userData = new UserData();
1466 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001467 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001468 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001469 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001470 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001471 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001472
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001473 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001474 synchronized (mRestrictionsLock) {
1475 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1476 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001477
Fyodor Kupolov82402752015-10-28 14:54:51 -07001478 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001479 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001480
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001481 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001482 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001483 }
1484
Amith Yamasani12747872015-12-07 14:19:49 -08001485 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001486 if (DBG) {
1487 debug("scheduleWriteUser");
1488 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001489 // No need to wrap it within a lock -- worst case, we'll just post the same message
1490 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001491 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1492 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001493 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1494 }
1495 }
1496
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001497 /*
1498 * Writes the user file in this format:
1499 *
1500 * <user flags="20039023" id="0">
1501 * <name>Primary</name>
1502 * </user>
1503 */
Amith Yamasani12747872015-12-07 14:19:49 -08001504 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001506 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001508 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001509 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001510 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001511 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001512 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1513
1514 // XmlSerializer serializer = XmlUtils.serializerInstance();
1515 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001516 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001517 serializer.startDocument(null, true);
1518 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1519
Amith Yamasani12747872015-12-07 14:19:49 -08001520 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001521 serializer.startTag(null, TAG_USER);
1522 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001523 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001524 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001525 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1526 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1527 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001528 if (userInfo.iconPath != null) {
1529 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1530 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001531 if (userInfo.partial) {
1532 serializer.attribute(null, ATTR_PARTIAL, "true");
1533 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001534 if (userInfo.guestToRemove) {
1535 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1536 }
Kenny Guy2a764942014-04-02 13:29:20 +01001537 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1538 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1539 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001540 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001541 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1542 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1543 Integer.toString(userInfo.restrictedProfileParentId));
1544 }
Amith Yamasani12747872015-12-07 14:19:49 -08001545 // Write seed data
1546 if (userData.persistSeedData) {
1547 if (userData.seedAccountName != null) {
1548 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1549 }
1550 if (userData.seedAccountType != null) {
1551 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1552 }
1553 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001554 serializer.startTag(null, TAG_NAME);
1555 serializer.text(userInfo.name);
1556 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001557 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001558 UserRestrictionsUtils.writeRestrictions(serializer,
1559 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1560 UserRestrictionsUtils.writeRestrictions(serializer,
1561 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1562 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001563 }
Amith Yamasani12747872015-12-07 14:19:49 -08001564
1565 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001566 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001567 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001568 serializer.endTag(null, TAG_ACCOUNT);
1569 }
1570
Amith Yamasani12747872015-12-07 14:19:49 -08001571 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1572 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1573 userData.seedAccountOptions.saveToXml(serializer);
1574 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1575 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001576 serializer.endTag(null, TAG_USER);
1577
1578 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001579 userFile.finishWrite(fos);
1580 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001581 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001582 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001583 }
1584 }
1585
1586 /*
1587 * Writes the user list file in this format:
1588 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001589 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001590 * <user id="0"></user>
1591 * <user id="2"></user>
1592 * </users>
1593 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001594 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 if (DBG) {
1596 debug("writeUserList");
1597 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001598 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001599 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001600 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001601 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001602 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1603
1604 // XmlSerializer serializer = XmlUtils.serializerInstance();
1605 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001606 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001607 serializer.startDocument(null, true);
1608 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1609
1610 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001612 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001613
Adam Lesinskieddeb492014-09-08 17:50:03 -07001614 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001615 synchronized (mGuestRestrictions) {
1616 UserRestrictionsUtils
1617 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1618 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301619 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001620 synchronized (mRestrictionsLock) {
1621 UserRestrictionsUtils.writeRestrictions(serializer,
1622 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1623 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001624 int[] userIdsToWrite;
1625 synchronized (mUsersLock) {
1626 userIdsToWrite = new int[mUsers.size()];
1627 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001628 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001629 userIdsToWrite[i] = user.id;
1630 }
1631 }
1632 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001633 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001634 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001635 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001636 }
1637
1638 serializer.endTag(null, TAG_USERS);
1639
1640 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001641 userListFile.finishWrite(fos);
1642 } catch (Exception e) {
1643 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001644 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001645 }
1646 }
1647
Amith Yamasani12747872015-12-07 14:19:49 -08001648 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001649 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001650 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001652 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001653 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001654 long creationTime = 0L;
1655 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001656 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001657 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001658 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001659 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001660 boolean persistSeedData = false;
1661 String seedAccountName = null;
1662 String seedAccountType = null;
1663 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001664 Bundle baseRestrictions = new Bundle();
1665 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001666
1667 FileInputStream fis = null;
1668 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001669 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001670 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001671 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001672 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001673 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001674 int type;
1675 while ((type = parser.next()) != XmlPullParser.START_TAG
1676 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001677 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001678 }
1679
1680 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001681 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 return null;
1683 }
1684
1685 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001686 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1687 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001688 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001689 return null;
1690 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001691 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1692 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001693 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001694 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1695 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001696 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1697 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001698 restrictedProfileParentId = readIntAttribute(parser,
1699 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001700 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1701 if ("true".equals(valueString)) {
1702 partial = true;
1703 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001704 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1705 if ("true".equals(valueString)) {
1706 guestToRemove = true;
1707 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001708
Amith Yamasani12747872015-12-07 14:19:49 -08001709 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1710 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1711 if (seedAccountName != null || seedAccountType != null) {
1712 persistSeedData = true;
1713 }
1714
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001715 int outerDepth = parser.getDepth();
1716 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1717 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1718 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1719 continue;
1720 }
1721 String tag = parser.getName();
1722 if (TAG_NAME.equals(tag)) {
1723 type = parser.next();
1724 if (type == XmlPullParser.TEXT) {
1725 name = parser.getText();
1726 }
1727 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1729 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1730 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001731 } else if (TAG_ACCOUNT.equals(tag)) {
1732 type = parser.next();
1733 if (type == XmlPullParser.TEXT) {
1734 account = parser.getText();
1735 }
Amith Yamasani12747872015-12-07 14:19:49 -08001736 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1737 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1738 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001739 }
1740 }
1741 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001742
Amith Yamasani12747872015-12-07 14:19:49 -08001743 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001744 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001745 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001746 userInfo.creationTime = creationTime;
1747 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001748 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001749 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001750 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001751 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001752
1753 // Create the UserData object that's internal to this class
1754 UserData userData = new UserData();
1755 userData.info = userInfo;
1756 userData.account = account;
1757 userData.seedAccountName = seedAccountName;
1758 userData.seedAccountType = seedAccountType;
1759 userData.persistSeedData = persistSeedData;
1760 userData.seedAccountOptions = seedAccountOptions;
1761
Makoto Onuki068c54a2015-10-13 14:34:03 -07001762 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 mBaseUserRestrictions.put(id, baseRestrictions);
1764 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001765 }
Amith Yamasani12747872015-12-07 14:19:49 -08001766 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001767 } catch (IOException ioe) {
1768 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001769 } finally {
1770 if (fis != null) {
1771 try {
1772 fis.close();
1773 } catch (IOException e) {
1774 }
1775 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001776 }
1777 return null;
1778 }
1779
Amith Yamasani920ace02012-09-20 22:15:37 -07001780 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1781 String valueString = parser.getAttributeValue(null, attr);
1782 if (valueString == null) return defaultValue;
1783 try {
1784 return Integer.parseInt(valueString);
1785 } catch (NumberFormatException nfe) {
1786 return defaultValue;
1787 }
1788 }
1789
1790 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1791 String valueString = parser.getAttributeValue(null, attr);
1792 if (valueString == null) return defaultValue;
1793 try {
1794 return Long.parseLong(valueString);
1795 } catch (NumberFormatException nfe) {
1796 return defaultValue;
1797 }
1798 }
1799
Amith Yamasanib82add22013-07-09 11:24:44 -07001800 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001801 * Removes the app restrictions file for a specific package and user id, if it exists.
1802 */
1803 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1804 synchronized (mPackagesLock) {
1805 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001806 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001807 if (resFile.exists()) {
1808 resFile.delete();
1809 }
1810 }
1811 }
1812
Kenny Guya52dc3e2014-02-11 15:33:14 +00001813 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001814 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001815 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001816 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001817 }
1818
Amith Yamasani258848d2012-08-10 17:06:33 -07001819 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001820 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001821 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001822 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001823 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001824
Jessica Hummelbe81c802014-04-22 15:49:22 +01001825 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001826 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001827 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1828 return null;
1829 }
phweisse9c44062016-02-10 12:57:38 +01001830 return createUserInternalUnchecked(name, flags, parentId);
1831 }
1832
1833 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001834 if (ActivityManager.isLowRamDeviceStatic()) {
1835 return null;
1836 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001837 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001838 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001839 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001840 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001841 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001842 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001843 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001844 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001845 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001846 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001847 if (parentId != UserHandle.USER_NULL) {
1848 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001849 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001850 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001851 if (parent == null) return null;
1852 }
1853 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1854 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1855 return null;
1856 }
1857 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1858 // If we're not adding a guest user or a managed profile and the limit has
1859 // been reached, cannot add a user.
1860 return null;
1861 }
1862 // If we're adding a guest and there already exists one, bail.
1863 if (isGuest && findCurrentGuestUser() != null) {
1864 return null;
1865 }
1866 // In legacy mode, restricted profile's parent can only be the owner user
1867 if (isRestricted && !UserManager.isSplitSystemUser()
1868 && (parentId != UserHandle.USER_SYSTEM)) {
1869 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1870 return null;
1871 }
1872 if (isRestricted && UserManager.isSplitSystemUser()) {
1873 if (parent == null) {
1874 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1875 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001876 return null;
1877 }
Amith Yamasani12747872015-12-07 14:19:49 -08001878 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1880 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001881 return null;
1882 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001883 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001884 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1885 Log.e(LOG_TAG,
1886 "Ephemeral users are supported on split-system-user systems only.");
1887 return null;
1888 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001889 // In split system user mode, we assign the first human user the primary flag.
1890 // And if there is no device owner, we also assign the admin flag to primary user.
1891 if (UserManager.isSplitSystemUser()
1892 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1893 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001894 synchronized (mUsersLock) {
1895 if (!mIsDeviceManaged) {
1896 flags |= UserInfo.FLAG_ADMIN;
1897 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001898 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001899 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001900
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001901 userId = getNextAvailableId();
1902 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001903 boolean ephemeralGuests = Resources.getSystem()
1904 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001905
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001906 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001907 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1908 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1909 || (parent != null && parent.info.isEphemeral())) {
1910 flags |= UserInfo.FLAG_EPHEMERAL;
1911 }
1912
1913 userInfo = new UserInfo(userId, name, null, flags);
1914 userInfo.serialNumber = mNextSerialNumber++;
1915 long now = System.currentTimeMillis();
1916 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1917 userInfo.partial = true;
1918 userData = new UserData();
1919 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001920 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001921 }
1922 writeUserListLP();
1923 if (parent != null) {
1924 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001925 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1926 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001927 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001928 }
Amith Yamasani12747872015-12-07 14:19:49 -08001929 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001930 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001931 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1932 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001933 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001934 }
Amith Yamasani12747872015-12-07 14:19:49 -08001935 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001936 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001937 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001938 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001939 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001940 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001941 prepareUserStorage(userId, userInfo.serialNumber,
1942 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001943 mPm.createNewUser(userId);
1944 userInfo.partial = false;
1945 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001946 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001947 }
1948 updateUserIds();
1949 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001950 if (isGuest) {
1951 synchronized (mGuestRestrictions) {
1952 restrictions.putAll(mGuestRestrictions);
1953 }
1954 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001955 synchronized (mRestrictionsLock) {
1956 mBaseUserRestrictions.append(userId, restrictions);
1957 }
1958 mPm.newUserCreated(userId);
1959 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1960 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1961 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1962 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001963 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001964 } finally {
1965 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001966 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001967 return userInfo;
1968 }
1969
Amith Yamasani0b285492011-04-14 17:35:23 -07001970 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001971 * @hide
1972 */
Amith Yamasani12747872015-12-07 14:19:49 -08001973 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001974 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1975 checkManageUsersPermission("setupRestrictedProfile");
1976 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1977 if (user == null) {
1978 return null;
1979 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08001980 long identity = Binder.clearCallingIdentity();
1981 try {
1982 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1983 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1984 // the putIntForUser() will fail.
1985 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1986 android.provider.Settings.Secure.LOCATION_MODE,
1987 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1988 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1989 } finally {
1990 Binder.restoreCallingIdentity(identity);
1991 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001992 return user;
1993 }
1994
1995 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001996 * Find the current guest user. If the Guest user is partial,
1997 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001998 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001999 private UserInfo findCurrentGuestUser() {
2000 synchronized (mUsersLock) {
2001 final int size = mUsers.size();
2002 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002003 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002004 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2005 return user;
2006 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002007 }
2008 }
2009 return null;
2010 }
2011
2012 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002013 * Mark this guest user for deletion to allow us to create another guest
2014 * and switch to that user before actually removing this guest.
2015 * @param userHandle the userid of the current guest
2016 * @return whether the user could be marked for deletion
2017 */
Amith Yamasani12747872015-12-07 14:19:49 -08002018 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002019 public boolean markGuestForDeletion(int userHandle) {
2020 checkManageUsersPermission("Only the system can remove users");
2021 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2022 UserManager.DISALLOW_REMOVE_USER, false)) {
2023 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2024 return false;
2025 }
2026
2027 long ident = Binder.clearCallingIdentity();
2028 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002029 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002030 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002031 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002032 userData = mUsers.get(userHandle);
2033 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002034 return false;
2035 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002036 }
Amith Yamasani12747872015-12-07 14:19:49 -08002037 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002038 return false;
2039 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002040 // We set this to a guest user that is to be removed. This is a temporary state
2041 // where we are allowed to add new Guest users, even if this one is still not
2042 // removed. This user will still show up in getUserInfo() calls.
2043 // If we don't get around to removing this Guest user, it will be purged on next
2044 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002045 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002046 // Mark it as disabled, so that it isn't returned any more when
2047 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002048 userData.info.flags |= UserInfo.FLAG_DISABLED;
2049 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002050 }
2051 } finally {
2052 Binder.restoreCallingIdentity(ident);
2053 }
2054 return true;
2055 }
2056
2057 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002058 * Removes a user and all data directories created for that user. This method should be called
2059 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002060 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002061 */
Amith Yamasani12747872015-12-07 14:19:49 -08002062 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002063 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002064 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002065 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2066 UserManager.DISALLOW_REMOVE_USER, false)) {
2067 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2068 return false;
2069 }
2070
Kenny Guyee58b4f2014-05-23 15:19:53 +01002071 long ident = Binder.clearCallingIdentity();
2072 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002073 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002074 int currentUser = ActivityManager.getCurrentUser();
2075 if (currentUser == userHandle) {
2076 Log.w(LOG_TAG, "Current user cannot be removed");
2077 return false;
2078 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002079 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002080 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002081 userData = mUsers.get(userHandle);
2082 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002083 return false;
2084 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002085
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 // We remember deleted user IDs to prevent them from being
2087 // reused during the current boot; they can still be reused
2088 // after a reboot.
2089 mRemovingUserIds.put(userHandle, true);
2090 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002091
Kenny Guyee58b4f2014-05-23 15:19:53 +01002092 try {
2093 mAppOpsService.removeUser(userHandle);
2094 } catch (RemoteException e) {
2095 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2096 }
2097 // Set this to a partially created user, so that the user will be purged
2098 // on next startup, in case the runtime stops now before stopping and
2099 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002100 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002101 // Mark it as disabled, so that it isn't returned any more when
2102 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002103 userData.info.flags |= UserInfo.FLAG_DISABLED;
2104 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002105 }
2106
Amith Yamasani12747872015-12-07 14:19:49 -08002107 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2108 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002109 // Send broadcast to notify system that the user removed was a
2110 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002111 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002112 }
2113
2114 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2115 int res;
2116 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002117 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2118 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002119 @Override
2120 public void userStopped(int userId) {
2121 finishRemoveUser(userId);
2122 }
2123 @Override
2124 public void userStopAborted(int userId) {
2125 }
2126 });
2127 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002128 return false;
2129 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002130 return res == ActivityManager.USER_OP_SUCCESS;
2131 } finally {
2132 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002133 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002134 }
2135
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002136 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002137 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002138 // Let other services shutdown any activity and clean up their state before completely
2139 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002140 long ident = Binder.clearCallingIdentity();
2141 try {
2142 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2143 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002144 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2145 android.Manifest.permission.MANAGE_USERS,
2146
2147 new BroadcastReceiver() {
2148 @Override
2149 public void onReceive(Context context, Intent intent) {
2150 if (DBG) {
2151 Slog.i(LOG_TAG,
2152 "USER_REMOVED broadcast sent, cleaning up user data "
2153 + userHandle);
2154 }
2155 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002156 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002157 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002158 // Clean up any ActivityManager state
2159 LocalServices.getService(ActivityManagerInternal.class)
2160 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002161 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002162 }
2163 }.start();
2164 }
2165 },
2166
2167 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002168 } finally {
2169 Binder.restoreCallingIdentity(ident);
2170 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002171 }
2172
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002173 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002174 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002175 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002176 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002177
2178 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002179 synchronized (mUsersLock) {
2180 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002181 mIsUserManaged.delete(userHandle);
2182 }
2183 synchronized (mRestrictionsLock) {
2184 mBaseUserRestrictions.remove(userHandle);
2185 mAppliedUserRestrictions.remove(userHandle);
2186 mCachedEffectiveUserRestrictions.remove(userHandle);
2187 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002188 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002189 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002190 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002191 userFile.delete();
2192 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002193 synchronized (mPackagesLock) {
2194 writeUserListLP();
2195 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002196 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002197 File userDir = Environment.getUserSystemDirectory(userHandle);
2198 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2199 if (userDir.renameTo(renamedUserDir)) {
2200 removeDirectoryRecursive(renamedUserDir);
2201 } else {
2202 removeDirectoryRecursive(userDir);
2203 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002204 }
2205
Amith Yamasani61f57372012-08-31 12:12:28 -07002206 private void removeDirectoryRecursive(File parent) {
2207 if (parent.isDirectory()) {
2208 String[] files = parent.list();
2209 for (String filename : files) {
2210 File child = new File(parent, filename);
2211 removeDirectoryRecursive(child);
2212 }
2213 }
2214 parent.delete();
2215 }
2216
Kenny Guyf8d3a232014-05-15 16:09:52 +01002217 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002218 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002219 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2220 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002221 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002222 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002223 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002224 }
2225
Amith Yamasani2a003292012-08-14 18:25:45 -07002226 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002227 public Bundle getApplicationRestrictions(String packageName) {
2228 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2229 }
2230
2231 @Override
2232 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002233 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002234 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002235 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002236 }
2237 synchronized (mPackagesLock) {
2238 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002239 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002240 }
2241 }
2242
2243 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002244 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002245 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002246 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002247 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002248 if (restrictions == null || restrictions.isEmpty()) {
2249 cleanAppRestrictionsForPackage(packageName, userId);
2250 } else {
2251 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002252 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002253 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002254 }
Robin Lee66e5d962014-04-09 16:44:21 +01002255
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002256 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2257 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2258 changeIntent.setPackage(packageName);
2259 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2260 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002261 }
2262
2263 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002264 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002265 try {
2266 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002267 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002268 } catch (NameNotFoundException nnfe) {
2269 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002270 } finally {
2271 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002272 }
2273 }
2274
Fyodor Kupolov82402752015-10-28 14:54:51 -07002275 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002276 AtomicFile restrictionsFile =
2277 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2278 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002279 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002280 }
2281
2282 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002283 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002284 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002285 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002286 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002287 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002288 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002289
2290 FileInputStream fis = null;
2291 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002292 fis = restrictionsFile.openRead();
2293 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002294 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002295 XmlUtils.nextElement(parser);
2296 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002297 Slog.e(LOG_TAG, "Unable to read restrictions file "
2298 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002299 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002300 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002301 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2302 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002303 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002304 } catch (IOException|XmlPullParserException e) {
2305 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002306 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002307 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002308 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002309 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002310 }
2311
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002312 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2313 XmlPullParser parser) throws XmlPullParserException, IOException {
2314 int type = parser.getEventType();
2315 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2316 String key = parser.getAttributeValue(null, ATTR_KEY);
2317 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2318 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2319 if (multiple != null) {
2320 values.clear();
2321 int count = Integer.parseInt(multiple);
2322 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2323 if (type == XmlPullParser.START_TAG
2324 && parser.getName().equals(TAG_VALUE)) {
2325 values.add(parser.nextText().trim());
2326 count--;
2327 }
2328 }
2329 String [] valueStrings = new String[values.size()];
2330 values.toArray(valueStrings);
2331 restrictions.putStringArray(key, valueStrings);
2332 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2333 restrictions.putBundle(key, readBundleEntry(parser, values));
2334 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2335 final int outerDepth = parser.getDepth();
2336 ArrayList<Bundle> bundleList = new ArrayList<>();
2337 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2338 Bundle childBundle = readBundleEntry(parser, values);
2339 bundleList.add(childBundle);
2340 }
2341 restrictions.putParcelableArray(key,
2342 bundleList.toArray(new Bundle[bundleList.size()]));
2343 } else {
2344 String value = parser.nextText().trim();
2345 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2346 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2347 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2348 restrictions.putInt(key, Integer.parseInt(value));
2349 } else {
2350 restrictions.putString(key, value);
2351 }
2352 }
2353 }
2354 }
2355
2356 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2357 throws IOException, XmlPullParserException {
2358 Bundle childBundle = new Bundle();
2359 final int outerDepth = parser.getDepth();
2360 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2361 readEntry(childBundle, values, parser);
2362 }
2363 return childBundle;
2364 }
2365
Fyodor Kupolov82402752015-10-28 14:54:51 -07002366 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002367 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002368 AtomicFile restrictionsFile = new AtomicFile(
2369 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002370 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002371 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002372 }
2373
2374 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002375 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002376 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002377 try {
2378 fos = restrictionsFile.startWrite();
2379 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2380
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002381 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002382 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002383 serializer.startDocument(null, true);
2384 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2385
2386 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002387 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002388 serializer.endTag(null, TAG_RESTRICTIONS);
2389
2390 serializer.endDocument();
2391 restrictionsFile.finishWrite(fos);
2392 } catch (Exception e) {
2393 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002394 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2395 }
2396 }
2397
2398 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2399 throws IOException {
2400 for (String key : restrictions.keySet()) {
2401 Object value = restrictions.get(key);
2402 serializer.startTag(null, TAG_ENTRY);
2403 serializer.attribute(null, ATTR_KEY, key);
2404
2405 if (value instanceof Boolean) {
2406 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2407 serializer.text(value.toString());
2408 } else if (value instanceof Integer) {
2409 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2410 serializer.text(value.toString());
2411 } else if (value == null || value instanceof String) {
2412 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2413 serializer.text(value != null ? (String) value : "");
2414 } else if (value instanceof Bundle) {
2415 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2416 writeBundle((Bundle) value, serializer);
2417 } else if (value instanceof Parcelable[]) {
2418 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2419 Parcelable[] array = (Parcelable[]) value;
2420 for (Parcelable parcelable : array) {
2421 if (!(parcelable instanceof Bundle)) {
2422 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2423 }
2424 serializer.startTag(null, TAG_ENTRY);
2425 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2426 writeBundle((Bundle) parcelable, serializer);
2427 serializer.endTag(null, TAG_ENTRY);
2428 }
2429 } else {
2430 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2431 String[] values = (String[]) value;
2432 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2433 for (String choice : values) {
2434 serializer.startTag(null, TAG_VALUE);
2435 serializer.text(choice != null ? choice : "");
2436 serializer.endTag(null, TAG_VALUE);
2437 }
2438 }
2439 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002440 }
2441 }
2442
2443 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002444 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002446 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002447 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002448 }
2449 }
2450
2451 @Override
2452 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002453 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002454 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002455 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002456 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002457 }
2458 // Not found
2459 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002460 }
2461 }
2462
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002463 @Override
2464 public long getUserCreationTime(int userHandle) {
2465 int callingUserId = UserHandle.getCallingUserId();
2466 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002467 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002468 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002469 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002470 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002471 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002472 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002473 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002474 }
2475 }
2476 }
2477 if (userInfo == null) {
2478 throw new SecurityException("userHandle can only be the calling user or a managed "
2479 + "profile associated with this user");
2480 }
2481 return userInfo.creationTime;
2482 }
2483
Amith Yamasani0b285492011-04-14 17:35:23 -07002484 /**
2485 * Caches the list of user ids in an array, adjusting the array size when necessary.
2486 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002487 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002488 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002489 synchronized (mUsersLock) {
2490 final int userSize = mUsers.size();
2491 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002492 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002493 num++;
2494 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002495 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002496 final int[] newUsers = new int[num];
2497 int n = 0;
2498 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002499 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002500 newUsers[n++] = mUsers.keyAt(i);
2501 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002502 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002503 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002504 }
2505 }
2506
2507 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002508 * Prepare storage areas for given user on all mounted devices.
2509 */
2510 private void prepareUserStorage(int userId, int userSerial, int flags) {
2511 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2512 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2513 final String volumeUuid = vol.getFsUuid();
2514 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2515 }
2516 }
2517
2518 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002519 * Called right before a user is started. This gives us a chance to prepare
2520 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002521 */
2522 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002523 final int userSerial = getUserSerialNumber(userId);
2524 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2525 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002526
2527 if (userId != UserHandle.USER_SYSTEM) {
2528 synchronized (mRestrictionsLock) {
2529 applyUserRestrictionsLR(userId);
2530 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002531 }
2532 }
2533
2534 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002535 * Called right before a user is unlocked. This gives us a chance to prepare
2536 * app storage.
2537 */
2538 public void onBeforeUnlockUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002539 final int userSerial = getUserSerialNumber(userId);
2540 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2541 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002542 }
2543
2544 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002545 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002546 * @param userId the user that was just foregrounded
2547 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002548 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002549 UserData userData = getUserDataNoChecks(userId);
2550 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002551 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2552 return;
2553 }
2554 long now = System.currentTimeMillis();
2555 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002556 userData.info.lastLoggedInTime = now;
2557 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002558 }
2559 }
2560
2561 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002562 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002563 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2564 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002565 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002566 private int getNextAvailableId() {
2567 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002568 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002569 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002570 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002571 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002572 }
2573 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002574 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002575 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002576 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002577 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002578
Amith Yamasanifc95e702013-09-26 13:20:17 -07002579 private String packageToRestrictionsFileName(String packageName) {
2580 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2581 }
2582
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002583 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002584 * Enforce that serial number stored in user directory inode matches the
2585 * given expected value. Gracefully sets the serial number if currently
2586 * undefined.
2587 *
2588 * @throws IOException when problem extracting serial number, or serial
2589 * number is mismatched.
2590 */
2591 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2592 final int foundSerial = getSerialNumber(file);
2593 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2594
2595 if (foundSerial == -1) {
2596 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2597 try {
2598 setSerialNumber(file, serialNumber);
2599 } catch (IOException e) {
2600 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2601 }
2602
2603 } else if (foundSerial != serialNumber) {
2604 throw new IOException("Found serial number " + foundSerial
2605 + " doesn't match expected " + serialNumber);
2606 }
2607 }
2608
2609 /**
2610 * Set serial number stored in user directory inode.
2611 *
2612 * @throws IOException if serial number was already set
2613 */
2614 private static void setSerialNumber(File file, int serialNumber)
2615 throws IOException {
2616 try {
2617 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2618 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2619 } catch (ErrnoException e) {
2620 throw e.rethrowAsIOException();
2621 }
2622 }
2623
2624 /**
2625 * Return serial number stored in user directory inode.
2626 *
2627 * @return parsed serial number, or -1 if not set
2628 */
2629 private static int getSerialNumber(File file) throws IOException {
2630 try {
2631 final byte[] buf = new byte[256];
2632 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2633 final String serial = new String(buf, 0, len);
2634 try {
2635 return Integer.parseInt(serial);
2636 } catch (NumberFormatException e) {
2637 throw new IOException("Bad serial number: " + serial);
2638 }
2639 } catch (ErrnoException e) {
2640 if (e.errno == OsConstants.ENODATA) {
2641 return -1;
2642 } else {
2643 throw e.rethrowAsIOException();
2644 }
2645 }
2646 }
2647
Amith Yamasani920ace02012-09-20 22:15:37 -07002648 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002649 public void setSeedAccountData(int userId, String accountName, String accountType,
2650 PersistableBundle accountOptions, boolean persist) {
2651 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2652 synchronized (mPackagesLock) {
2653 final UserData userData;
2654 synchronized (mUsersLock) {
2655 userData = getUserDataLU(userId);
2656 if (userData == null) {
2657 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2658 return;
2659 }
2660 userData.seedAccountName = accountName;
2661 userData.seedAccountType = accountType;
2662 userData.seedAccountOptions = accountOptions;
2663 userData.persistSeedData = persist;
2664 }
2665 if (persist) {
2666 writeUserLP(userData);
2667 }
2668 }
2669 }
2670
2671 @Override
2672 public String getSeedAccountName() throws RemoteException {
2673 checkManageUsersPermission("Cannot get seed account information");
2674 synchronized (mUsersLock) {
2675 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2676 return userData.seedAccountName;
2677 }
2678 }
2679
2680 @Override
2681 public String getSeedAccountType() throws RemoteException {
2682 checkManageUsersPermission("Cannot get seed account information");
2683 synchronized (mUsersLock) {
2684 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2685 return userData.seedAccountType;
2686 }
2687 }
2688
2689 @Override
2690 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2691 checkManageUsersPermission("Cannot get seed account information");
2692 synchronized (mUsersLock) {
2693 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2694 return userData.seedAccountOptions;
2695 }
2696 }
2697
2698 @Override
2699 public void clearSeedAccountData() throws RemoteException {
2700 checkManageUsersPermission("Cannot clear seed account information");
2701 synchronized (mPackagesLock) {
2702 UserData userData;
2703 synchronized (mUsersLock) {
2704 userData = getUserDataLU(UserHandle.getCallingUserId());
2705 if (userData == null) return;
2706 userData.clearSeedAccountData();
2707 }
2708 writeUserLP(userData);
2709 }
2710 }
2711
2712 @Override
2713 public boolean someUserHasSeedAccount(String accountName, String accountType)
2714 throws RemoteException {
2715 checkManageUsersPermission("Cannot check seed account information");
2716 synchronized (mUsersLock) {
2717 final int userSize = mUsers.size();
2718 for (int i = 0; i < userSize; i++) {
2719 final UserData data = mUsers.valueAt(i);
2720 if (data.info.isInitialized()) continue;
2721 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2722 continue;
2723 }
2724 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2725 continue;
2726 }
2727 return true;
2728 }
2729 }
2730 return false;
2731 }
2732
2733 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002734 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2735 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2736 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2737 }
2738
2739 int onShellCommand(Shell shell, String cmd) {
2740 if (cmd == null) {
2741 return shell.handleDefaultCommands(cmd);
2742 }
2743
2744 final PrintWriter pw = shell.getOutPrintWriter();
2745 try {
2746 switch(cmd) {
2747 case "list":
2748 return runList(pw);
2749 }
2750 } catch (RemoteException e) {
2751 pw.println("Remote exception: " + e);
2752 }
2753 return -1;
2754 }
2755
2756 private int runList(PrintWriter pw) throws RemoteException {
2757 final IActivityManager am = ActivityManagerNative.getDefault();
2758 final List<UserInfo> users = getUsers(false);
2759 if (users == null) {
2760 pw.println("Error: couldn't get users");
2761 return 1;
2762 } else {
2763 pw.println("Users:");
2764 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002765 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002766 pw.println("\t" + users.get(i).toString() + running);
2767 }
2768 return 0;
2769 }
2770 }
2771
2772 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002773 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2774 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2775 != PackageManager.PERMISSION_GRANTED) {
2776 pw.println("Permission Denial: can't dump UserManager from from pid="
2777 + Binder.getCallingPid()
2778 + ", uid=" + Binder.getCallingUid()
2779 + " without permission "
2780 + android.Manifest.permission.DUMP);
2781 return;
2782 }
2783
2784 long now = System.currentTimeMillis();
2785 StringBuilder sb = new StringBuilder();
2786 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 synchronized (mUsersLock) {
2788 pw.println("Users:");
2789 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002790 UserData userData = mUsers.valueAt(i);
2791 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002792 continue;
2793 }
Amith Yamasani12747872015-12-07 14:19:49 -08002794 UserInfo userInfo = userData.info;
2795 final int userId = userInfo.id;
2796 pw.print(" "); pw.print(userInfo);
2797 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002798 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002799 pw.print(" <removing> ");
2800 }
Amith Yamasani12747872015-12-07 14:19:49 -08002801 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002802 pw.print(" <partial>");
2803 }
2804 pw.println();
2805 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002806 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002807 pw.println("<unknown>");
2808 } else {
2809 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002810 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 sb.append(" ago");
2812 pw.println(sb);
2813 }
2814 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002815 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002816 pw.println("<unknown>");
2817 } else {
2818 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002819 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002820 sb.append(" ago");
2821 pw.println(sb);
2822 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002823 pw.print(" Has profile owner: ");
2824 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002825 pw.println(" Restrictions:");
2826 synchronized (mRestrictionsLock) {
2827 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002828 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002829 pw.println(" Device policy local restrictions:");
2830 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002831 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002832 pw.println(" Effective restrictions:");
2833 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002834 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002835 }
Amith Yamasani12747872015-12-07 14:19:49 -08002836
2837 if (userData.account != null) {
2838 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002839 pw.println();
2840 }
Amith Yamasani12747872015-12-07 14:19:49 -08002841
2842 if (userData.seedAccountName != null) {
2843 pw.print(" Seed account name: " + userData.seedAccountName);
2844 pw.println();
2845 if (userData.seedAccountType != null) {
2846 pw.print(" account type: " + userData.seedAccountType);
2847 pw.println();
2848 }
2849 if (userData.seedAccountOptions != null) {
2850 pw.print(" account options exist");
2851 pw.println();
2852 }
2853 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002854 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002855 }
Amith Yamasani12747872015-12-07 14:19:49 -08002856 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002857 pw.println(" Device policy global restrictions:");
2858 synchronized (mRestrictionsLock) {
2859 UserRestrictionsUtils
2860 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2861 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002862 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002863 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002864 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002865 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002866 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002867 synchronized (mUsersLock) {
2868 pw.println();
2869 pw.println(" Device managed: " + mIsDeviceManaged);
2870 }
Amith Yamasani12747872015-12-07 14:19:49 -08002871 // Dump some capabilities
2872 pw.println();
2873 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2874 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002875 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2876 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002877 }
2878 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002879
2880 final class MainHandler extends Handler {
2881
2882 @Override
2883 public void handleMessage(Message msg) {
2884 switch (msg.what) {
2885 case WRITE_USER_MSG:
2886 removeMessages(WRITE_USER_MSG, msg.obj);
2887 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002888 int userId = ((UserData) msg.obj).info.id;
2889 UserData userData = getUserDataNoChecks(userId);
2890 if (userData != null) {
2891 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002892 }
2893 }
2894 }
2895 }
2896 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002897
2898 /**
2899 * @param userId
2900 * @return whether the user has been initialized yet
2901 */
2902 boolean isInitialized(int userId) {
2903 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2904 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002905
2906 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002907 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002908 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2909 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002910 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002911 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002912 }
2913
2914 @Override
2915 public Bundle getBaseUserRestrictions(int userId) {
2916 synchronized (mRestrictionsLock) {
2917 return mBaseUserRestrictions.get(userId);
2918 }
2919 }
2920
2921 @Override
2922 public void setBaseUserRestrictionsByDpmsForMigration(
2923 int userId, Bundle baseRestrictions) {
2924 synchronized (mRestrictionsLock) {
2925 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002926 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002927 }
2928
Amith Yamasani12747872015-12-07 14:19:49 -08002929 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002930 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002931 if (userData != null) {
2932 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002933 } else {
2934 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2935 }
2936 }
2937 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002938
2939 @Override
2940 public boolean getUserRestriction(int userId, String key) {
2941 return getUserRestrictions(userId).getBoolean(key);
2942 }
2943
2944 @Override
2945 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2946 synchronized (mUserRestrictionsListeners) {
2947 mUserRestrictionsListeners.add(listener);
2948 }
2949 }
2950
2951 @Override
2952 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2953 synchronized (mUserRestrictionsListeners) {
2954 mUserRestrictionsListeners.remove(listener);
2955 }
2956 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002957
2958 @Override
2959 public void setDeviceManaged(boolean isManaged) {
2960 synchronized (mUsersLock) {
2961 mIsDeviceManaged = isManaged;
2962 }
2963 }
2964
2965 @Override
2966 public void setUserManaged(int userId, boolean isManaged) {
2967 synchronized (mUsersLock) {
2968 mIsUserManaged.put(userId, isManaged);
2969 }
2970 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002971
2972 @Override
2973 public void setUserIcon(int userId, Bitmap bitmap) {
2974 long ident = Binder.clearCallingIdentity();
2975 try {
2976 synchronized (mPackagesLock) {
2977 UserData userData = getUserDataNoChecks(userId);
2978 if (userData == null || userData.info.partial) {
2979 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2980 return;
2981 }
2982 writeBitmapLP(userData.info, bitmap);
2983 writeUserLP(userData);
2984 }
2985 sendUserInfoChangedBroadcast(userId);
2986 } finally {
2987 Binder.restoreCallingIdentity(ident);
2988 }
2989 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002990
2991 @Override
2992 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2993 synchronized (mUsersLock) {
2994 mForceEphemeralUsers = forceEphemeralUsers;
2995 }
2996 }
2997
2998 @Override
2999 public void removeAllUsers() {
3000 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3001 // Remove the non-system users straight away.
3002 removeNonSystemUsers();
3003 } else {
3004 // Switch to the system user first and then remove the other users.
3005 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3006 @Override
3007 public void onReceive(Context context, Intent intent) {
3008 int userId =
3009 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3010 if (userId != UserHandle.USER_SYSTEM) {
3011 return;
3012 }
3013 mContext.unregisterReceiver(this);
3014 removeNonSystemUsers();
3015 }
3016 };
3017 IntentFilter userSwitchedFilter = new IntentFilter();
3018 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3019 mContext.registerReceiver(
3020 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3021
3022 // Switch to the system user.
3023 ActivityManager am =
3024 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3025 am.switchUser(UserHandle.USER_SYSTEM);
3026 }
3027 }
phweisse9c44062016-02-10 12:57:38 +01003028
3029 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003030 public void onEphemeralUserStop(int userId) {
3031 synchronized (mUsersLock) {
3032 UserInfo userInfo = getUserInfoLU(userId);
3033 if (userInfo != null && userInfo.isEphemeral()) {
3034 // Do not allow switching back to the ephemeral user again as the user is going
3035 // to be deleted.
3036 userInfo.flags |= UserInfo.FLAG_DISABLED;
3037 if (userInfo.isGuest()) {
3038 // Indicate that the guest will be deleted after it stops.
3039 userInfo.guestToRemove = true;
3040 }
3041 }
3042 }
3043 }
3044
3045 @Override
phweisse9c44062016-02-10 12:57:38 +01003046 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3047 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3048 // Keep this in sync with UserManager.createUser
3049 if (user != null && !user.isAdmin()) {
3050 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3051 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3052 }
3053 return user;
3054 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003055 }
3056
3057 /* Remove all the users except of the system one. */
3058 private void removeNonSystemUsers() {
3059 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3060 synchronized (mUsersLock) {
3061 final int userSize = mUsers.size();
3062 for (int i = 0; i < userSize; i++) {
3063 UserInfo ui = mUsers.valueAt(i).info;
3064 if (ui.id != UserHandle.USER_SYSTEM) {
3065 usersToRemove.add(ui);
3066 }
3067 }
3068 }
3069 for (UserInfo ui: usersToRemove) {
3070 removeUser(ui.id);
3071 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003072 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003073
3074 private class Shell extends ShellCommand {
3075 @Override
3076 public int onCommand(String cmd) {
3077 return onShellCommand(this, cmd);
3078 }
3079
3080 @Override
3081 public void onHelp() {
3082 final PrintWriter pw = getOutPrintWriter();
3083 pw.println("User manager (user) commands:");
3084 pw.println(" help");
3085 pw.println(" Print this help text.");
3086 pw.println("");
3087 pw.println(" list");
3088 pw.println(" Prints all users on the system.");
3089 }
3090 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003091
3092 private static void debug(String message) {
3093 Log.d(LOG_TAG, message +
3094 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3095 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003096}