blob: 637feaac3e6cb84f09c4b6ab3b8394cb2311d562 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010035import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080039import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070040import android.os.Environment;
41import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080042import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080044import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010045import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070046import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080047import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070048import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070049import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040051import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070053import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070054import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070055import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080056import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010057import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070058import android.os.storage.VolumeInfo;
59import android.system.ErrnoException;
60import android.system.Os;
61import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070062import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070063import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import android.util.Slog;
65import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070067import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import android.util.Xml;
69
Makoto Onuki068c54a2015-10-13 14:34:03 -070070import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070071import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040072import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080073import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080074import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070075import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070076import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000077import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070078import com.android.server.LocalServices;
Jeff Sharkey0e62384c2016-01-13 18:52:55 -070079import com.android.server.pm.Installer.StorageFlags;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080
81import org.xmlpull.v1.XmlPullParser;
82import org.xmlpull.v1.XmlPullParserException;
83import org.xmlpull.v1.XmlSerializer;
84
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.BufferedOutputStream;
86import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.io.FileOutputStream;
91import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070092import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010093import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094import java.util.ArrayList;
95import java.util.List;
96
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080098import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070099
Makoto Onuki068c54a2015-10-13 14:34:03 -0700100/**
101 * Service for {@link UserManager}.
102 *
103 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700104 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800105 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
107 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
108 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700109 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700110public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700111 private static final String LOG_TAG = "UserManagerService";
Amith Yamasani12747872015-12-07 14:19:49 -0800112 static final boolean DBG = true; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800113 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700114
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800116 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700118 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700120 private static final String ATTR_CREATION_TIME = "created";
121 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700122 private static final String ATTR_SERIAL_NO = "serialNumber";
123 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700124 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700125 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700126 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100127 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700128 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800129 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
130 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530131 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800134 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800136 private static final String TAG_ENTRY = "entry";
137 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800138 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800139 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700140 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700143 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
144 private static final String ATTR_TYPE_STRING = "s";
145 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700146 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700147 private static final String ATTR_TYPE_BUNDLE = "B";
148 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700149
Amith Yamasani0b285492011-04-14 17:35:23 -0700150 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700152 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100153 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800155 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700156 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157
Amith Yamasani634cf312012-10-04 17:34:21 -0700158 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700159 // We need to keep process uid within Integer.MAX_VALUE.
160 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700161
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700162 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163
Amith Yamasani920ace02012-09-20 22:15:37 -0700164 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
165
Nicolas Prevotb8186812015-08-06 15:00:03 +0100166 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700167 // without first making sure that the rest of the framework is prepared for it.
168 private static final int MAX_MANAGED_PROFILES = 1;
169
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800170 static final int WRITE_USER_MSG = 1;
171 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530172
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700173 private static final String XATTR_SERIAL = "user.serial";
174
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800175 // Tron counters
176 private static final String TRON_GUEST_CREATED = "users_guest_created";
177 private static final String TRON_USER_CREATED = "users_user_created";
178
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 private final Context mContext;
180 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700182 // Short-term lock for internal state, when interaction/sync with PM is not required
183 private final Object mUsersLock = new Object();
184 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800186 private final Handler mHandler;
187
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private final File mUsersDir;
189 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800192 * User-related information that is used for persisting to flash. Only UserInfo is
193 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800194 */
Amith Yamasani12747872015-12-07 14:19:49 -0800195 private static class UserData {
196 // Basic user information and properties
197 UserInfo info;
198 // Account name used when there is a strong association between a user and an account
199 String account;
200 // Account information for seeding into a newly created user. This could also be
201 // used for login validation for an existing user, for updating their credentials.
202 // In the latter case, data may not need to be persisted as it is only valid for the
203 // current login session.
204 String seedAccountName;
205 String seedAccountType;
206 PersistableBundle seedAccountOptions;
207 // Whether to perist the seed account information to be available after a boot
208 boolean persistSeedData;
209
210 void clearSeedAccountData() {
211 seedAccountName = null;
212 seedAccountType = null;
213 seedAccountOptions = null;
214 persistSeedData = false;
215 }
216 }
217
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800218 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800219 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800220
221 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700222 * User restrictions set via UserManager. This doesn't include restrictions set by
223 * device owner / profile owners.
224 *
225 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
226 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
227 * maybe shared between {@link #mBaseUserRestrictions} and
228 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
229 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700231 */
232 @GuardedBy("mRestrictionsLock")
233 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
234
235 /**
236 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
237 * with device / profile owner restrictions. We'll initialize it lazily; use
238 * {@link #getEffectiveUserRestrictions} to access it.
239 *
240 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
241 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
242 * maybe shared between {@link #mBaseUserRestrictions} and
243 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
244 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700245 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 */
247 @GuardedBy("mRestrictionsLock")
248 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
249
Makoto Onuki4f160732015-10-27 17:15:38 -0700250 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800251 * User restrictions that have already been applied in
252 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
253 * that have changed since the last
254 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700255 */
256 @GuardedBy("mRestrictionsLock")
257 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
258
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800259 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800260 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
261 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800262 */
263 @GuardedBy("mRestrictionsLock")
264 private Bundle mDevicePolicyGlobalUserRestrictions;
265
266 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800267 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
268 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800269 */
270 @GuardedBy("mRestrictionsLock")
271 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
272
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800273 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530274 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800275
276 /**
277 * Set of user IDs being actively removed. Removed IDs linger in this set
278 * for several seconds to work around a VFS caching issue.
279 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700280 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800281 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700282
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700284 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800285 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700286 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700287 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700288
Jason Monk62062992014-05-06 09:55:28 -0400289 private IAppOpsService mAppOpsService;
290
Makoto Onuki068c54a2015-10-13 14:34:03 -0700291 private final LocalService mLocalService;
292
Makoto Onukie7927da2015-11-25 10:05:17 -0800293 @GuardedBy("mUsersLock")
294 private boolean mIsDeviceManaged;
295
296 @GuardedBy("mUsersLock")
297 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
298
Makoto Onukid45a4a22015-11-02 17:17:38 -0800299 @GuardedBy("mUserRestrictionsListeners")
300 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
301 new ArrayList<>();
302
Clara Bayarria1771112015-12-18 16:29:18 +0000303 private final LockPatternUtils mLockPatternUtils;
304
Amith Yamasani258848d2012-08-10 17:06:33 -0700305 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700306
Dianne Hackborn4428e172012-08-24 17:43:05 -0700307 public static UserManagerService getInstance() {
308 synchronized (UserManagerService.class) {
309 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700311 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700312
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800313 @VisibleForTesting
314 UserManagerService(File dataDir) {
315 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700316 }
317
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 /**
319 * Called by package manager to create the service. This is closely
320 * associated with the package manager, and the given lock is the
321 * package manager's own lock.
322 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800323 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
324 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700325 }
326
Dianne Hackborn4428e172012-08-24 17:43:05 -0700327 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800328 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700329 mContext = context;
330 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700331 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800332 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 synchronized (mPackagesLock) {
334 mUsersDir = new File(dataDir, USER_INFO_DIR);
335 mUsersDir.mkdirs();
336 // Make zeroth user directory, for services to migrate their files to that location
337 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
338 userZeroDir.mkdirs();
339 FileUtils.setPermissions(mUsersDir.toString(),
340 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
341 -1, -1);
342 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
343 initDefaultGuestRestrictions();
344 readUserListLP();
345 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700346 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700347 mLocalService = new LocalService();
348 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000349 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700350 }
351
352 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100353 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800354 ArrayList<UserInfo> partials = new ArrayList<>();
355 synchronized (mUsersLock) {
356 final int userSize = mUsers.size();
357 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800358 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100359 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700363 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 final int partialsSize = partials.size();
365 for (int i = 0; i < partialsSize; i++) {
366 UserInfo ui = partials.get(i);
367 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
368 + " (name=" + ui.name + ")");
369 removeUserState(ui.id);
370 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800371
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700372 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800373
Jason Monk62062992014-05-06 09:55:28 -0400374 mAppOpsService = IAppOpsService.Stub.asInterface(
375 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800376
377 synchronized (mRestrictionsLock) {
378 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400379 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700380 }
381
382 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800383 public String getUserAccount(int userId) {
384 checkManageUserAndAcrossUsersFullPermission("get user account");
385 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800386 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800387 }
388 }
389
390 @Override
391 public void setUserAccount(int userId, String accountName) {
392 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800393 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800394 synchronized (mPackagesLock) {
395 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800396 final UserData userData = mUsers.get(userId);
397 if (userData == null) {
398 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
399 return;
400 }
401 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800402 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800403 userData.account = accountName;
404 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800405 }
406 }
407
408 if (userToUpdate != null) {
409 writeUserLP(userToUpdate);
410 }
411 }
412 }
413
414 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700415 public UserInfo getPrimaryUser() {
416 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700417 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700418 final int userSize = mUsers.size();
419 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800420 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800421 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700422 return ui;
423 }
424 }
425 }
426 return null;
427 }
428
429 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700430 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700431 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700432 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700433 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700434 final int userSize = mUsers.size();
435 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800436 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 if (ui.partial) {
438 continue;
439 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800440 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700442 }
Amith Yamasani13593602012-03-22 16:16:17 -0700443 }
444 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700445 }
Amith Yamasani13593602012-03-22 16:16:17 -0700446 }
447
Amith Yamasani258848d2012-08-10 17:06:33 -0700448 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100449 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800450 if (userId != UserHandle.getCallingUserId()) {
451 checkManageUsersPermission("getting profiles related to user " + userId);
452 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700453 final long ident = Binder.clearCallingIdentity();
454 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700455 synchronized (mUsersLock) {
456 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100457 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700458 } finally {
459 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000460 }
461 }
462
Amith Yamasanibe465322014-04-24 13:45:17 -0700463 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700464 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
465 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700466 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700467 if (user == null) {
468 // Probably a dying user
469 return users;
470 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700471 final int userSize = mUsers.size();
472 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800473 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700474 if (!isProfileOf(user, profile)) {
475 continue;
476 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100477 if (enabledOnly && !profile.isEnabled()) {
478 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700479 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700480 if (mRemovingUserIds.get(profile.id)) {
481 continue;
482 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700483 users.add(profile);
484 }
485 return users;
486 }
487
Jessica Hummelbe81c802014-04-22 15:49:22 +0100488 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700489 public int getCredentialOwnerProfile(int userHandle) {
490 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000491 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700492 synchronized (mUsersLock) {
493 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700494 if (profileParent != null) {
495 return profileParent.id;
496 }
497 }
498 }
499
500 return userHandle;
501 }
502
503 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700504 public boolean isSameProfileGroup(int userId, int otherUserId) {
505 if (userId == otherUserId) return true;
506 checkManageUsersPermission("check if in the same profile group");
507 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700508 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700509 }
510 }
511
Fyodor Kupolov82402752015-10-28 14:54:51 -0700512 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
513 synchronized (mUsersLock) {
514 UserInfo userInfo = getUserInfoLU(userId);
515 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
516 return false;
517 }
518 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
519 if (otherUserInfo == null
520 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
521 return false;
522 }
523 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700524 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700525 }
526
527 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100528 public UserInfo getProfileParent(int userHandle) {
529 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700530 synchronized (mUsersLock) {
531 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700532 }
533 }
534
Fyodor Kupolov82402752015-10-28 14:54:51 -0700535 private UserInfo getProfileParentLU(int userHandle) {
536 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700537 if (profile == null) {
538 return null;
539 }
540 int parentUserId = profile.profileGroupId;
541 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
542 return null;
543 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700544 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100545 }
546 }
547
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100549 return user.id == profile.id ||
550 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
551 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000552 }
553
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000554 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000555 UserHandle parentHandle, boolean inQuietMode) {
556 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
557 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
558 intent.putExtra(Intent.EXTRA_USER, profileHandle);
559 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000560 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000561 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000562 }
563
564 @Override
565 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
566 checkManageUsersPermission("silence profile");
567 boolean changed = false;
568 UserInfo profile, parent;
569 synchronized (mPackagesLock) {
570 synchronized (mUsersLock) {
571 profile = getUserInfoLU(userHandle);
572 parent = getProfileParentLU(userHandle);
573
574 }
575 if (profile == null || !profile.isManagedProfile()) {
576 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
577 }
578 if (profile.isQuietModeEnabled() != enableQuietMode) {
579 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800580 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000581 changed = true;
582 }
583 }
584 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000585 long identity = Binder.clearCallingIdentity();
586 try {
587 if (enableQuietMode) {
588 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
589 } else {
590 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
591 }
592 } catch (RemoteException e) {
593 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
594 } finally {
595 Binder.restoreCallingIdentity(identity);
596 }
597
598 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
599 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000600 }
601 }
602
603 @Override
604 public boolean isQuietModeEnabled(int userHandle) {
605 synchronized (mPackagesLock) {
606 UserInfo info;
607 synchronized (mUsersLock) {
608 info = getUserInfoLU(userHandle);
609 }
610 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000611 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000612 }
613 return info.isQuietModeEnabled();
614 }
615 }
616
Kenny Guya52dc3e2014-02-11 15:33:14 +0000617 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100618 public void setUserEnabled(int userId) {
619 checkManageUsersPermission("enable user");
620 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700621 UserInfo info;
622 synchronized (mUsersLock) {
623 info = getUserInfoLU(userId);
624 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100625 if (info != null && !info.isEnabled()) {
626 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800627 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100628 }
629 }
630 }
631
632 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700633 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700634 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700635 synchronized (mUsersLock) {
636 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700637 }
638 }
639
Amith Yamasani71e6c692013-03-24 17:39:28 -0700640 @Override
641 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700642 synchronized (mUsersLock) {
643 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700644 }
645 }
646
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700647 @Override
648 public boolean canHaveRestrictedProfile(int userId) {
649 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700650 synchronized (mUsersLock) {
651 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700652 if (userInfo == null || !userInfo.canHaveProfile()) {
653 return false;
654 }
655 if (!userInfo.isAdmin()) {
656 return false;
657 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800658 // restricted profile can be created if there is no DO set and the admin user has no PO;
659 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700660 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700661 }
662
Amith Yamasani195263742012-08-21 15:40:12 -0700663 /*
664 * Should be locked on mUsers before calling this.
665 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800667 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700668 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800669 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700670 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
671 return null;
672 }
Amith Yamasani12747872015-12-07 14:19:49 -0800673 return userData != null ? userData.info : null;
674 }
675
676 private UserData getUserDataLU(int userId) {
677 final UserData userData = mUsers.get(userId);
678 // If it is partial and not in the process of being removed, return as unknown user.
679 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
680 return null;
681 }
682 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700683 }
684
Fyodor Kupolov82402752015-10-28 14:54:51 -0700685 /**
686 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
687 * <p>No permissions checking or any addition checks are made</p>
688 */
689 private UserInfo getUserInfoNoChecks(int userId) {
690 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800691 final UserData userData = mUsers.get(userId);
692 return userData != null ? userData.info : null;
693 }
694 }
695
696 /**
697 * Obtains {@link #mUsersLock} and return UserData from mUsers.
698 * <p>No permissions checking or any addition checks are made</p>
699 */
700 private UserData getUserDataNoChecks(int userId) {
701 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 return mUsers.get(userId);
703 }
704 }
705
Amith Yamasani236b2b52015-08-18 14:32:14 -0700706 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700707 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700708 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700709 }
710
Amith Yamasani258848d2012-08-10 17:06:33 -0700711 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700712 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700713 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700714 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700715 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800716 UserData userData = getUserDataNoChecks(userId);
717 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700718 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
719 return;
720 }
Amith Yamasani12747872015-12-07 14:19:49 -0800721 if (name != null && !name.equals(userData.info.name)) {
722 userData.info.name = name;
723 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700724 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700725 }
726 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700727 if (changed) {
728 sendUserInfoChangedBroadcast(userId);
729 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 }
731
Amith Yamasani258848d2012-08-10 17:06:33 -0700732 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700733 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700734 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100735 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
736 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
737 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700738 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100739 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700740 }
741
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100742
743
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700744 private void sendUserInfoChangedBroadcast(int userId) {
745 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
746 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
747 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700748 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700749 }
750
Amith Yamasani258848d2012-08-10 17:06:33 -0700751 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100752 public ParcelFileDescriptor getUserIcon(int userId) {
753 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700754 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700755 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700756 if (info == null || info.partial) {
757 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
758 return null;
759 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700760 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100761 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
762 || callingGroupId != info.profileGroupId) {
763 checkManageUsersPermission("get the icon of a user who is not related");
764 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700765 if (info.iconPath == null) {
766 return null;
767 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100768 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700769 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100770
771 try {
772 return ParcelFileDescriptor.open(
773 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
774 } catch (FileNotFoundException e) {
775 Log.e(LOG_TAG, "Couldn't find icon file", e);
776 }
777 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700778 }
779
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700780 public void makeInitialized(int userId) {
781 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800782 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800783 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800784 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800785 userData = mUsers.get(userId);
786 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700787 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800788 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700789 }
Amith Yamasani12747872015-12-07 14:19:49 -0800790 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
791 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800792 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700793 }
794 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800795 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800796 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800797 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700798 }
799
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700800 /**
801 * If default guest restrictions haven't been initialized yet, add the basic
802 * restrictions.
803 */
804 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800805 synchronized (mGuestRestrictions) {
806 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800807 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800808 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
809 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
810 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700811 }
812 }
813
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800814 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530815 public Bundle getDefaultGuestRestrictions() {
816 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800817 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530818 return new Bundle(mGuestRestrictions);
819 }
820 }
821
822 @Override
823 public void setDefaultGuestRestrictions(Bundle restrictions) {
824 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800825 synchronized (mGuestRestrictions) {
826 mGuestRestrictions.clear();
827 mGuestRestrictions.putAll(restrictions);
828 }
829 synchronized (mPackagesLock) {
830 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530831 }
832 }
833
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800834 /**
835 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
836 */
837 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
838 @Nullable Bundle global) {
839 Preconditions.checkNotNull(local);
840 boolean globalChanged = false;
841 boolean localChanged;
842 synchronized (mRestrictionsLock) {
843 if (global != null) {
844 // Update global.
845 globalChanged = !UserRestrictionsUtils.areEqual(
846 mDevicePolicyGlobalUserRestrictions, global);
847 if (globalChanged) {
848 mDevicePolicyGlobalUserRestrictions = global;
849 }
850 }
851 {
852 // Update local.
853 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
854 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
855 if (localChanged) {
856 mDevicePolicyLocalUserRestrictions.put(userId, local);
857 }
858 }
859 }
860 if (DBG) {
861 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
862 + " global=" + global + (globalChanged ? " (changed)" : "")
863 + " local=" + local + (localChanged ? " (changed)" : "")
864 );
865 }
866 // Don't call them within the mRestrictionsLock.
867 synchronized (mPackagesLock) {
868 if (globalChanged) {
869 writeUserListLP();
870 }
871 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800872 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800873 }
874 }
875
876 synchronized (mRestrictionsLock) {
877 if (globalChanged) {
878 applyUserRestrictionsForAllUsersLR();
879 } else if (localChanged) {
880 applyUserRestrictionsLR(userId);
881 }
882 }
883 }
884
Makoto Onuki068c54a2015-10-13 14:34:03 -0700885 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700886 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800887 final Bundle baseRestrictions =
888 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
889 final Bundle global = mDevicePolicyGlobalUserRestrictions;
890 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700891
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800892 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
893 // Common case first.
894 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700895 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800896 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
897 UserRestrictionsUtils.merge(effective, global);
898 UserRestrictionsUtils.merge(effective, local);
899
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 return effective;
901 }
902
903 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700904 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700905 if (DBG) {
906 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
907 }
908 mCachedEffectiveUserRestrictions.remove(userId);
909 }
910
911 private Bundle getEffectiveUserRestrictions(int userId) {
912 synchronized (mRestrictionsLock) {
913 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
914 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700915 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700916 mCachedEffectiveUserRestrictions.put(userId, restrictions);
917 }
918 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700919 }
920 }
921
Makoto Onuki068c54a2015-10-13 14:34:03 -0700922 /** @return a specific user restriction that's in effect currently. */
923 @Override
924 public boolean hasUserRestriction(String restrictionKey, int userId) {
925 Bundle restrictions = getEffectiveUserRestrictions(userId);
926 return restrictions != null && restrictions.getBoolean(restrictionKey);
927 }
928
929 /**
930 * @return UserRestrictions that are in effect currently. This always returns a new
931 * {@link Bundle}.
932 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700933 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800934 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800935 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800936 }
937
938 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000939 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
940 checkManageUsersPermission("hasBaseUserRestriction");
941 synchronized (mRestrictionsLock) {
942 Bundle bundle = mBaseUserRestrictions.get(userId);
943 return (bundle != null && bundle.getBoolean(restrictionKey, false));
944 }
945 }
946
947 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700948 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700949 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700950 synchronized (mRestrictionsLock) {
951 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
952 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800953 final Bundle newRestrictions = UserRestrictionsUtils.clone(
954 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700955 newRestrictions.putBoolean(key, value);
956
Fyodor Kupolov82402752015-10-28 14:54:51 -0700957 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700958 }
959 }
960
Makoto Onuki068c54a2015-10-13 14:34:03 -0700961 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800962 * Optionally updating user restrictions, calculate the effective user restrictions and also
963 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700964 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800965 * @param newRestrictions User restrictions to set.
966 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700967 * @param userId target user ID.
968 */
969 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700970 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700971 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800972
973 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
974 mAppliedUserRestrictions.get(userId));
975
976 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700977 if (newRestrictions != null) {
978 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800979 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
980
981 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700982 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
983 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800984
985 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
986 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800987 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800988 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700989 }
990
Fyodor Kupolov82402752015-10-28 14:54:51 -0700991 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700992
Makoto Onuki759a7632015-10-28 16:43:10 -0700993 mCachedEffectiveUserRestrictions.put(userId, effective);
994
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800995 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700996 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800997 debug("Applying user restrictions: userId=" + userId
998 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700999 }
1000
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001001 if (mAppOpsService != null) { // We skip it until system-ready.
1002 final long token = Binder.clearCallingIdentity();
1003 try {
1004 mAppOpsService.setUserRestrictions(effective, userId);
1005 } catch (RemoteException e) {
1006 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1007 } finally {
1008 Binder.restoreCallingIdentity(token);
1009 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001010 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001011
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001013
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001014 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001015 }
1016
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001017 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001018 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001019 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1020 // actually, but we still need some kind of synchronization otherwise we might end up
1021 // calling listeners out-of-order, thus "LR".
1022
1023 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1024 return;
1025 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001026
1027 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1028 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1029
1030 mHandler.post(new Runnable() {
1031 @Override
1032 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001033 UserRestrictionsUtils.applyUserRestrictions(
1034 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001035
Makoto Onukid45a4a22015-11-02 17:17:38 -08001036 final UserRestrictionsListener[] listeners;
1037 synchronized (mUserRestrictionsListeners) {
1038 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1039 mUserRestrictionsListeners.toArray(listeners);
1040 }
1041 for (int i = 0; i < listeners.length; i++) {
1042 listeners[i].onUserRestrictionsChanged(userId,
1043 newRestrictionsFinal, prevRestrictionsFinal);
1044 }
1045 }
1046 });
1047 }
1048
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001049 // Package private for the inner class.
1050 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001051 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001052 }
1053
1054 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001055 // Package private for the inner class.
1056 void applyUserRestrictionsForAllUsersLR() {
1057 if (DBG) {
1058 debug("applyUserRestrictionsForAllUsersLR");
1059 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001061 mCachedEffectiveUserRestrictions.clear();
1062
Makoto Onuki068c54a2015-10-13 14:34:03 -07001063 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1064 // it on a handler.
1065 final Runnable r = new Runnable() {
1066 @Override
1067 public void run() {
1068 // Then get the list of running users.
1069 final int[] runningUsers;
1070 try {
1071 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1072 } catch (RemoteException e) {
1073 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1074 return;
1075 }
1076 // Then re-calculate the effective restrictions and apply, only for running users.
1077 // It's okay if a new user has started after the getRunningUserIds() call,
1078 // because we'll do the same thing (re-calculate the restrictions and apply)
1079 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 synchronized (mRestrictionsLock) {
1081 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001082 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001083 }
1084 }
1085 }
1086 };
1087 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001088 }
1089
Amith Yamasani258848d2012-08-10 17:06:33 -07001090 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001091 * Check if we've hit the limit of how many users can be created.
1092 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001093 private boolean isUserLimitReached() {
1094 int count;
1095 synchronized (mUsersLock) {
1096 count = getAliveUsersExcludingGuestsCountLU();
1097 }
1098 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001099 }
1100
1101 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001102 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001103 checkManageUsersPermission("check if more managed profiles can be added.");
1104 if (ActivityManager.isLowRamDeviceStatic()) {
1105 return false;
1106 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001107 if (!mContext.getPackageManager().hasSystemFeature(
1108 PackageManager.FEATURE_MANAGED_USERS)) {
1109 return false;
1110 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001111 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001112 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1113 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1114 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001115 return false;
1116 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001117 synchronized(mUsersLock) {
1118 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001119 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001120 return false;
1121 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001122 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1123 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001124 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001125 return usersCountAfterRemoving == 1
1126 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001127 }
1128 }
1129
Fyodor Kupolov82402752015-10-28 14:54:51 -07001130 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001131 int aliveUserCount = 0;
1132 final int totalUserCount = mUsers.size();
1133 // Skip over users being removed
1134 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001135 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001136 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001137 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001138 aliveUserCount++;
1139 }
1140 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001141 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001142 }
1143
1144 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001145 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001146 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1147 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1148 * permissions can make certain calls to the UserManager.
1149 *
1150 * @param message used as message if SecurityException is thrown
1151 * @throws SecurityException if the caller does not have enough privilege.
1152 */
1153 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1154 final int uid = Binder.getCallingUid();
1155 if (uid != Process.SYSTEM_UID && uid != 0
1156 && ActivityManager.checkComponentPermission(
1157 Manifest.permission.MANAGE_USERS,
1158 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1159 && ActivityManager.checkComponentPermission(
1160 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1161 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1162 throw new SecurityException(
1163 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1164 + message);
1165 }
1166 }
1167
1168 /**
1169 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001170 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001171 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001172 *
1173 * @param message used as message if SecurityException is thrown
1174 * @throws SecurityException if the caller is not system or root
1175 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001176 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001177 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001178 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001179 && ActivityManager.checkComponentPermission(
1180 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001181 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1182 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1183 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001184 }
1185
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001186 /**
1187 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1188 * UserManager.
1189 *
1190 * @param message used as message if SecurityException is thrown
1191 * @throws SecurityException if the caller is not system or root
1192 */
1193 private static void checkSystemOrRoot(String message) {
1194 final int uid = Binder.getCallingUid();
1195 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1196 throw new SecurityException("Only system may: " + message);
1197 }
1198 }
1199
Fyodor Kupolov82402752015-10-28 14:54:51 -07001200 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001201 try {
1202 File dir = new File(mUsersDir, Integer.toString(info.id));
1203 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001204 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001205 if (!dir.exists()) {
1206 dir.mkdir();
1207 FileUtils.setPermissions(
1208 dir.getPath(),
1209 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1210 -1, -1);
1211 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001212 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001213 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1214 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001215 info.iconPath = file.getAbsolutePath();
1216 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001217 try {
1218 os.close();
1219 } catch (IOException ioe) {
1220 // What the ... !
1221 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001222 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001223 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001224 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001225 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001226 }
1227
Amith Yamasani0b285492011-04-14 17:35:23 -07001228 /**
1229 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1230 * cache it elsewhere.
1231 * @return the array of user ids.
1232 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001233 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001234 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001235 return mUserIds;
1236 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001237 }
1238
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001239 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001240 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001241 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001242 return;
1243 }
1244 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001245 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001246 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001247 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001249 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001250 int type;
1251 while ((type = parser.next()) != XmlPullParser.START_TAG
1252 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001253 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 }
1255
1256 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001257 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001258 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001259 return;
1260 }
1261
Amith Yamasani2a003292012-08-14 18:25:45 -07001262 mNextSerialNumber = -1;
1263 if (parser.getName().equals(TAG_USERS)) {
1264 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1265 if (lastSerialNumber != null) {
1266 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1267 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001268 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1269 if (versionNumber != null) {
1270 mUserVersion = Integer.parseInt(versionNumber);
1271 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001272 }
1273
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001274 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1275
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001276 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301277 if (type == XmlPullParser.START_TAG) {
1278 final String name = parser.getName();
1279 if (name.equals(TAG_USER)) {
1280 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001281
Amith Yamasani12747872015-12-07 14:19:49 -08001282 UserData userData = readUserLP(Integer.parseInt(id));
1283
1284 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001285 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001286 mUsers.put(userData.info.id, userData);
1287 if (mNextSerialNumber < 0
1288 || mNextSerialNumber <= userData.info.id) {
1289 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001290 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301291 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001292 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301293 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001294 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1295 && type != XmlPullParser.END_TAG) {
1296 if (type == XmlPullParser.START_TAG) {
1297 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001298 synchronized (mGuestRestrictions) {
1299 UserRestrictionsUtils
1300 .readRestrictions(parser, mGuestRestrictions);
1301 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001302 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1303 ) {
1304 UserRestrictionsUtils.readRestrictions(parser,
1305 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001306 }
1307 break;
1308 }
1309 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001310 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 }
1312 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 synchronized (mRestrictionsLock) {
1314 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1315 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001316 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001317 upgradeIfNecessaryLP();
1318 } catch (IOException | XmlPullParserException e) {
1319 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001320 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001321 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001322 }
1323 }
1324
Amith Yamasani6f34b412012-10-22 18:19:27 -07001325 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001326 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001327 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001328 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001329 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001330 int userVersion = mUserVersion;
1331 if (userVersion < 1) {
1332 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001333 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1334 if ("Primary".equals(userData.info.name)) {
1335 userData.info.name =
1336 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1337 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001338 }
1339 userVersion = 1;
1340 }
1341
Amith Yamasanibc9625052012-11-15 14:39:18 -08001342 if (userVersion < 2) {
1343 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001344 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1345 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1346 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1347 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001348 }
1349 userVersion = 2;
1350 }
1351
Amith Yamasani350962c2013-08-06 11:18:53 -07001352
Amith Yamasani5e486f52013-08-07 11:06:44 -07001353 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001354 userVersion = 4;
1355 }
1356
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001357 if (userVersion < 5) {
1358 initDefaultGuestRestrictions();
1359 userVersion = 5;
1360 }
1361
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001362 if (userVersion < 6) {
1363 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001364 synchronized (mUsersLock) {
1365 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001366 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001367 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001368 if (!splitSystemUser && userData.info.isRestricted()
1369 && (userData.info.restrictedProfileParentId
1370 == UserInfo.NO_PROFILE_GROUP_ID)) {
1371 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1372 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001373 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001374 }
1375 }
1376 userVersion = 6;
1377 }
1378
Amith Yamasani6f34b412012-10-22 18:19:27 -07001379 if (userVersion < USER_VERSION) {
1380 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1381 + USER_VERSION);
1382 } else {
1383 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001384
1385 if (originalVersion < mUserVersion) {
1386 writeUserListLP();
1387 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001388 }
1389 }
1390
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001391 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001392 int flags = UserInfo.FLAG_INITIALIZED;
1393 // In split system user mode, the admin and primary flags are assigned to the first human
1394 // user.
1395 if (!UserManager.isSplitSystemUser()) {
1396 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1397 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001398 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001399 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001400 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001401 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001402 UserData userData = new UserData();
1403 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001404 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001405 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001406 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001407 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001408 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001409
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001410 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001411 synchronized (mRestrictionsLock) {
1412 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1413 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001414
Fyodor Kupolov82402752015-10-28 14:54:51 -07001415 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001416 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001418 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001419 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001420 }
1421
Amith Yamasani12747872015-12-07 14:19:49 -08001422 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001423 if (DBG) {
1424 debug("scheduleWriteUser");
1425 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001426 // No need to wrap it within a lock -- worst case, we'll just post the same message
1427 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001428 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1429 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001430 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1431 }
1432 }
1433
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001434 /*
1435 * Writes the user file in this format:
1436 *
1437 * <user flags="20039023" id="0">
1438 * <name>Primary</name>
1439 * </user>
1440 */
Amith Yamasani12747872015-12-07 14:19:49 -08001441 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001442 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001443 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001445 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001446 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001447 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001448 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001449 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1450
1451 // XmlSerializer serializer = XmlUtils.serializerInstance();
1452 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001453 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001454 serializer.startDocument(null, true);
1455 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1456
Amith Yamasani12747872015-12-07 14:19:49 -08001457 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001458 serializer.startTag(null, TAG_USER);
1459 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001460 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001461 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001462 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1463 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1464 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001465 if (userInfo.iconPath != null) {
1466 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1467 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001468 if (userInfo.partial) {
1469 serializer.attribute(null, ATTR_PARTIAL, "true");
1470 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001471 if (userInfo.guestToRemove) {
1472 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1473 }
Kenny Guy2a764942014-04-02 13:29:20 +01001474 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1475 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1476 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001477 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001478 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1479 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1480 Integer.toString(userInfo.restrictedProfileParentId));
1481 }
Amith Yamasani12747872015-12-07 14:19:49 -08001482 // Write seed data
1483 if (userData.persistSeedData) {
1484 if (userData.seedAccountName != null) {
1485 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1486 }
1487 if (userData.seedAccountType != null) {
1488 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1489 }
1490 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001491 serializer.startTag(null, TAG_NAME);
1492 serializer.text(userInfo.name);
1493 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001494 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001495 UserRestrictionsUtils.writeRestrictions(serializer,
1496 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1497 UserRestrictionsUtils.writeRestrictions(serializer,
1498 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1499 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001500 }
Amith Yamasani12747872015-12-07 14:19:49 -08001501
1502 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001503 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001504 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001505 serializer.endTag(null, TAG_ACCOUNT);
1506 }
1507
Amith Yamasani12747872015-12-07 14:19:49 -08001508 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1509 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1510 userData.seedAccountOptions.saveToXml(serializer);
1511 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1512 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 serializer.endTag(null, TAG_USER);
1514
1515 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001516 userFile.finishWrite(fos);
1517 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001518 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001519 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001520 }
1521 }
1522
1523 /*
1524 * Writes the user list file in this format:
1525 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001526 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001527 * <user id="0"></user>
1528 * <user id="2"></user>
1529 * </users>
1530 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001531 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 if (DBG) {
1533 debug("writeUserList");
1534 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001535 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001536 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001537 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001538 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001539 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1540
1541 // XmlSerializer serializer = XmlUtils.serializerInstance();
1542 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001543 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001544 serializer.startDocument(null, true);
1545 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1546
1547 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001548 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001549 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001550
Adam Lesinskieddeb492014-09-08 17:50:03 -07001551 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001552 synchronized (mGuestRestrictions) {
1553 UserRestrictionsUtils
1554 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1555 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301556 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001557 synchronized (mRestrictionsLock) {
1558 UserRestrictionsUtils.writeRestrictions(serializer,
1559 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1560 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001561 int[] userIdsToWrite;
1562 synchronized (mUsersLock) {
1563 userIdsToWrite = new int[mUsers.size()];
1564 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001565 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001566 userIdsToWrite[i] = user.id;
1567 }
1568 }
1569 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001570 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001571 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001572 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001573 }
1574
1575 serializer.endTag(null, TAG_USERS);
1576
1577 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001578 userListFile.finishWrite(fos);
1579 } catch (Exception e) {
1580 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001581 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001582 }
1583 }
1584
Amith Yamasani12747872015-12-07 14:19:49 -08001585 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001586 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001587 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001588 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001589 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001590 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001591 long creationTime = 0L;
1592 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001593 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001594 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001595 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001596 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001597 boolean persistSeedData = false;
1598 String seedAccountName = null;
1599 String seedAccountType = null;
1600 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001601 Bundle baseRestrictions = new Bundle();
1602 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001603
1604 FileInputStream fis = null;
1605 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001606 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001607 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001608 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001609 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001610 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001611 int type;
1612 while ((type = parser.next()) != XmlPullParser.START_TAG
1613 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001614 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001615 }
1616
1617 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001618 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001619 return null;
1620 }
1621
1622 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001623 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1624 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001625 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001626 return null;
1627 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001628 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1629 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001630 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001631 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1632 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001633 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1634 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001635 restrictedProfileParentId = readIntAttribute(parser,
1636 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001637 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1638 if ("true".equals(valueString)) {
1639 partial = true;
1640 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001641 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1642 if ("true".equals(valueString)) {
1643 guestToRemove = true;
1644 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001645
Amith Yamasani12747872015-12-07 14:19:49 -08001646 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1647 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1648 if (seedAccountName != null || seedAccountType != null) {
1649 persistSeedData = true;
1650 }
1651
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001652 int outerDepth = parser.getDepth();
1653 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1654 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1655 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1656 continue;
1657 }
1658 String tag = parser.getName();
1659 if (TAG_NAME.equals(tag)) {
1660 type = parser.next();
1661 if (type == XmlPullParser.TEXT) {
1662 name = parser.getText();
1663 }
1664 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001665 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1666 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1667 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001668 } else if (TAG_ACCOUNT.equals(tag)) {
1669 type = parser.next();
1670 if (type == XmlPullParser.TEXT) {
1671 account = parser.getText();
1672 }
Amith Yamasani12747872015-12-07 14:19:49 -08001673 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1674 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1675 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001676 }
1677 }
1678 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001679
Amith Yamasani12747872015-12-07 14:19:49 -08001680 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001681 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001682 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001683 userInfo.creationTime = creationTime;
1684 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001685 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001686 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001687 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001688 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001689
1690 // Create the UserData object that's internal to this class
1691 UserData userData = new UserData();
1692 userData.info = userInfo;
1693 userData.account = account;
1694 userData.seedAccountName = seedAccountName;
1695 userData.seedAccountType = seedAccountType;
1696 userData.persistSeedData = persistSeedData;
1697 userData.seedAccountOptions = seedAccountOptions;
1698
Makoto Onuki068c54a2015-10-13 14:34:03 -07001699 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 mBaseUserRestrictions.put(id, baseRestrictions);
1701 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001702 }
Amith Yamasani12747872015-12-07 14:19:49 -08001703 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001704 } catch (IOException ioe) {
1705 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001706 } finally {
1707 if (fis != null) {
1708 try {
1709 fis.close();
1710 } catch (IOException e) {
1711 }
1712 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001713 }
1714 return null;
1715 }
1716
Amith Yamasani920ace02012-09-20 22:15:37 -07001717 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1718 String valueString = parser.getAttributeValue(null, attr);
1719 if (valueString == null) return defaultValue;
1720 try {
1721 return Integer.parseInt(valueString);
1722 } catch (NumberFormatException nfe) {
1723 return defaultValue;
1724 }
1725 }
1726
1727 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1728 String valueString = parser.getAttributeValue(null, attr);
1729 if (valueString == null) return defaultValue;
1730 try {
1731 return Long.parseLong(valueString);
1732 } catch (NumberFormatException nfe) {
1733 return defaultValue;
1734 }
1735 }
1736
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001737 private boolean isPackageInstalled(String pkg, int userId) {
1738 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1739 PackageManager.GET_UNINSTALLED_PACKAGES,
1740 userId);
1741 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1742 return false;
1743 }
1744 return true;
1745 }
1746
Amith Yamasanib82add22013-07-09 11:24:44 -07001747 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001748 * Removes the app restrictions file for a specific package and user id, if it exists.
1749 */
1750 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1751 synchronized (mPackagesLock) {
1752 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001753 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001754 if (resFile.exists()) {
1755 resFile.delete();
1756 }
1757 }
1758 }
1759
Kenny Guya52dc3e2014-02-11 15:33:14 +00001760 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001761 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001762 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001763 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001764 }
1765
Amith Yamasani258848d2012-08-10 17:06:33 -07001766 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001767 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001768 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001769 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001770 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001771
Jessica Hummelbe81c802014-04-22 15:49:22 +01001772 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001773 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001774 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1775 return null;
1776 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001777 if (ActivityManager.isLowRamDeviceStatic()) {
1778 return null;
1779 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001780 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001781 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001782 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001783 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001784 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001785 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001786 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001787 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001788 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001789 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001790 if (parentId != UserHandle.USER_NULL) {
1791 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001792 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001793 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001794 if (parent == null) return null;
1795 }
1796 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1797 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1798 return null;
1799 }
1800 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1801 // If we're not adding a guest user or a managed profile and the limit has
1802 // been reached, cannot add a user.
1803 return null;
1804 }
1805 // If we're adding a guest and there already exists one, bail.
1806 if (isGuest && findCurrentGuestUser() != null) {
1807 return null;
1808 }
1809 // In legacy mode, restricted profile's parent can only be the owner user
1810 if (isRestricted && !UserManager.isSplitSystemUser()
1811 && (parentId != UserHandle.USER_SYSTEM)) {
1812 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1813 return null;
1814 }
1815 if (isRestricted && UserManager.isSplitSystemUser()) {
1816 if (parent == null) {
1817 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1818 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001819 return null;
1820 }
Amith Yamasani12747872015-12-07 14:19:49 -08001821 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001822 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1823 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001824 return null;
1825 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001826 }
1827 // In split system user mode, we assign the first human user the primary flag.
1828 // And if there is no device owner, we also assign the admin flag to primary user.
1829 if (UserManager.isSplitSystemUser()
1830 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1831 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001832 synchronized (mUsersLock) {
1833 if (!mIsDeviceManaged) {
1834 flags |= UserInfo.FLAG_ADMIN;
1835 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001836 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001837 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001838
Lenka Trochtova02fee152015-12-22 14:26:18 +01001839 // Add ephemeral flag to guests if required. Also inherit it from parent.
1840 boolean ephemeralGuests = Resources.getSystem()
1841 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
1842 if ((isGuest && ephemeralGuests)
1843 || (parent != null && parent.info.isEphemeral())) {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001844 flags |= UserInfo.FLAG_EPHEMERAL;
1845 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001846 userId = getNextAvailableId();
1847 userInfo = new UserInfo(userId, name, null, flags);
1848 userInfo.serialNumber = mNextSerialNumber++;
1849 long now = System.currentTimeMillis();
1850 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1851 userInfo.partial = true;
Amith Yamasani12747872015-12-07 14:19:49 -08001852 userData = new UserData();
1853 userData.info = userInfo;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001854 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1855 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001856 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001857 }
1858 writeUserListLP();
1859 if (parent != null) {
1860 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001861 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1862 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001863 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001864 }
Amith Yamasani12747872015-12-07 14:19:49 -08001865 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001866 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001867 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1868 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001869 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001870 }
Amith Yamasani12747872015-12-07 14:19:49 -08001871 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001872 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001873 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001874 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001876 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001877 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1878 final String volumeUuid = vol.getFsUuid();
1879 try {
1880 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001881 storage.prepareUserStorage(
1882 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001883 enforceSerialNumber(userDir, userInfo.serialNumber);
1884 } catch (IOException e) {
1885 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1886 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001887 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001888 mPm.createNewUser(userId);
1889 userInfo.partial = false;
1890 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001891 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001892 }
1893 updateUserIds();
1894 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001895 if (isGuest) {
1896 synchronized (mGuestRestrictions) {
1897 restrictions.putAll(mGuestRestrictions);
1898 }
1899 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 synchronized (mRestrictionsLock) {
1901 mBaseUserRestrictions.append(userId, restrictions);
1902 }
1903 mPm.newUserCreated(userId);
1904 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1905 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1906 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1907 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001908 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001909 } finally {
1910 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001911 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001912 return userInfo;
1913 }
1914
Amith Yamasani0b285492011-04-14 17:35:23 -07001915 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001916 * @hide
1917 */
Amith Yamasani12747872015-12-07 14:19:49 -08001918 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001919 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1920 checkManageUsersPermission("setupRestrictedProfile");
1921 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1922 if (user == null) {
1923 return null;
1924 }
1925 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1926 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1927 // the putIntForUser() will fail.
1928 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1929 android.provider.Settings.Secure.LOCATION_MODE,
1930 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1931 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1932 return user;
1933 }
1934
1935 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001936 * Find the current guest user. If the Guest user is partial,
1937 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001938 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001939 private UserInfo findCurrentGuestUser() {
1940 synchronized (mUsersLock) {
1941 final int size = mUsers.size();
1942 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001943 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001944 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1945 return user;
1946 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001947 }
1948 }
1949 return null;
1950 }
1951
1952 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001953 * Mark this guest user for deletion to allow us to create another guest
1954 * and switch to that user before actually removing this guest.
1955 * @param userHandle the userid of the current guest
1956 * @return whether the user could be marked for deletion
1957 */
Amith Yamasani12747872015-12-07 14:19:49 -08001958 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001959 public boolean markGuestForDeletion(int userHandle) {
1960 checkManageUsersPermission("Only the system can remove users");
1961 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1962 UserManager.DISALLOW_REMOVE_USER, false)) {
1963 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1964 return false;
1965 }
1966
1967 long ident = Binder.clearCallingIdentity();
1968 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001969 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001970 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001971 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001972 userData = mUsers.get(userHandle);
1973 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001974 return false;
1975 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001976 }
Amith Yamasani12747872015-12-07 14:19:49 -08001977 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001978 return false;
1979 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001980 // We set this to a guest user that is to be removed. This is a temporary state
1981 // where we are allowed to add new Guest users, even if this one is still not
1982 // removed. This user will still show up in getUserInfo() calls.
1983 // If we don't get around to removing this Guest user, it will be purged on next
1984 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001985 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001986 // Mark it as disabled, so that it isn't returned any more when
1987 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001988 userData.info.flags |= UserInfo.FLAG_DISABLED;
1989 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07001990 }
1991 } finally {
1992 Binder.restoreCallingIdentity(ident);
1993 }
1994 return true;
1995 }
1996
1997 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001998 * Removes a user and all data directories created for that user. This method should be called
1999 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002000 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002001 */
Amith Yamasani12747872015-12-07 14:19:49 -08002002 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002003 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002004 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002005 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2006 UserManager.DISALLOW_REMOVE_USER, false)) {
2007 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2008 return false;
2009 }
2010
Kenny Guyee58b4f2014-05-23 15:19:53 +01002011 long ident = Binder.clearCallingIdentity();
2012 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002013 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002014 int currentUser = ActivityManager.getCurrentUser();
2015 if (currentUser == userHandle) {
2016 Log.w(LOG_TAG, "Current user cannot be removed");
2017 return false;
2018 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002019 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002020 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002021 userData = mUsers.get(userHandle);
2022 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002023 return false;
2024 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002025
Fyodor Kupolov82402752015-10-28 14:54:51 -07002026 // We remember deleted user IDs to prevent them from being
2027 // reused during the current boot; they can still be reused
2028 // after a reboot.
2029 mRemovingUserIds.put(userHandle, true);
2030 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002031
Kenny Guyee58b4f2014-05-23 15:19:53 +01002032 try {
2033 mAppOpsService.removeUser(userHandle);
2034 } catch (RemoteException e) {
2035 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2036 }
2037 // Set this to a partially created user, so that the user will be purged
2038 // on next startup, in case the runtime stops now before stopping and
2039 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002040 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002041 // Mark it as disabled, so that it isn't returned any more when
2042 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002043 userData.info.flags |= UserInfo.FLAG_DISABLED;
2044 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002045 }
2046
Amith Yamasani12747872015-12-07 14:19:49 -08002047 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2048 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002049 // Send broadcast to notify system that the user removed was a
2050 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002051 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002052 }
2053
2054 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2055 int res;
2056 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002057 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2058 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002059 @Override
2060 public void userStopped(int userId) {
2061 finishRemoveUser(userId);
2062 }
2063 @Override
2064 public void userStopAborted(int userId) {
2065 }
2066 });
2067 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002068 return false;
2069 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002070 return res == ActivityManager.USER_OP_SUCCESS;
2071 } finally {
2072 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002073 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002074 }
2075
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002076 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002077 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002078 // Let other services shutdown any activity and clean up their state before completely
2079 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002080 long ident = Binder.clearCallingIdentity();
2081 try {
2082 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2083 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002084 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2085 android.Manifest.permission.MANAGE_USERS,
2086
2087 new BroadcastReceiver() {
2088 @Override
2089 public void onReceive(Context context, Intent intent) {
2090 if (DBG) {
2091 Slog.i(LOG_TAG,
2092 "USER_REMOVED broadcast sent, cleaning up user data "
2093 + userHandle);
2094 }
2095 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002096 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002097 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002098 // Clean up any ActivityManager state
2099 LocalServices.getService(ActivityManagerInternal.class)
2100 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002101 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002102 }
2103 }.start();
2104 }
2105 },
2106
2107 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002108 } finally {
2109 Binder.restoreCallingIdentity(ident);
2110 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002111 }
2112
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002113 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002114 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002115 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002116 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002117
2118 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002119 synchronized (mUsersLock) {
2120 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002121 mIsUserManaged.delete(userHandle);
2122 }
2123 synchronized (mRestrictionsLock) {
2124 mBaseUserRestrictions.remove(userHandle);
2125 mAppliedUserRestrictions.remove(userHandle);
2126 mCachedEffectiveUserRestrictions.remove(userHandle);
2127 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002128 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002129 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002130 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002131 userFile.delete();
2132 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002133 synchronized (mPackagesLock) {
2134 writeUserListLP();
2135 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002136 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002137 File userDir = Environment.getUserSystemDirectory(userHandle);
2138 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2139 if (userDir.renameTo(renamedUserDir)) {
2140 removeDirectoryRecursive(renamedUserDir);
2141 } else {
2142 removeDirectoryRecursive(userDir);
2143 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002144 }
2145
Amith Yamasani61f57372012-08-31 12:12:28 -07002146 private void removeDirectoryRecursive(File parent) {
2147 if (parent.isDirectory()) {
2148 String[] files = parent.list();
2149 for (String filename : files) {
2150 File child = new File(parent, filename);
2151 removeDirectoryRecursive(child);
2152 }
2153 }
2154 parent.delete();
2155 }
2156
Kenny Guyf8d3a232014-05-15 16:09:52 +01002157 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002158 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002159 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2160 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002161 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002162 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002163 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002164 }
2165
Amith Yamasani2a003292012-08-14 18:25:45 -07002166 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002167 public Bundle getApplicationRestrictions(String packageName) {
2168 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2169 }
2170
2171 @Override
2172 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002173 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002174 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002175 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002176 }
2177 synchronized (mPackagesLock) {
2178 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002179 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002180 }
2181 }
2182
2183 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002184 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002185 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002186 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002187 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002188 if (restrictions == null || restrictions.isEmpty()) {
2189 cleanAppRestrictionsForPackage(packageName, userId);
2190 } else {
2191 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002192 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002193 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002194 }
Robin Lee66e5d962014-04-09 16:44:21 +01002195
Kenny Guyd21b2182014-07-17 16:38:55 +01002196 if (isPackageInstalled(packageName, userId)) {
2197 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2198 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2199 changeIntent.setPackage(packageName);
2200 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2201 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2202 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002203 }
2204
2205 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002206 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002207 try {
2208 return mContext.getPackageManager().getApplicationInfo(packageName,
2209 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2210 } catch (NameNotFoundException nnfe) {
2211 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002212 } finally {
2213 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002214 }
2215 }
2216
Fyodor Kupolov82402752015-10-28 14:54:51 -07002217 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002218 AtomicFile restrictionsFile =
2219 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2220 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002221 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002222 }
2223
2224 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002225 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002226 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002227 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002228 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002229 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002230 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002231
2232 FileInputStream fis = null;
2233 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002234 fis = restrictionsFile.openRead();
2235 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002236 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002237 XmlUtils.nextElement(parser);
2238 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002239 Slog.e(LOG_TAG, "Unable to read restrictions file "
2240 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002241 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002242 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002243 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2244 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002245 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002246 } catch (IOException|XmlPullParserException e) {
2247 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002248 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002249 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002250 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002251 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002252 }
2253
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002254 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2255 XmlPullParser parser) throws XmlPullParserException, IOException {
2256 int type = parser.getEventType();
2257 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2258 String key = parser.getAttributeValue(null, ATTR_KEY);
2259 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2260 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2261 if (multiple != null) {
2262 values.clear();
2263 int count = Integer.parseInt(multiple);
2264 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2265 if (type == XmlPullParser.START_TAG
2266 && parser.getName().equals(TAG_VALUE)) {
2267 values.add(parser.nextText().trim());
2268 count--;
2269 }
2270 }
2271 String [] valueStrings = new String[values.size()];
2272 values.toArray(valueStrings);
2273 restrictions.putStringArray(key, valueStrings);
2274 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2275 restrictions.putBundle(key, readBundleEntry(parser, values));
2276 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2277 final int outerDepth = parser.getDepth();
2278 ArrayList<Bundle> bundleList = new ArrayList<>();
2279 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2280 Bundle childBundle = readBundleEntry(parser, values);
2281 bundleList.add(childBundle);
2282 }
2283 restrictions.putParcelableArray(key,
2284 bundleList.toArray(new Bundle[bundleList.size()]));
2285 } else {
2286 String value = parser.nextText().trim();
2287 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2288 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2289 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2290 restrictions.putInt(key, Integer.parseInt(value));
2291 } else {
2292 restrictions.putString(key, value);
2293 }
2294 }
2295 }
2296 }
2297
2298 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2299 throws IOException, XmlPullParserException {
2300 Bundle childBundle = new Bundle();
2301 final int outerDepth = parser.getDepth();
2302 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2303 readEntry(childBundle, values, parser);
2304 }
2305 return childBundle;
2306 }
2307
Fyodor Kupolov82402752015-10-28 14:54:51 -07002308 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002309 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002310 AtomicFile restrictionsFile = new AtomicFile(
2311 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002312 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002313 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002314 }
2315
2316 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002317 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002318 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002319 try {
2320 fos = restrictionsFile.startWrite();
2321 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2322
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002323 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002324 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002325 serializer.startDocument(null, true);
2326 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2327
2328 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002329 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002330 serializer.endTag(null, TAG_RESTRICTIONS);
2331
2332 serializer.endDocument();
2333 restrictionsFile.finishWrite(fos);
2334 } catch (Exception e) {
2335 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002336 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2337 }
2338 }
2339
2340 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2341 throws IOException {
2342 for (String key : restrictions.keySet()) {
2343 Object value = restrictions.get(key);
2344 serializer.startTag(null, TAG_ENTRY);
2345 serializer.attribute(null, ATTR_KEY, key);
2346
2347 if (value instanceof Boolean) {
2348 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2349 serializer.text(value.toString());
2350 } else if (value instanceof Integer) {
2351 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2352 serializer.text(value.toString());
2353 } else if (value == null || value instanceof String) {
2354 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2355 serializer.text(value != null ? (String) value : "");
2356 } else if (value instanceof Bundle) {
2357 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2358 writeBundle((Bundle) value, serializer);
2359 } else if (value instanceof Parcelable[]) {
2360 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2361 Parcelable[] array = (Parcelable[]) value;
2362 for (Parcelable parcelable : array) {
2363 if (!(parcelable instanceof Bundle)) {
2364 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2365 }
2366 serializer.startTag(null, TAG_ENTRY);
2367 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2368 writeBundle((Bundle) parcelable, serializer);
2369 serializer.endTag(null, TAG_ENTRY);
2370 }
2371 } else {
2372 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2373 String[] values = (String[]) value;
2374 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2375 for (String choice : values) {
2376 serializer.startTag(null, TAG_VALUE);
2377 serializer.text(choice != null ? choice : "");
2378 serializer.endTag(null, TAG_VALUE);
2379 }
2380 }
2381 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002382 }
2383 }
2384
2385 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002386 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002387 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002388 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002389 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002390 }
2391 }
2392
2393 @Override
2394 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002395 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002396 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002398 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002399 }
2400 // Not found
2401 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002402 }
2403 }
2404
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002405 @Override
2406 public long getUserCreationTime(int userHandle) {
2407 int callingUserId = UserHandle.getCallingUserId();
2408 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002409 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002410 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002411 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002412 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002413 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002414 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002415 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002416 }
2417 }
2418 }
2419 if (userInfo == null) {
2420 throw new SecurityException("userHandle can only be the calling user or a managed "
2421 + "profile associated with this user");
2422 }
2423 return userInfo.creationTime;
2424 }
2425
Amith Yamasani0b285492011-04-14 17:35:23 -07002426 /**
2427 * Caches the list of user ids in an array, adjusting the array size when necessary.
2428 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002429 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002430 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002431 synchronized (mUsersLock) {
2432 final int userSize = mUsers.size();
2433 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002434 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002435 num++;
2436 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002437 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002438 final int[] newUsers = new int[num];
2439 int n = 0;
2440 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002441 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002442 newUsers[n++] = mUsers.keyAt(i);
2443 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002444 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002446 }
2447 }
2448
2449 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002450 * Called right before a user is started. This gives us a chance to prepare
2451 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002452 */
2453 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002454 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2455
2456 if (userId != UserHandle.USER_SYSTEM) {
2457 synchronized (mRestrictionsLock) {
2458 applyUserRestrictionsLR(userId);
2459 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002460 }
2461 }
2462
2463 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002464 * Called right before a user is unlocked. This gives us a chance to prepare
2465 * app storage.
2466 */
2467 public void onBeforeUnlockUser(int userId) {
2468 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2469 }
2470
2471 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002472 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002473 * @param userId the user that was just foregrounded
2474 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002475 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002476 UserData userData = getUserDataNoChecks(userId);
2477 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002478 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2479 return;
2480 }
2481 long now = System.currentTimeMillis();
2482 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002483 userData.info.lastLoggedInTime = now;
2484 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002485 }
2486 }
2487
2488 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002489 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002490 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2491 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002492 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002493 private int getNextAvailableId() {
2494 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002495 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002496 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002497 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002498 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002499 }
2500 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002501 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002502 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002503 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002504 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002505
Amith Yamasanifc95e702013-09-26 13:20:17 -07002506 private String packageToRestrictionsFileName(String packageName) {
2507 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2508 }
2509
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002510 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002511 * Enforce that serial number stored in user directory inode matches the
2512 * given expected value. Gracefully sets the serial number if currently
2513 * undefined.
2514 *
2515 * @throws IOException when problem extracting serial number, or serial
2516 * number is mismatched.
2517 */
2518 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2519 final int foundSerial = getSerialNumber(file);
2520 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2521
2522 if (foundSerial == -1) {
2523 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2524 try {
2525 setSerialNumber(file, serialNumber);
2526 } catch (IOException e) {
2527 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2528 }
2529
2530 } else if (foundSerial != serialNumber) {
2531 throw new IOException("Found serial number " + foundSerial
2532 + " doesn't match expected " + serialNumber);
2533 }
2534 }
2535
2536 /**
2537 * Set serial number stored in user directory inode.
2538 *
2539 * @throws IOException if serial number was already set
2540 */
2541 private static void setSerialNumber(File file, int serialNumber)
2542 throws IOException {
2543 try {
2544 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2545 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2546 } catch (ErrnoException e) {
2547 throw e.rethrowAsIOException();
2548 }
2549 }
2550
2551 /**
2552 * Return serial number stored in user directory inode.
2553 *
2554 * @return parsed serial number, or -1 if not set
2555 */
2556 private static int getSerialNumber(File file) throws IOException {
2557 try {
2558 final byte[] buf = new byte[256];
2559 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2560 final String serial = new String(buf, 0, len);
2561 try {
2562 return Integer.parseInt(serial);
2563 } catch (NumberFormatException e) {
2564 throw new IOException("Bad serial number: " + serial);
2565 }
2566 } catch (ErrnoException e) {
2567 if (e.errno == OsConstants.ENODATA) {
2568 return -1;
2569 } else {
2570 throw e.rethrowAsIOException();
2571 }
2572 }
2573 }
2574
Amith Yamasani920ace02012-09-20 22:15:37 -07002575 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002576 public void setSeedAccountData(int userId, String accountName, String accountType,
2577 PersistableBundle accountOptions, boolean persist) {
2578 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2579 synchronized (mPackagesLock) {
2580 final UserData userData;
2581 synchronized (mUsersLock) {
2582 userData = getUserDataLU(userId);
2583 if (userData == null) {
2584 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2585 return;
2586 }
2587 userData.seedAccountName = accountName;
2588 userData.seedAccountType = accountType;
2589 userData.seedAccountOptions = accountOptions;
2590 userData.persistSeedData = persist;
2591 }
2592 if (persist) {
2593 writeUserLP(userData);
2594 }
2595 }
2596 }
2597
2598 @Override
2599 public String getSeedAccountName() throws RemoteException {
2600 checkManageUsersPermission("Cannot get seed account information");
2601 synchronized (mUsersLock) {
2602 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2603 return userData.seedAccountName;
2604 }
2605 }
2606
2607 @Override
2608 public String getSeedAccountType() throws RemoteException {
2609 checkManageUsersPermission("Cannot get seed account information");
2610 synchronized (mUsersLock) {
2611 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2612 return userData.seedAccountType;
2613 }
2614 }
2615
2616 @Override
2617 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2618 checkManageUsersPermission("Cannot get seed account information");
2619 synchronized (mUsersLock) {
2620 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2621 return userData.seedAccountOptions;
2622 }
2623 }
2624
2625 @Override
2626 public void clearSeedAccountData() throws RemoteException {
2627 checkManageUsersPermission("Cannot clear seed account information");
2628 synchronized (mPackagesLock) {
2629 UserData userData;
2630 synchronized (mUsersLock) {
2631 userData = getUserDataLU(UserHandle.getCallingUserId());
2632 if (userData == null) return;
2633 userData.clearSeedAccountData();
2634 }
2635 writeUserLP(userData);
2636 }
2637 }
2638
2639 @Override
2640 public boolean someUserHasSeedAccount(String accountName, String accountType)
2641 throws RemoteException {
2642 checkManageUsersPermission("Cannot check seed account information");
2643 synchronized (mUsersLock) {
2644 final int userSize = mUsers.size();
2645 for (int i = 0; i < userSize; i++) {
2646 final UserData data = mUsers.valueAt(i);
2647 if (data.info.isInitialized()) continue;
2648 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2649 continue;
2650 }
2651 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2652 continue;
2653 }
2654 return true;
2655 }
2656 }
2657 return false;
2658 }
2659
2660 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002661 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2662 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2663 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2664 }
2665
2666 int onShellCommand(Shell shell, String cmd) {
2667 if (cmd == null) {
2668 return shell.handleDefaultCommands(cmd);
2669 }
2670
2671 final PrintWriter pw = shell.getOutPrintWriter();
2672 try {
2673 switch(cmd) {
2674 case "list":
2675 return runList(pw);
2676 }
2677 } catch (RemoteException e) {
2678 pw.println("Remote exception: " + e);
2679 }
2680 return -1;
2681 }
2682
2683 private int runList(PrintWriter pw) throws RemoteException {
2684 final IActivityManager am = ActivityManagerNative.getDefault();
2685 final List<UserInfo> users = getUsers(false);
2686 if (users == null) {
2687 pw.println("Error: couldn't get users");
2688 return 1;
2689 } else {
2690 pw.println("Users:");
2691 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002692 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002693 pw.println("\t" + users.get(i).toString() + running);
2694 }
2695 return 0;
2696 }
2697 }
2698
2699 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002700 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2701 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2702 != PackageManager.PERMISSION_GRANTED) {
2703 pw.println("Permission Denial: can't dump UserManager from from pid="
2704 + Binder.getCallingPid()
2705 + ", uid=" + Binder.getCallingUid()
2706 + " without permission "
2707 + android.Manifest.permission.DUMP);
2708 return;
2709 }
2710
2711 long now = System.currentTimeMillis();
2712 StringBuilder sb = new StringBuilder();
2713 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002714 synchronized (mUsersLock) {
2715 pw.println("Users:");
2716 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002717 UserData userData = mUsers.valueAt(i);
2718 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002719 continue;
2720 }
Amith Yamasani12747872015-12-07 14:19:49 -08002721 UserInfo userInfo = userData.info;
2722 final int userId = userInfo.id;
2723 pw.print(" "); pw.print(userInfo);
2724 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002725 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002726 pw.print(" <removing> ");
2727 }
Amith Yamasani12747872015-12-07 14:19:49 -08002728 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002729 pw.print(" <partial>");
2730 }
2731 pw.println();
2732 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002733 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002734 pw.println("<unknown>");
2735 } else {
2736 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002737 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002738 sb.append(" ago");
2739 pw.println(sb);
2740 }
2741 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002742 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002743 pw.println("<unknown>");
2744 } else {
2745 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002746 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002747 sb.append(" ago");
2748 pw.println(sb);
2749 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002750 pw.print(" Has profile owner: ");
2751 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002752 pw.println(" Restrictions:");
2753 synchronized (mRestrictionsLock) {
2754 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002755 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002756 pw.println(" Device policy local restrictions:");
2757 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002758 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002759 pw.println(" Effective restrictions:");
2760 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002761 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 }
Amith Yamasani12747872015-12-07 14:19:49 -08002763
2764 if (userData.account != null) {
2765 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002766 pw.println();
2767 }
Amith Yamasani12747872015-12-07 14:19:49 -08002768
2769 if (userData.seedAccountName != null) {
2770 pw.print(" Seed account name: " + userData.seedAccountName);
2771 pw.println();
2772 if (userData.seedAccountType != null) {
2773 pw.print(" account type: " + userData.seedAccountType);
2774 pw.println();
2775 }
2776 if (userData.seedAccountOptions != null) {
2777 pw.print(" account options exist");
2778 pw.println();
2779 }
2780 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002781 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002782 }
Amith Yamasani12747872015-12-07 14:19:49 -08002783 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002784 pw.println(" Device policy global restrictions:");
2785 synchronized (mRestrictionsLock) {
2786 UserRestrictionsUtils
2787 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2788 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002789 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002790 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002792 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002793 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002794 synchronized (mUsersLock) {
2795 pw.println();
2796 pw.println(" Device managed: " + mIsDeviceManaged);
2797 }
Amith Yamasani12747872015-12-07 14:19:49 -08002798 // Dump some capabilities
2799 pw.println();
2800 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2801 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002802 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2803 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002804 }
2805 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002806
2807 final class MainHandler extends Handler {
2808
2809 @Override
2810 public void handleMessage(Message msg) {
2811 switch (msg.what) {
2812 case WRITE_USER_MSG:
2813 removeMessages(WRITE_USER_MSG, msg.obj);
2814 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002815 int userId = ((UserData) msg.obj).info.id;
2816 UserData userData = getUserDataNoChecks(userId);
2817 if (userData != null) {
2818 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002819 }
2820 }
2821 }
2822 }
2823 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002824
2825 /**
2826 * @param userId
2827 * @return whether the user has been initialized yet
2828 */
2829 boolean isInitialized(int userId) {
2830 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2831 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002832
2833 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002834 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002835 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2836 @Nullable Bundle globalRestrictions) {
2837 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2838 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002839 }
2840
2841 @Override
2842 public Bundle getBaseUserRestrictions(int userId) {
2843 synchronized (mRestrictionsLock) {
2844 return mBaseUserRestrictions.get(userId);
2845 }
2846 }
2847
2848 @Override
2849 public void setBaseUserRestrictionsByDpmsForMigration(
2850 int userId, Bundle baseRestrictions) {
2851 synchronized (mRestrictionsLock) {
2852 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002853 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002854 }
2855
Amith Yamasani12747872015-12-07 14:19:49 -08002856 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002857 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002858 if (userData != null) {
2859 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002860 } else {
2861 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2862 }
2863 }
2864 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002865
2866 @Override
2867 public boolean getUserRestriction(int userId, String key) {
2868 return getUserRestrictions(userId).getBoolean(key);
2869 }
2870
2871 @Override
2872 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2873 synchronized (mUserRestrictionsListeners) {
2874 mUserRestrictionsListeners.add(listener);
2875 }
2876 }
2877
2878 @Override
2879 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2880 synchronized (mUserRestrictionsListeners) {
2881 mUserRestrictionsListeners.remove(listener);
2882 }
2883 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002884
2885 @Override
2886 public void setDeviceManaged(boolean isManaged) {
2887 synchronized (mUsersLock) {
2888 mIsDeviceManaged = isManaged;
2889 }
2890 }
2891
2892 @Override
2893 public void setUserManaged(int userId, boolean isManaged) {
2894 synchronized (mUsersLock) {
2895 mIsUserManaged.put(userId, isManaged);
2896 }
2897 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002898
2899 @Override
2900 public void setUserIcon(int userId, Bitmap bitmap) {
2901 long ident = Binder.clearCallingIdentity();
2902 try {
2903 synchronized (mPackagesLock) {
2904 UserData userData = getUserDataNoChecks(userId);
2905 if (userData == null || userData.info.partial) {
2906 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2907 return;
2908 }
2909 writeBitmapLP(userData.info, bitmap);
2910 writeUserLP(userData);
2911 }
2912 sendUserInfoChangedBroadcast(userId);
2913 } finally {
2914 Binder.restoreCallingIdentity(ident);
2915 }
2916 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002917 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002918
2919 private class Shell extends ShellCommand {
2920 @Override
2921 public int onCommand(String cmd) {
2922 return onShellCommand(this, cmd);
2923 }
2924
2925 @Override
2926 public void onHelp() {
2927 final PrintWriter pw = getOutPrintWriter();
2928 pw.println("User manager (user) commands:");
2929 pw.println(" help");
2930 pw.println(" Print this help text.");
2931 pw.println("");
2932 pw.println(" list");
2933 pw.println(" Prints all users on the system.");
2934 }
2935 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002936
2937 private static void debug(String message) {
2938 Log.d(LOG_TAG, message +
2939 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2940 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002941}