blob: 5b9f0b3b67a29a66f870c8d18a6312c51c1caa98 [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";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800112 static final boolean DBG = false; // 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,
555 UserHandle parentHandle, Bundle extras) {
556 // Send intent to profile
557 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
558 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
559 intent.putExtras(extras);
560 mContext.sendBroadcastAsUser(intent, profileHandle);
561
562 // Send intent to parent
563 if (parentHandle != null) {
564 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
565 intent.putExtra(Intent.EXTRA_USER, profileHandle);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700566 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000567 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
568 intent.putExtras(extras);
569 mContext.sendBroadcastAsUser(intent, parentHandle);
570 }
571 }
572
573 @Override
574 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
575 checkManageUsersPermission("silence profile");
576 boolean changed = false;
577 UserInfo profile, parent;
578 synchronized (mPackagesLock) {
579 synchronized (mUsersLock) {
580 profile = getUserInfoLU(userHandle);
581 parent = getProfileParentLU(userHandle);
582
583 }
584 if (profile == null || !profile.isManagedProfile()) {
585 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
586 }
587 if (profile.isQuietModeEnabled() != enableQuietMode) {
588 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800589 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000590 changed = true;
591 }
592 }
593 if (changed) {
594 Bundle extras = new Bundle();
595 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
596 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
597 parent != null ? parent.getUserHandle() : null, extras);
598 }
599 }
600
601 @Override
602 public boolean isQuietModeEnabled(int userHandle) {
603 synchronized (mPackagesLock) {
604 UserInfo info;
605 synchronized (mUsersLock) {
606 info = getUserInfoLU(userHandle);
607 }
608 if (info == null || !info.isManagedProfile()) {
609 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
610 }
611 return info.isQuietModeEnabled();
612 }
613 }
614
Kenny Guya52dc3e2014-02-11 15:33:14 +0000615 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100616 public void setUserEnabled(int userId) {
617 checkManageUsersPermission("enable user");
618 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 UserInfo info;
620 synchronized (mUsersLock) {
621 info = getUserInfoLU(userId);
622 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100623 if (info != null && !info.isEnabled()) {
624 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800625 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100626 }
627 }
628 }
629
630 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700631 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700632 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700633 synchronized (mUsersLock) {
634 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700635 }
636 }
637
Amith Yamasani71e6c692013-03-24 17:39:28 -0700638 @Override
639 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700640 synchronized (mUsersLock) {
641 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700642 }
643 }
644
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700645 @Override
646 public boolean canHaveRestrictedProfile(int userId) {
647 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700648 synchronized (mUsersLock) {
649 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700650 if (userInfo == null || !userInfo.canHaveProfile()) {
651 return false;
652 }
653 if (!userInfo.isAdmin()) {
654 return false;
655 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800656 // restricted profile can be created if there is no DO set and the admin user has no PO;
657 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700658 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700659 }
660
Amith Yamasani195263742012-08-21 15:40:12 -0700661 /*
662 * Should be locked on mUsers before calling this.
663 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700664 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800665 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700666 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800667 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700668 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
669 return null;
670 }
Amith Yamasani12747872015-12-07 14:19:49 -0800671 return userData != null ? userData.info : null;
672 }
673
674 private UserData getUserDataLU(int userId) {
675 final UserData userData = mUsers.get(userId);
676 // If it is partial and not in the process of being removed, return as unknown user.
677 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
678 return null;
679 }
680 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700681 }
682
Fyodor Kupolov82402752015-10-28 14:54:51 -0700683 /**
684 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
685 * <p>No permissions checking or any addition checks are made</p>
686 */
687 private UserInfo getUserInfoNoChecks(int userId) {
688 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800689 final UserData userData = mUsers.get(userId);
690 return userData != null ? userData.info : null;
691 }
692 }
693
694 /**
695 * Obtains {@link #mUsersLock} and return UserData from mUsers.
696 * <p>No permissions checking or any addition checks are made</p>
697 */
698 private UserData getUserDataNoChecks(int userId) {
699 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700700 return mUsers.get(userId);
701 }
702 }
703
Amith Yamasani236b2b52015-08-18 14:32:14 -0700704 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700705 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700706 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700707 }
708
Amith Yamasani258848d2012-08-10 17:06:33 -0700709 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700710 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700711 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700712 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700713 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800714 UserData userData = getUserDataNoChecks(userId);
715 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700716 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
717 return;
718 }
Amith Yamasani12747872015-12-07 14:19:49 -0800719 if (name != null && !name.equals(userData.info.name)) {
720 userData.info.name = name;
721 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700722 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700723 }
724 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700725 if (changed) {
726 sendUserInfoChangedBroadcast(userId);
727 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700728 }
729
Amith Yamasani258848d2012-08-10 17:06:33 -0700730 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700731 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700732 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100733 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
734 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
735 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700736 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100737 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700738 }
739
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100740
741
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700742 private void sendUserInfoChangedBroadcast(int userId) {
743 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
744 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
745 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700746 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700747 }
748
Amith Yamasani258848d2012-08-10 17:06:33 -0700749 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100750 public ParcelFileDescriptor getUserIcon(int userId) {
751 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700752 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700753 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700754 if (info == null || info.partial) {
755 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
756 return null;
757 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700758 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100759 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
760 || callingGroupId != info.profileGroupId) {
761 checkManageUsersPermission("get the icon of a user who is not related");
762 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700763 if (info.iconPath == null) {
764 return null;
765 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100766 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700767 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100768
769 try {
770 return ParcelFileDescriptor.open(
771 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
772 } catch (FileNotFoundException e) {
773 Log.e(LOG_TAG, "Couldn't find icon file", e);
774 }
775 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700776 }
777
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700778 public void makeInitialized(int userId) {
779 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800780 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800781 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800782 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800783 userData = mUsers.get(userId);
784 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700785 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800786 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700787 }
Amith Yamasani12747872015-12-07 14:19:49 -0800788 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
789 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800790 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700791 }
792 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800793 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800794 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800795 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700796 }
797
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700798 /**
799 * If default guest restrictions haven't been initialized yet, add the basic
800 * restrictions.
801 */
802 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800803 synchronized (mGuestRestrictions) {
804 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800805 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800806 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
807 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
808 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700809 }
810 }
811
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800812 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530813 public Bundle getDefaultGuestRestrictions() {
814 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800815 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530816 return new Bundle(mGuestRestrictions);
817 }
818 }
819
820 @Override
821 public void setDefaultGuestRestrictions(Bundle restrictions) {
822 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800823 synchronized (mGuestRestrictions) {
824 mGuestRestrictions.clear();
825 mGuestRestrictions.putAll(restrictions);
826 }
827 synchronized (mPackagesLock) {
828 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530829 }
830 }
831
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800832 /**
833 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
834 */
835 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
836 @Nullable Bundle global) {
837 Preconditions.checkNotNull(local);
838 boolean globalChanged = false;
839 boolean localChanged;
840 synchronized (mRestrictionsLock) {
841 if (global != null) {
842 // Update global.
843 globalChanged = !UserRestrictionsUtils.areEqual(
844 mDevicePolicyGlobalUserRestrictions, global);
845 if (globalChanged) {
846 mDevicePolicyGlobalUserRestrictions = global;
847 }
848 }
849 {
850 // Update local.
851 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
852 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
853 if (localChanged) {
854 mDevicePolicyLocalUserRestrictions.put(userId, local);
855 }
856 }
857 }
858 if (DBG) {
859 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
860 + " global=" + global + (globalChanged ? " (changed)" : "")
861 + " local=" + local + (localChanged ? " (changed)" : "")
862 );
863 }
864 // Don't call them within the mRestrictionsLock.
865 synchronized (mPackagesLock) {
866 if (globalChanged) {
867 writeUserListLP();
868 }
869 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800870 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800871 }
872 }
873
874 synchronized (mRestrictionsLock) {
875 if (globalChanged) {
876 applyUserRestrictionsForAllUsersLR();
877 } else if (localChanged) {
878 applyUserRestrictionsLR(userId);
879 }
880 }
881 }
882
Makoto Onuki068c54a2015-10-13 14:34:03 -0700883 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700884 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800885 final Bundle baseRestrictions =
886 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
887 final Bundle global = mDevicePolicyGlobalUserRestrictions;
888 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700889
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800890 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
891 // Common case first.
892 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700893 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800894 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
895 UserRestrictionsUtils.merge(effective, global);
896 UserRestrictionsUtils.merge(effective, local);
897
Makoto Onuki068c54a2015-10-13 14:34:03 -0700898 return effective;
899 }
900
901 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700902 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700903 if (DBG) {
904 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
905 }
906 mCachedEffectiveUserRestrictions.remove(userId);
907 }
908
909 private Bundle getEffectiveUserRestrictions(int userId) {
910 synchronized (mRestrictionsLock) {
911 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
912 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700913 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700914 mCachedEffectiveUserRestrictions.put(userId, restrictions);
915 }
916 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700917 }
918 }
919
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920 /** @return a specific user restriction that's in effect currently. */
921 @Override
922 public boolean hasUserRestriction(String restrictionKey, int userId) {
923 Bundle restrictions = getEffectiveUserRestrictions(userId);
924 return restrictions != null && restrictions.getBoolean(restrictionKey);
925 }
926
927 /**
928 * @return UserRestrictions that are in effect currently. This always returns a new
929 * {@link Bundle}.
930 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700931 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800932 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800933 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800934 }
935
936 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000937 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
938 checkManageUsersPermission("hasBaseUserRestriction");
939 synchronized (mRestrictionsLock) {
940 Bundle bundle = mBaseUserRestrictions.get(userId);
941 return (bundle != null && bundle.getBoolean(restrictionKey, false));
942 }
943 }
944
945 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700946 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700947 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700948 synchronized (mRestrictionsLock) {
949 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
950 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800951 final Bundle newRestrictions = UserRestrictionsUtils.clone(
952 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700953 newRestrictions.putBoolean(key, value);
954
Fyodor Kupolov82402752015-10-28 14:54:51 -0700955 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700956 }
957 }
958
Makoto Onuki068c54a2015-10-13 14:34:03 -0700959 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800960 * Optionally updating user restrictions, calculate the effective user restrictions and also
961 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700962 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800963 * @param newRestrictions User restrictions to set.
964 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700965 * @param userId target user ID.
966 */
967 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700968 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800970
971 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
972 mAppliedUserRestrictions.get(userId));
973
974 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700975 if (newRestrictions != null) {
976 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
978
979 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700980 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
981 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800982
983 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
984 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800985 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800986 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700987 }
988
Fyodor Kupolov82402752015-10-28 14:54:51 -0700989 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700990
Makoto Onuki759a7632015-10-28 16:43:10 -0700991 mCachedEffectiveUserRestrictions.put(userId, effective);
992
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800993 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700994 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800995 debug("Applying user restrictions: userId=" + userId
996 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700997 }
998
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800999 if (mAppOpsService != null) { // We skip it until system-ready.
1000 final long token = Binder.clearCallingIdentity();
1001 try {
1002 mAppOpsService.setUserRestrictions(effective, userId);
1003 } catch (RemoteException e) {
1004 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1005 } finally {
1006 Binder.restoreCallingIdentity(token);
1007 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001008 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001009
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001010 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001011
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001013 }
1014
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001015 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001016 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001017 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1018 // actually, but we still need some kind of synchronization otherwise we might end up
1019 // calling listeners out-of-order, thus "LR".
1020
1021 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1022 return;
1023 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001024
1025 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1026 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1027
1028 mHandler.post(new Runnable() {
1029 @Override
1030 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001031 UserRestrictionsUtils.applyUserRestrictions(
1032 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001033
Makoto Onukid45a4a22015-11-02 17:17:38 -08001034 final UserRestrictionsListener[] listeners;
1035 synchronized (mUserRestrictionsListeners) {
1036 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1037 mUserRestrictionsListeners.toArray(listeners);
1038 }
1039 for (int i = 0; i < listeners.length; i++) {
1040 listeners[i].onUserRestrictionsChanged(userId,
1041 newRestrictionsFinal, prevRestrictionsFinal);
1042 }
1043 }
1044 });
1045 }
1046
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001047 // Package private for the inner class.
1048 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001049 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001050 }
1051
1052 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001053 // Package private for the inner class.
1054 void applyUserRestrictionsForAllUsersLR() {
1055 if (DBG) {
1056 debug("applyUserRestrictionsForAllUsersLR");
1057 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001058 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001059 mCachedEffectiveUserRestrictions.clear();
1060
Makoto Onuki068c54a2015-10-13 14:34:03 -07001061 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1062 // it on a handler.
1063 final Runnable r = new Runnable() {
1064 @Override
1065 public void run() {
1066 // Then get the list of running users.
1067 final int[] runningUsers;
1068 try {
1069 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1070 } catch (RemoteException e) {
1071 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1072 return;
1073 }
1074 // Then re-calculate the effective restrictions and apply, only for running users.
1075 // It's okay if a new user has started after the getRunningUserIds() call,
1076 // because we'll do the same thing (re-calculate the restrictions and apply)
1077 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001078 synchronized (mRestrictionsLock) {
1079 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001080 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001081 }
1082 }
1083 }
1084 };
1085 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001086 }
1087
Amith Yamasani258848d2012-08-10 17:06:33 -07001088 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001089 * Check if we've hit the limit of how many users can be created.
1090 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001091 private boolean isUserLimitReached() {
1092 int count;
1093 synchronized (mUsersLock) {
1094 count = getAliveUsersExcludingGuestsCountLU();
1095 }
1096 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001097 }
1098
1099 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001100 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001101 checkManageUsersPermission("check if more managed profiles can be added.");
1102 if (ActivityManager.isLowRamDeviceStatic()) {
1103 return false;
1104 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001105 if (!mContext.getPackageManager().hasSystemFeature(
1106 PackageManager.FEATURE_MANAGED_USERS)) {
1107 return false;
1108 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001109 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001110 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1111 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1112 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001113 return false;
1114 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001115 synchronized(mUsersLock) {
1116 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001117 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001118 return false;
1119 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001120 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1121 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001122 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001123 return usersCountAfterRemoving == 1
1124 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001125 }
1126 }
1127
Fyodor Kupolov82402752015-10-28 14:54:51 -07001128 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001129 int aliveUserCount = 0;
1130 final int totalUserCount = mUsers.size();
1131 // Skip over users being removed
1132 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001133 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001134 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001135 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001136 aliveUserCount++;
1137 }
1138 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001139 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001140 }
1141
1142 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001143 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001144 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1145 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1146 * permissions can make certain calls to the UserManager.
1147 *
1148 * @param message used as message if SecurityException is thrown
1149 * @throws SecurityException if the caller does not have enough privilege.
1150 */
1151 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1152 final int uid = Binder.getCallingUid();
1153 if (uid != Process.SYSTEM_UID && uid != 0
1154 && ActivityManager.checkComponentPermission(
1155 Manifest.permission.MANAGE_USERS,
1156 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1157 && ActivityManager.checkComponentPermission(
1158 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1159 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1160 throw new SecurityException(
1161 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1162 + message);
1163 }
1164 }
1165
1166 /**
1167 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001168 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001169 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001170 *
1171 * @param message used as message if SecurityException is thrown
1172 * @throws SecurityException if the caller is not system or root
1173 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001174 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001175 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001176 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001177 && ActivityManager.checkComponentPermission(
1178 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001179 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1180 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1181 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001182 }
1183
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001184 /**
1185 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1186 * UserManager.
1187 *
1188 * @param message used as message if SecurityException is thrown
1189 * @throws SecurityException if the caller is not system or root
1190 */
1191 private static void checkSystemOrRoot(String message) {
1192 final int uid = Binder.getCallingUid();
1193 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1194 throw new SecurityException("Only system may: " + message);
1195 }
1196 }
1197
Fyodor Kupolov82402752015-10-28 14:54:51 -07001198 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001199 try {
1200 File dir = new File(mUsersDir, Integer.toString(info.id));
1201 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001202 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001203 if (!dir.exists()) {
1204 dir.mkdir();
1205 FileUtils.setPermissions(
1206 dir.getPath(),
1207 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1208 -1, -1);
1209 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001210 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001211 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1212 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001213 info.iconPath = file.getAbsolutePath();
1214 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001215 try {
1216 os.close();
1217 } catch (IOException ioe) {
1218 // What the ... !
1219 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001220 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001221 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001222 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001223 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001224 }
1225
Amith Yamasani0b285492011-04-14 17:35:23 -07001226 /**
1227 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1228 * cache it elsewhere.
1229 * @return the array of user ids.
1230 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001231 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001232 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001233 return mUserIds;
1234 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001235 }
1236
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001237 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001238 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001239 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001240 return;
1241 }
1242 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001243 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001244 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001245 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001246 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001247 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 int type;
1249 while ((type = parser.next()) != XmlPullParser.START_TAG
1250 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001251 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001252 }
1253
1254 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001255 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 return;
1258 }
1259
Amith Yamasani2a003292012-08-14 18:25:45 -07001260 mNextSerialNumber = -1;
1261 if (parser.getName().equals(TAG_USERS)) {
1262 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1263 if (lastSerialNumber != null) {
1264 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1265 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001266 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1267 if (versionNumber != null) {
1268 mUserVersion = Integer.parseInt(versionNumber);
1269 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001270 }
1271
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1273
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001274 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301275 if (type == XmlPullParser.START_TAG) {
1276 final String name = parser.getName();
1277 if (name.equals(TAG_USER)) {
1278 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001279
Amith Yamasani12747872015-12-07 14:19:49 -08001280 UserData userData = readUserLP(Integer.parseInt(id));
1281
1282 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001283 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001284 mUsers.put(userData.info.id, userData);
1285 if (mNextSerialNumber < 0
1286 || mNextSerialNumber <= userData.info.id) {
1287 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001288 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301289 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001290 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301291 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001292 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1293 && type != XmlPullParser.END_TAG) {
1294 if (type == XmlPullParser.START_TAG) {
1295 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001296 synchronized (mGuestRestrictions) {
1297 UserRestrictionsUtils
1298 .readRestrictions(parser, mGuestRestrictions);
1299 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001300 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1301 ) {
1302 UserRestrictionsUtils.readRestrictions(parser,
1303 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001304 }
1305 break;
1306 }
1307 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001308 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 }
1310 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001311 synchronized (mRestrictionsLock) {
1312 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1313 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001314 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001315 upgradeIfNecessaryLP();
1316 } catch (IOException | XmlPullParserException e) {
1317 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001318 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001319 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001320 }
1321 }
1322
Amith Yamasani6f34b412012-10-22 18:19:27 -07001323 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001324 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001325 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001326 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001327 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001328 int userVersion = mUserVersion;
1329 if (userVersion < 1) {
1330 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001331 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1332 if ("Primary".equals(userData.info.name)) {
1333 userData.info.name =
1334 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1335 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001336 }
1337 userVersion = 1;
1338 }
1339
Amith Yamasanibc9625052012-11-15 14:39:18 -08001340 if (userVersion < 2) {
1341 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001342 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1343 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1344 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1345 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001346 }
1347 userVersion = 2;
1348 }
1349
Amith Yamasani350962c2013-08-06 11:18:53 -07001350
Amith Yamasani5e486f52013-08-07 11:06:44 -07001351 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001352 userVersion = 4;
1353 }
1354
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001355 if (userVersion < 5) {
1356 initDefaultGuestRestrictions();
1357 userVersion = 5;
1358 }
1359
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001360 if (userVersion < 6) {
1361 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 synchronized (mUsersLock) {
1363 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001364 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001365 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001366 if (!splitSystemUser && userData.info.isRestricted()
1367 && (userData.info.restrictedProfileParentId
1368 == UserInfo.NO_PROFILE_GROUP_ID)) {
1369 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1370 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001371 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001372 }
1373 }
1374 userVersion = 6;
1375 }
1376
Amith Yamasani6f34b412012-10-22 18:19:27 -07001377 if (userVersion < USER_VERSION) {
1378 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1379 + USER_VERSION);
1380 } else {
1381 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001382
1383 if (originalVersion < mUserVersion) {
1384 writeUserListLP();
1385 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001386 }
1387 }
1388
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001389 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001390 int flags = UserInfo.FLAG_INITIALIZED;
1391 // In split system user mode, the admin and primary flags are assigned to the first human
1392 // user.
1393 if (!UserManager.isSplitSystemUser()) {
1394 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1395 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001396 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001397 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001398 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001399 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001400 UserData userData = new UserData();
1401 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001402 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001403 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001404 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001405 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001406 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001407
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001408 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 synchronized (mRestrictionsLock) {
1410 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1411 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001412
Fyodor Kupolov82402752015-10-28 14:54:51 -07001413 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001414 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001415
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001416 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001417 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001418 }
1419
Amith Yamasani12747872015-12-07 14:19:49 -08001420 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001421 if (DBG) {
1422 debug("scheduleWriteUser");
1423 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001424 // No need to wrap it within a lock -- worst case, we'll just post the same message
1425 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001426 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1427 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001428 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1429 }
1430 }
1431
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001432 /*
1433 * Writes the user file in this format:
1434 *
1435 * <user flags="20039023" id="0">
1436 * <name>Primary</name>
1437 * </user>
1438 */
Amith Yamasani12747872015-12-07 14:19:49 -08001439 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001440 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001441 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001442 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001443 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001444 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001445 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001446 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001447 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1448
1449 // XmlSerializer serializer = XmlUtils.serializerInstance();
1450 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001451 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001452 serializer.startDocument(null, true);
1453 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1454
Amith Yamasani12747872015-12-07 14:19:49 -08001455 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456 serializer.startTag(null, TAG_USER);
1457 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001458 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001459 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001460 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1461 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1462 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001463 if (userInfo.iconPath != null) {
1464 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1465 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001466 if (userInfo.partial) {
1467 serializer.attribute(null, ATTR_PARTIAL, "true");
1468 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001469 if (userInfo.guestToRemove) {
1470 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1471 }
Kenny Guy2a764942014-04-02 13:29:20 +01001472 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1473 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1474 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001475 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001476 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1477 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1478 Integer.toString(userInfo.restrictedProfileParentId));
1479 }
Amith Yamasani12747872015-12-07 14:19:49 -08001480 // Write seed data
1481 if (userData.persistSeedData) {
1482 if (userData.seedAccountName != null) {
1483 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1484 }
1485 if (userData.seedAccountType != null) {
1486 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1487 }
1488 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001489 serializer.startTag(null, TAG_NAME);
1490 serializer.text(userInfo.name);
1491 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001492 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001493 UserRestrictionsUtils.writeRestrictions(serializer,
1494 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1495 UserRestrictionsUtils.writeRestrictions(serializer,
1496 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1497 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001498 }
Amith Yamasani12747872015-12-07 14:19:49 -08001499
1500 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001501 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001502 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001503 serializer.endTag(null, TAG_ACCOUNT);
1504 }
1505
Amith Yamasani12747872015-12-07 14:19:49 -08001506 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1507 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1508 userData.seedAccountOptions.saveToXml(serializer);
1509 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1510 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001511 serializer.endTag(null, TAG_USER);
1512
1513 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001514 userFile.finishWrite(fos);
1515 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001516 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001517 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001518 }
1519 }
1520
1521 /*
1522 * Writes the user list file in this format:
1523 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001524 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001525 * <user id="0"></user>
1526 * <user id="2"></user>
1527 * </users>
1528 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001529 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530 if (DBG) {
1531 debug("writeUserList");
1532 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001533 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001534 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001535 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001536 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001537 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1538
1539 // XmlSerializer serializer = XmlUtils.serializerInstance();
1540 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001541 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001542 serializer.startDocument(null, true);
1543 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1544
1545 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001546 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001547 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001548
Adam Lesinskieddeb492014-09-08 17:50:03 -07001549 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001550 synchronized (mGuestRestrictions) {
1551 UserRestrictionsUtils
1552 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1553 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301554 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001555 synchronized (mRestrictionsLock) {
1556 UserRestrictionsUtils.writeRestrictions(serializer,
1557 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1558 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001559 int[] userIdsToWrite;
1560 synchronized (mUsersLock) {
1561 userIdsToWrite = new int[mUsers.size()];
1562 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001563 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001564 userIdsToWrite[i] = user.id;
1565 }
1566 }
1567 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001568 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001569 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001570 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001571 }
1572
1573 serializer.endTag(null, TAG_USERS);
1574
1575 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001576 userListFile.finishWrite(fos);
1577 } catch (Exception e) {
1578 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001579 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001580 }
1581 }
1582
Amith Yamasani12747872015-12-07 14:19:49 -08001583 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001584 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001585 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001586 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001587 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001588 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001589 long creationTime = 0L;
1590 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001591 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001592 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001593 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001594 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001595 boolean persistSeedData = false;
1596 String seedAccountName = null;
1597 String seedAccountType = null;
1598 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599 Bundle baseRestrictions = new Bundle();
1600 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001601
1602 FileInputStream fis = null;
1603 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001604 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001605 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001606 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001607 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001608 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001609 int type;
1610 while ((type = parser.next()) != XmlPullParser.START_TAG
1611 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001612 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001613 }
1614
1615 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001616 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001617 return null;
1618 }
1619
1620 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001621 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1622 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001623 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001624 return null;
1625 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001626 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1627 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001628 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001629 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1630 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001631 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1632 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001633 restrictedProfileParentId = readIntAttribute(parser,
1634 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001635 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1636 if ("true".equals(valueString)) {
1637 partial = true;
1638 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001639 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1640 if ("true".equals(valueString)) {
1641 guestToRemove = true;
1642 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001643
Amith Yamasani12747872015-12-07 14:19:49 -08001644 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1645 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1646 if (seedAccountName != null || seedAccountType != null) {
1647 persistSeedData = true;
1648 }
1649
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001650 int outerDepth = parser.getDepth();
1651 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1652 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1653 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1654 continue;
1655 }
1656 String tag = parser.getName();
1657 if (TAG_NAME.equals(tag)) {
1658 type = parser.next();
1659 if (type == XmlPullParser.TEXT) {
1660 name = parser.getText();
1661 }
1662 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001663 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1664 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1665 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001666 } else if (TAG_ACCOUNT.equals(tag)) {
1667 type = parser.next();
1668 if (type == XmlPullParser.TEXT) {
1669 account = parser.getText();
1670 }
Amith Yamasani12747872015-12-07 14:19:49 -08001671 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1672 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1673 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001674 }
1675 }
1676 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001677
Amith Yamasani12747872015-12-07 14:19:49 -08001678 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001679 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001680 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001681 userInfo.creationTime = creationTime;
1682 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001683 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001684 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001685 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001686 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001687
1688 // Create the UserData object that's internal to this class
1689 UserData userData = new UserData();
1690 userData.info = userInfo;
1691 userData.account = account;
1692 userData.seedAccountName = seedAccountName;
1693 userData.seedAccountType = seedAccountType;
1694 userData.persistSeedData = persistSeedData;
1695 userData.seedAccountOptions = seedAccountOptions;
1696
Makoto Onuki068c54a2015-10-13 14:34:03 -07001697 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 mBaseUserRestrictions.put(id, baseRestrictions);
1699 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001700 }
Amith Yamasani12747872015-12-07 14:19:49 -08001701 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001702 } catch (IOException ioe) {
1703 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001704 } finally {
1705 if (fis != null) {
1706 try {
1707 fis.close();
1708 } catch (IOException e) {
1709 }
1710 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001711 }
1712 return null;
1713 }
1714
Amith Yamasani920ace02012-09-20 22:15:37 -07001715 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1716 String valueString = parser.getAttributeValue(null, attr);
1717 if (valueString == null) return defaultValue;
1718 try {
1719 return Integer.parseInt(valueString);
1720 } catch (NumberFormatException nfe) {
1721 return defaultValue;
1722 }
1723 }
1724
1725 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1726 String valueString = parser.getAttributeValue(null, attr);
1727 if (valueString == null) return defaultValue;
1728 try {
1729 return Long.parseLong(valueString);
1730 } catch (NumberFormatException nfe) {
1731 return defaultValue;
1732 }
1733 }
1734
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001735 private boolean isPackageInstalled(String pkg, int userId) {
1736 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1737 PackageManager.GET_UNINSTALLED_PACKAGES,
1738 userId);
1739 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1740 return false;
1741 }
1742 return true;
1743 }
1744
Amith Yamasanib82add22013-07-09 11:24:44 -07001745 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001746 * Removes the app restrictions file for a specific package and user id, if it exists.
1747 */
1748 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1749 synchronized (mPackagesLock) {
1750 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001751 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001752 if (resFile.exists()) {
1753 resFile.delete();
1754 }
1755 }
1756 }
1757
Kenny Guya52dc3e2014-02-11 15:33:14 +00001758 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001759 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001760 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001761 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001762 }
1763
Amith Yamasani258848d2012-08-10 17:06:33 -07001764 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001765 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001766 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001767 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001768 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001769
Jessica Hummelbe81c802014-04-22 15:49:22 +01001770 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001771 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001772 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1773 return null;
1774 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001775 if (ActivityManager.isLowRamDeviceStatic()) {
1776 return null;
1777 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001778 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001779 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001780 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001781 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001782 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001783 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001784 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001785 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001786 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001787 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001788 if (parentId != UserHandle.USER_NULL) {
1789 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001790 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001791 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001792 if (parent == null) return null;
1793 }
1794 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1795 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1796 return null;
1797 }
1798 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1799 // If we're not adding a guest user or a managed profile and the limit has
1800 // been reached, cannot add a user.
1801 return null;
1802 }
1803 // If we're adding a guest and there already exists one, bail.
1804 if (isGuest && findCurrentGuestUser() != null) {
1805 return null;
1806 }
1807 // In legacy mode, restricted profile's parent can only be the owner user
1808 if (isRestricted && !UserManager.isSplitSystemUser()
1809 && (parentId != UserHandle.USER_SYSTEM)) {
1810 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1811 return null;
1812 }
1813 if (isRestricted && UserManager.isSplitSystemUser()) {
1814 if (parent == null) {
1815 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1816 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001817 return null;
1818 }
Amith Yamasani12747872015-12-07 14:19:49 -08001819 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001820 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1821 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001822 return null;
1823 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001824 }
1825 // In split system user mode, we assign the first human user the primary flag.
1826 // And if there is no device owner, we also assign the admin flag to primary user.
1827 if (UserManager.isSplitSystemUser()
1828 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1829 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001830 synchronized (mUsersLock) {
1831 if (!mIsDeviceManaged) {
1832 flags |= UserInfo.FLAG_ADMIN;
1833 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001834 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001835 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001836
Lenka Trochtova02fee152015-12-22 14:26:18 +01001837 // Add ephemeral flag to guests if required. Also inherit it from parent.
1838 boolean ephemeralGuests = Resources.getSystem()
1839 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
1840 if ((isGuest && ephemeralGuests)
1841 || (parent != null && parent.info.isEphemeral())) {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001842 flags |= UserInfo.FLAG_EPHEMERAL;
1843 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001844 userId = getNextAvailableId();
1845 userInfo = new UserInfo(userId, name, null, flags);
1846 userInfo.serialNumber = mNextSerialNumber++;
1847 long now = System.currentTimeMillis();
1848 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1849 userInfo.partial = true;
Amith Yamasani12747872015-12-07 14:19:49 -08001850 userData = new UserData();
1851 userData.info = userInfo;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001852 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1853 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001854 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001855 }
1856 writeUserListLP();
1857 if (parent != null) {
1858 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001859 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1860 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001861 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001862 }
Amith Yamasani12747872015-12-07 14:19:49 -08001863 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001864 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001865 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1866 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001868 }
Amith Yamasani12747872015-12-07 14:19:49 -08001869 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001870 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001871 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001872 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001873 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001874 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1876 final String volumeUuid = vol.getFsUuid();
1877 try {
1878 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001879 storage.prepareUserStorage(
1880 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001881 enforceSerialNumber(userDir, userInfo.serialNumber);
1882 } catch (IOException e) {
1883 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1884 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001885 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001886 mPm.createNewUser(userId);
1887 userInfo.partial = false;
1888 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001889 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001890 }
1891 updateUserIds();
1892 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001893 if (isGuest) {
1894 synchronized (mGuestRestrictions) {
1895 restrictions.putAll(mGuestRestrictions);
1896 }
1897 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 synchronized (mRestrictionsLock) {
1899 mBaseUserRestrictions.append(userId, restrictions);
1900 }
1901 mPm.newUserCreated(userId);
1902 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1903 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1904 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1905 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001906 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001907 } finally {
1908 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001909 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001910 return userInfo;
1911 }
1912
Amith Yamasani0b285492011-04-14 17:35:23 -07001913 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001914 * @hide
1915 */
Amith Yamasani12747872015-12-07 14:19:49 -08001916 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001917 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1918 checkManageUsersPermission("setupRestrictedProfile");
1919 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1920 if (user == null) {
1921 return null;
1922 }
1923 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1924 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1925 // the putIntForUser() will fail.
1926 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1927 android.provider.Settings.Secure.LOCATION_MODE,
1928 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1929 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1930 return user;
1931 }
1932
1933 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001934 * Find the current guest user. If the Guest user is partial,
1935 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001936 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001937 private UserInfo findCurrentGuestUser() {
1938 synchronized (mUsersLock) {
1939 final int size = mUsers.size();
1940 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001941 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001942 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1943 return user;
1944 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001945 }
1946 }
1947 return null;
1948 }
1949
1950 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001951 * Mark this guest user for deletion to allow us to create another guest
1952 * and switch to that user before actually removing this guest.
1953 * @param userHandle the userid of the current guest
1954 * @return whether the user could be marked for deletion
1955 */
Amith Yamasani12747872015-12-07 14:19:49 -08001956 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001957 public boolean markGuestForDeletion(int userHandle) {
1958 checkManageUsersPermission("Only the system can remove users");
1959 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1960 UserManager.DISALLOW_REMOVE_USER, false)) {
1961 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1962 return false;
1963 }
1964
1965 long ident = Binder.clearCallingIdentity();
1966 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001967 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001968 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001969 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001970 userData = mUsers.get(userHandle);
1971 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001972 return false;
1973 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001974 }
Amith Yamasani12747872015-12-07 14:19:49 -08001975 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001976 return false;
1977 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001978 // We set this to a guest user that is to be removed. This is a temporary state
1979 // where we are allowed to add new Guest users, even if this one is still not
1980 // removed. This user will still show up in getUserInfo() calls.
1981 // If we don't get around to removing this Guest user, it will be purged on next
1982 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001983 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001984 // Mark it as disabled, so that it isn't returned any more when
1985 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001986 userData.info.flags |= UserInfo.FLAG_DISABLED;
1987 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07001988 }
1989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 return true;
1993 }
1994
1995 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001996 * Removes a user and all data directories created for that user. This method should be called
1997 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001998 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001999 */
Amith Yamasani12747872015-12-07 14:19:49 -08002000 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002001 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002002 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002003 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2004 UserManager.DISALLOW_REMOVE_USER, false)) {
2005 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2006 return false;
2007 }
2008
Kenny Guyee58b4f2014-05-23 15:19:53 +01002009 long ident = Binder.clearCallingIdentity();
2010 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002011 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002012 int currentUser = ActivityManager.getCurrentUser();
2013 if (currentUser == userHandle) {
2014 Log.w(LOG_TAG, "Current user cannot be removed");
2015 return false;
2016 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002017 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002018 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002019 userData = mUsers.get(userHandle);
2020 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002021 return false;
2022 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002023
Fyodor Kupolov82402752015-10-28 14:54:51 -07002024 // We remember deleted user IDs to prevent them from being
2025 // reused during the current boot; they can still be reused
2026 // after a reboot.
2027 mRemovingUserIds.put(userHandle, true);
2028 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002029
Kenny Guyee58b4f2014-05-23 15:19:53 +01002030 try {
2031 mAppOpsService.removeUser(userHandle);
2032 } catch (RemoteException e) {
2033 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2034 }
2035 // Set this to a partially created user, so that the user will be purged
2036 // on next startup, in case the runtime stops now before stopping and
2037 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002038 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002039 // Mark it as disabled, so that it isn't returned any more when
2040 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002041 userData.info.flags |= UserInfo.FLAG_DISABLED;
2042 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002043 }
2044
Amith Yamasani12747872015-12-07 14:19:49 -08002045 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2046 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002047 // Send broadcast to notify system that the user removed was a
2048 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002049 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002050 }
2051
2052 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2053 int res;
2054 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002055 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2056 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002057 @Override
2058 public void userStopped(int userId) {
2059 finishRemoveUser(userId);
2060 }
2061 @Override
2062 public void userStopAborted(int userId) {
2063 }
2064 });
2065 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002066 return false;
2067 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002068 return res == ActivityManager.USER_OP_SUCCESS;
2069 } finally {
2070 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002071 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002072 }
2073
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002074 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002075 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002076 // Let other services shutdown any activity and clean up their state before completely
2077 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002078 long ident = Binder.clearCallingIdentity();
2079 try {
2080 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2081 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002082 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2083 android.Manifest.permission.MANAGE_USERS,
2084
2085 new BroadcastReceiver() {
2086 @Override
2087 public void onReceive(Context context, Intent intent) {
2088 if (DBG) {
2089 Slog.i(LOG_TAG,
2090 "USER_REMOVED broadcast sent, cleaning up user data "
2091 + userHandle);
2092 }
2093 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002094 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002095 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002096 // Clean up any ActivityManager state
2097 LocalServices.getService(ActivityManagerInternal.class)
2098 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002099 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002100 }
2101 }.start();
2102 }
2103 },
2104
2105 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002109 }
2110
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002111 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002112 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002113 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002114 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002115
2116 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002117 synchronized (mUsersLock) {
2118 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002119 mIsUserManaged.delete(userHandle);
2120 }
2121 synchronized (mRestrictionsLock) {
2122 mBaseUserRestrictions.remove(userHandle);
2123 mAppliedUserRestrictions.remove(userHandle);
2124 mCachedEffectiveUserRestrictions.remove(userHandle);
2125 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002127 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002128 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002129 userFile.delete();
2130 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002131 synchronized (mPackagesLock) {
2132 writeUserListLP();
2133 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002134 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002135 File userDir = Environment.getUserSystemDirectory(userHandle);
2136 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2137 if (userDir.renameTo(renamedUserDir)) {
2138 removeDirectoryRecursive(renamedUserDir);
2139 } else {
2140 removeDirectoryRecursive(userDir);
2141 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002142 }
2143
Amith Yamasani61f57372012-08-31 12:12:28 -07002144 private void removeDirectoryRecursive(File parent) {
2145 if (parent.isDirectory()) {
2146 String[] files = parent.list();
2147 for (String filename : files) {
2148 File child = new File(parent, filename);
2149 removeDirectoryRecursive(child);
2150 }
2151 }
2152 parent.delete();
2153 }
2154
Kenny Guyf8d3a232014-05-15 16:09:52 +01002155 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002156 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002157 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2158 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002159 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002160 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002161 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002162 }
2163
Amith Yamasani2a003292012-08-14 18:25:45 -07002164 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002165 public Bundle getApplicationRestrictions(String packageName) {
2166 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2167 }
2168
2169 @Override
2170 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002171 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002172 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002173 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002174 }
2175 synchronized (mPackagesLock) {
2176 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002177 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002178 }
2179 }
2180
2181 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002182 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002183 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002184 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002185 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002186 if (restrictions == null || restrictions.isEmpty()) {
2187 cleanAppRestrictionsForPackage(packageName, userId);
2188 } else {
2189 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002190 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002191 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002192 }
Robin Lee66e5d962014-04-09 16:44:21 +01002193
Kenny Guyd21b2182014-07-17 16:38:55 +01002194 if (isPackageInstalled(packageName, userId)) {
2195 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2196 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2197 changeIntent.setPackage(packageName);
2198 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2199 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2200 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002201 }
2202
2203 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002204 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002205 try {
2206 return mContext.getPackageManager().getApplicationInfo(packageName,
2207 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2208 } catch (NameNotFoundException nnfe) {
2209 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002210 } finally {
2211 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002212 }
2213 }
2214
Fyodor Kupolov82402752015-10-28 14:54:51 -07002215 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002216 AtomicFile restrictionsFile =
2217 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2218 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002219 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002220 }
2221
2222 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002223 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002224 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002225 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002226 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002227 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002228 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002229
2230 FileInputStream fis = null;
2231 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002232 fis = restrictionsFile.openRead();
2233 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002234 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002235 XmlUtils.nextElement(parser);
2236 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002237 Slog.e(LOG_TAG, "Unable to read restrictions file "
2238 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002239 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002240 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002241 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2242 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002243 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002244 } catch (IOException|XmlPullParserException e) {
2245 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002246 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002247 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002248 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002249 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002250 }
2251
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002252 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2253 XmlPullParser parser) throws XmlPullParserException, IOException {
2254 int type = parser.getEventType();
2255 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2256 String key = parser.getAttributeValue(null, ATTR_KEY);
2257 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2258 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2259 if (multiple != null) {
2260 values.clear();
2261 int count = Integer.parseInt(multiple);
2262 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2263 if (type == XmlPullParser.START_TAG
2264 && parser.getName().equals(TAG_VALUE)) {
2265 values.add(parser.nextText().trim());
2266 count--;
2267 }
2268 }
2269 String [] valueStrings = new String[values.size()];
2270 values.toArray(valueStrings);
2271 restrictions.putStringArray(key, valueStrings);
2272 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2273 restrictions.putBundle(key, readBundleEntry(parser, values));
2274 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2275 final int outerDepth = parser.getDepth();
2276 ArrayList<Bundle> bundleList = new ArrayList<>();
2277 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2278 Bundle childBundle = readBundleEntry(parser, values);
2279 bundleList.add(childBundle);
2280 }
2281 restrictions.putParcelableArray(key,
2282 bundleList.toArray(new Bundle[bundleList.size()]));
2283 } else {
2284 String value = parser.nextText().trim();
2285 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2286 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2287 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2288 restrictions.putInt(key, Integer.parseInt(value));
2289 } else {
2290 restrictions.putString(key, value);
2291 }
2292 }
2293 }
2294 }
2295
2296 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2297 throws IOException, XmlPullParserException {
2298 Bundle childBundle = new Bundle();
2299 final int outerDepth = parser.getDepth();
2300 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2301 readEntry(childBundle, values, parser);
2302 }
2303 return childBundle;
2304 }
2305
Fyodor Kupolov82402752015-10-28 14:54:51 -07002306 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002307 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002308 AtomicFile restrictionsFile = new AtomicFile(
2309 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002310 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002311 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002312 }
2313
2314 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002315 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002316 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002317 try {
2318 fos = restrictionsFile.startWrite();
2319 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2320
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002321 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002322 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002323 serializer.startDocument(null, true);
2324 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2325
2326 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002327 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002328 serializer.endTag(null, TAG_RESTRICTIONS);
2329
2330 serializer.endDocument();
2331 restrictionsFile.finishWrite(fos);
2332 } catch (Exception e) {
2333 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002334 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2335 }
2336 }
2337
2338 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2339 throws IOException {
2340 for (String key : restrictions.keySet()) {
2341 Object value = restrictions.get(key);
2342 serializer.startTag(null, TAG_ENTRY);
2343 serializer.attribute(null, ATTR_KEY, key);
2344
2345 if (value instanceof Boolean) {
2346 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2347 serializer.text(value.toString());
2348 } else if (value instanceof Integer) {
2349 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2350 serializer.text(value.toString());
2351 } else if (value == null || value instanceof String) {
2352 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2353 serializer.text(value != null ? (String) value : "");
2354 } else if (value instanceof Bundle) {
2355 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2356 writeBundle((Bundle) value, serializer);
2357 } else if (value instanceof Parcelable[]) {
2358 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2359 Parcelable[] array = (Parcelable[]) value;
2360 for (Parcelable parcelable : array) {
2361 if (!(parcelable instanceof Bundle)) {
2362 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2363 }
2364 serializer.startTag(null, TAG_ENTRY);
2365 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2366 writeBundle((Bundle) parcelable, serializer);
2367 serializer.endTag(null, TAG_ENTRY);
2368 }
2369 } else {
2370 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2371 String[] values = (String[]) value;
2372 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2373 for (String choice : values) {
2374 serializer.startTag(null, TAG_VALUE);
2375 serializer.text(choice != null ? choice : "");
2376 serializer.endTag(null, TAG_VALUE);
2377 }
2378 }
2379 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002380 }
2381 }
2382
2383 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002384 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002385 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002386 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002387 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002388 }
2389 }
2390
2391 @Override
2392 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002394 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002395 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002396 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002397 }
2398 // Not found
2399 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002400 }
2401 }
2402
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002403 @Override
2404 public long getUserCreationTime(int userHandle) {
2405 int callingUserId = UserHandle.getCallingUserId();
2406 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002407 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002408 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002409 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002410 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002411 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002412 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002413 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002414 }
2415 }
2416 }
2417 if (userInfo == null) {
2418 throw new SecurityException("userHandle can only be the calling user or a managed "
2419 + "profile associated with this user");
2420 }
2421 return userInfo.creationTime;
2422 }
2423
Amith Yamasani0b285492011-04-14 17:35:23 -07002424 /**
2425 * Caches the list of user ids in an array, adjusting the array size when necessary.
2426 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002427 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002428 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002429 synchronized (mUsersLock) {
2430 final int userSize = mUsers.size();
2431 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002432 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002433 num++;
2434 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002435 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002436 final int[] newUsers = new int[num];
2437 int n = 0;
2438 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002439 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002440 newUsers[n++] = mUsers.keyAt(i);
2441 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002442 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002443 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002444 }
2445 }
2446
2447 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002448 * Called right before a user is started. This gives us a chance to prepare
2449 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002450 */
2451 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002452 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2453
2454 if (userId != UserHandle.USER_SYSTEM) {
2455 synchronized (mRestrictionsLock) {
2456 applyUserRestrictionsLR(userId);
2457 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002458 }
2459 }
2460
2461 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002462 * Called right before a user is unlocked. This gives us a chance to prepare
2463 * app storage.
2464 */
2465 public void onBeforeUnlockUser(int userId) {
2466 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2467 }
2468
2469 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002470 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002471 * @param userId the user that was just foregrounded
2472 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002473 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002474 UserData userData = getUserDataNoChecks(userId);
2475 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002476 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2477 return;
2478 }
2479 long now = System.currentTimeMillis();
2480 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002481 userData.info.lastLoggedInTime = now;
2482 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002483 }
2484 }
2485
2486 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002487 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002488 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2489 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002490 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002491 private int getNextAvailableId() {
2492 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002493 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002494 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002495 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002496 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002497 }
2498 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002499 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002500 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002501 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002502 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002503
Amith Yamasanifc95e702013-09-26 13:20:17 -07002504 private String packageToRestrictionsFileName(String packageName) {
2505 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2506 }
2507
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002508 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002509 * Enforce that serial number stored in user directory inode matches the
2510 * given expected value. Gracefully sets the serial number if currently
2511 * undefined.
2512 *
2513 * @throws IOException when problem extracting serial number, or serial
2514 * number is mismatched.
2515 */
2516 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2517 final int foundSerial = getSerialNumber(file);
2518 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2519
2520 if (foundSerial == -1) {
2521 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2522 try {
2523 setSerialNumber(file, serialNumber);
2524 } catch (IOException e) {
2525 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2526 }
2527
2528 } else if (foundSerial != serialNumber) {
2529 throw new IOException("Found serial number " + foundSerial
2530 + " doesn't match expected " + serialNumber);
2531 }
2532 }
2533
2534 /**
2535 * Set serial number stored in user directory inode.
2536 *
2537 * @throws IOException if serial number was already set
2538 */
2539 private static void setSerialNumber(File file, int serialNumber)
2540 throws IOException {
2541 try {
2542 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2543 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2544 } catch (ErrnoException e) {
2545 throw e.rethrowAsIOException();
2546 }
2547 }
2548
2549 /**
2550 * Return serial number stored in user directory inode.
2551 *
2552 * @return parsed serial number, or -1 if not set
2553 */
2554 private static int getSerialNumber(File file) throws IOException {
2555 try {
2556 final byte[] buf = new byte[256];
2557 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2558 final String serial = new String(buf, 0, len);
2559 try {
2560 return Integer.parseInt(serial);
2561 } catch (NumberFormatException e) {
2562 throw new IOException("Bad serial number: " + serial);
2563 }
2564 } catch (ErrnoException e) {
2565 if (e.errno == OsConstants.ENODATA) {
2566 return -1;
2567 } else {
2568 throw e.rethrowAsIOException();
2569 }
2570 }
2571 }
2572
Amith Yamasani920ace02012-09-20 22:15:37 -07002573 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002574 public void setSeedAccountData(int userId, String accountName, String accountType,
2575 PersistableBundle accountOptions, boolean persist) {
2576 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2577 synchronized (mPackagesLock) {
2578 final UserData userData;
2579 synchronized (mUsersLock) {
2580 userData = getUserDataLU(userId);
2581 if (userData == null) {
2582 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2583 return;
2584 }
2585 userData.seedAccountName = accountName;
2586 userData.seedAccountType = accountType;
2587 userData.seedAccountOptions = accountOptions;
2588 userData.persistSeedData = persist;
2589 }
2590 if (persist) {
2591 writeUserLP(userData);
2592 }
2593 }
2594 }
2595
2596 @Override
2597 public String getSeedAccountName() throws RemoteException {
2598 checkManageUsersPermission("Cannot get seed account information");
2599 synchronized (mUsersLock) {
2600 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2601 return userData.seedAccountName;
2602 }
2603 }
2604
2605 @Override
2606 public String getSeedAccountType() throws RemoteException {
2607 checkManageUsersPermission("Cannot get seed account information");
2608 synchronized (mUsersLock) {
2609 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2610 return userData.seedAccountType;
2611 }
2612 }
2613
2614 @Override
2615 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2616 checkManageUsersPermission("Cannot get seed account information");
2617 synchronized (mUsersLock) {
2618 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2619 return userData.seedAccountOptions;
2620 }
2621 }
2622
2623 @Override
2624 public void clearSeedAccountData() throws RemoteException {
2625 checkManageUsersPermission("Cannot clear seed account information");
2626 synchronized (mPackagesLock) {
2627 UserData userData;
2628 synchronized (mUsersLock) {
2629 userData = getUserDataLU(UserHandle.getCallingUserId());
2630 if (userData == null) return;
2631 userData.clearSeedAccountData();
2632 }
2633 writeUserLP(userData);
2634 }
2635 }
2636
2637 @Override
2638 public boolean someUserHasSeedAccount(String accountName, String accountType)
2639 throws RemoteException {
2640 checkManageUsersPermission("Cannot check seed account information");
2641 synchronized (mUsersLock) {
2642 final int userSize = mUsers.size();
2643 for (int i = 0; i < userSize; i++) {
2644 final UserData data = mUsers.valueAt(i);
2645 if (data.info.isInitialized()) continue;
2646 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2647 continue;
2648 }
2649 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2650 continue;
2651 }
2652 return true;
2653 }
2654 }
2655 return false;
2656 }
2657
2658 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002659 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2660 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2661 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2662 }
2663
2664 int onShellCommand(Shell shell, String cmd) {
2665 if (cmd == null) {
2666 return shell.handleDefaultCommands(cmd);
2667 }
2668
2669 final PrintWriter pw = shell.getOutPrintWriter();
2670 try {
2671 switch(cmd) {
2672 case "list":
2673 return runList(pw);
2674 }
2675 } catch (RemoteException e) {
2676 pw.println("Remote exception: " + e);
2677 }
2678 return -1;
2679 }
2680
2681 private int runList(PrintWriter pw) throws RemoteException {
2682 final IActivityManager am = ActivityManagerNative.getDefault();
2683 final List<UserInfo> users = getUsers(false);
2684 if (users == null) {
2685 pw.println("Error: couldn't get users");
2686 return 1;
2687 } else {
2688 pw.println("Users:");
2689 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002690 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002691 pw.println("\t" + users.get(i).toString() + running);
2692 }
2693 return 0;
2694 }
2695 }
2696
2697 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002698 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2699 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2700 != PackageManager.PERMISSION_GRANTED) {
2701 pw.println("Permission Denial: can't dump UserManager from from pid="
2702 + Binder.getCallingPid()
2703 + ", uid=" + Binder.getCallingUid()
2704 + " without permission "
2705 + android.Manifest.permission.DUMP);
2706 return;
2707 }
2708
2709 long now = System.currentTimeMillis();
2710 StringBuilder sb = new StringBuilder();
2711 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002712 synchronized (mUsersLock) {
2713 pw.println("Users:");
2714 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002715 UserData userData = mUsers.valueAt(i);
2716 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002717 continue;
2718 }
Amith Yamasani12747872015-12-07 14:19:49 -08002719 UserInfo userInfo = userData.info;
2720 final int userId = userInfo.id;
2721 pw.print(" "); pw.print(userInfo);
2722 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002723 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002724 pw.print(" <removing> ");
2725 }
Amith Yamasani12747872015-12-07 14:19:49 -08002726 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002727 pw.print(" <partial>");
2728 }
2729 pw.println();
2730 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002731 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002732 pw.println("<unknown>");
2733 } else {
2734 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002735 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002736 sb.append(" ago");
2737 pw.println(sb);
2738 }
2739 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002740 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002741 pw.println("<unknown>");
2742 } else {
2743 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002744 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002745 sb.append(" ago");
2746 pw.println(sb);
2747 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002748 pw.print(" Has profile owner: ");
2749 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002750 pw.println(" Restrictions:");
2751 synchronized (mRestrictionsLock) {
2752 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002753 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002754 pw.println(" Device policy local restrictions:");
2755 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002756 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002757 pw.println(" Effective restrictions:");
2758 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002759 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002760 }
Amith Yamasani12747872015-12-07 14:19:49 -08002761
2762 if (userData.account != null) {
2763 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002764 pw.println();
2765 }
Amith Yamasani12747872015-12-07 14:19:49 -08002766
2767 if (userData.seedAccountName != null) {
2768 pw.print(" Seed account name: " + userData.seedAccountName);
2769 pw.println();
2770 if (userData.seedAccountType != null) {
2771 pw.print(" account type: " + userData.seedAccountType);
2772 pw.println();
2773 }
2774 if (userData.seedAccountOptions != null) {
2775 pw.print(" account options exist");
2776 pw.println();
2777 }
2778 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002779 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002780 }
Amith Yamasani12747872015-12-07 14:19:49 -08002781 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002782 pw.println(" Device policy global restrictions:");
2783 synchronized (mRestrictionsLock) {
2784 UserRestrictionsUtils
2785 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2786 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002787 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002788 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002789 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002790 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002792 synchronized (mUsersLock) {
2793 pw.println();
2794 pw.println(" Device managed: " + mIsDeviceManaged);
2795 }
Amith Yamasani12747872015-12-07 14:19:49 -08002796 // Dump some capabilities
2797 pw.println();
2798 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2799 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002800 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2801 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002802 }
2803 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002804
2805 final class MainHandler extends Handler {
2806
2807 @Override
2808 public void handleMessage(Message msg) {
2809 switch (msg.what) {
2810 case WRITE_USER_MSG:
2811 removeMessages(WRITE_USER_MSG, msg.obj);
2812 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002813 int userId = ((UserData) msg.obj).info.id;
2814 UserData userData = getUserDataNoChecks(userId);
2815 if (userData != null) {
2816 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002817 }
2818 }
2819 }
2820 }
2821 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002822
2823 /**
2824 * @param userId
2825 * @return whether the user has been initialized yet
2826 */
2827 boolean isInitialized(int userId) {
2828 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2829 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002830
2831 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002832 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002833 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2834 @Nullable Bundle globalRestrictions) {
2835 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2836 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002837 }
2838
2839 @Override
2840 public Bundle getBaseUserRestrictions(int userId) {
2841 synchronized (mRestrictionsLock) {
2842 return mBaseUserRestrictions.get(userId);
2843 }
2844 }
2845
2846 @Override
2847 public void setBaseUserRestrictionsByDpmsForMigration(
2848 int userId, Bundle baseRestrictions) {
2849 synchronized (mRestrictionsLock) {
2850 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002851 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002852 }
2853
Amith Yamasani12747872015-12-07 14:19:49 -08002854 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002855 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002856 if (userData != null) {
2857 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002858 } else {
2859 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2860 }
2861 }
2862 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002863
2864 @Override
2865 public boolean getUserRestriction(int userId, String key) {
2866 return getUserRestrictions(userId).getBoolean(key);
2867 }
2868
2869 @Override
2870 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2871 synchronized (mUserRestrictionsListeners) {
2872 mUserRestrictionsListeners.add(listener);
2873 }
2874 }
2875
2876 @Override
2877 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2878 synchronized (mUserRestrictionsListeners) {
2879 mUserRestrictionsListeners.remove(listener);
2880 }
2881 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002882
2883 @Override
2884 public void setDeviceManaged(boolean isManaged) {
2885 synchronized (mUsersLock) {
2886 mIsDeviceManaged = isManaged;
2887 }
2888 }
2889
2890 @Override
2891 public void setUserManaged(int userId, boolean isManaged) {
2892 synchronized (mUsersLock) {
2893 mIsUserManaged.put(userId, isManaged);
2894 }
2895 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002896
2897 @Override
2898 public void setUserIcon(int userId, Bitmap bitmap) {
2899 long ident = Binder.clearCallingIdentity();
2900 try {
2901 synchronized (mPackagesLock) {
2902 UserData userData = getUserDataNoChecks(userId);
2903 if (userData == null || userData.info.partial) {
2904 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2905 return;
2906 }
2907 writeBitmapLP(userData.info, bitmap);
2908 writeUserLP(userData);
2909 }
2910 sendUserInfoChangedBroadcast(userId);
2911 } finally {
2912 Binder.restoreCallingIdentity(ident);
2913 }
2914 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002915 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002916
2917 private class Shell extends ShellCommand {
2918 @Override
2919 public int onCommand(String cmd) {
2920 return onShellCommand(this, cmd);
2921 }
2922
2923 @Override
2924 public void onHelp() {
2925 final PrintWriter pw = getOutPrintWriter();
2926 pw.println("User manager (user) commands:");
2927 pw.println(" help");
2928 pw.println(" Print this help text.");
2929 pw.println("");
2930 pw.println(" list");
2931 pw.println(" Prints all users on the system.");
2932 }
2933 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002934
2935 private static void debug(String message) {
2936 Log.d(LOG_TAG, message +
2937 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2938 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002939}