blob: 3248fe6178b04a247c86b245b846c58cc7308f1b [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010035import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080039import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070040import android.os.Environment;
41import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080042import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080044import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010045import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070046import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080047import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070048import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070049import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040051import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070053import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070054import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070055import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080056import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010057import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070058import android.os.storage.VolumeInfo;
59import android.system.ErrnoException;
60import android.system.Os;
61import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070062import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070063import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import android.util.Slog;
65import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070067import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import android.util.Xml;
69
Makoto Onuki068c54a2015-10-13 14:34:03 -070070import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070071import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040072import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080073import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080074import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070075import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070076import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000077import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070078import com.android.server.LocalServices;
Jeff Sharkey0e62384c2016-01-13 18:52:55 -070079import com.android.server.pm.Installer.StorageFlags;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080
81import org.xmlpull.v1.XmlPullParser;
82import org.xmlpull.v1.XmlPullParserException;
83import org.xmlpull.v1.XmlSerializer;
84
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.BufferedOutputStream;
86import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.io.FileOutputStream;
91import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070092import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010093import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094import java.util.ArrayList;
95import java.util.List;
96
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080098import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070099
Makoto Onuki068c54a2015-10-13 14:34:03 -0700100/**
101 * Service for {@link UserManager}.
102 *
103 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700104 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800105 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
107 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
108 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700109 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700110public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700111 private static final String LOG_TAG = "UserManagerService";
Amith Yamasani12747872015-12-07 14:19:49 -0800112 static final boolean DBG = true; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800113 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700114
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800116 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700118 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700120 private static final String ATTR_CREATION_TIME = "created";
121 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700122 private static final String ATTR_SERIAL_NO = "serialNumber";
123 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700124 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700125 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700126 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100127 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700128 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800129 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
130 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530131 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800134 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800136 private static final String TAG_ENTRY = "entry";
137 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800138 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800139 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700140 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700143 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
144 private static final String ATTR_TYPE_STRING = "s";
145 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700146 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700147 private static final String ATTR_TYPE_BUNDLE = "B";
148 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700149
Amith Yamasani0b285492011-04-14 17:35:23 -0700150 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700152 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100153 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800155 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700156 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157
Amith Yamasani634cf312012-10-04 17:34:21 -0700158 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700159 // We need to keep process uid within Integer.MAX_VALUE.
160 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700161
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700162 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163
Amith Yamasani920ace02012-09-20 22:15:37 -0700164 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
165
Nicolas Prevotb8186812015-08-06 15:00:03 +0100166 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700167 // without first making sure that the rest of the framework is prepared for it.
168 private static final int MAX_MANAGED_PROFILES = 1;
169
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800170 static final int WRITE_USER_MSG = 1;
171 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530172
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700173 private static final String XATTR_SERIAL = "user.serial";
174
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800175 // Tron counters
176 private static final String TRON_GUEST_CREATED = "users_guest_created";
177 private static final String TRON_USER_CREATED = "users_user_created";
178
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 private final Context mContext;
180 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700182 // Short-term lock for internal state, when interaction/sync with PM is not required
183 private final Object mUsersLock = new Object();
184 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800186 private final Handler mHandler;
187
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private final File mUsersDir;
189 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800192 * User-related information that is used for persisting to flash. Only UserInfo is
193 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800194 */
Amith Yamasani12747872015-12-07 14:19:49 -0800195 private static class UserData {
196 // Basic user information and properties
197 UserInfo info;
198 // Account name used when there is a strong association between a user and an account
199 String account;
200 // Account information for seeding into a newly created user. This could also be
201 // used for login validation for an existing user, for updating their credentials.
202 // In the latter case, data may not need to be persisted as it is only valid for the
203 // current login session.
204 String seedAccountName;
205 String seedAccountType;
206 PersistableBundle seedAccountOptions;
207 // Whether to perist the seed account information to be available after a boot
208 boolean persistSeedData;
209
210 void clearSeedAccountData() {
211 seedAccountName = null;
212 seedAccountType = null;
213 seedAccountOptions = null;
214 persistSeedData = false;
215 }
216 }
217
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800218 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800219 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800220
221 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700222 * User restrictions set via UserManager. This doesn't include restrictions set by
223 * device owner / profile owners.
224 *
225 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
226 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
227 * maybe shared between {@link #mBaseUserRestrictions} and
228 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
229 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700231 */
232 @GuardedBy("mRestrictionsLock")
233 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
234
235 /**
236 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
237 * with device / profile owner restrictions. We'll initialize it lazily; use
238 * {@link #getEffectiveUserRestrictions} to access it.
239 *
240 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
241 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
242 * maybe shared between {@link #mBaseUserRestrictions} and
243 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
244 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700245 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 */
247 @GuardedBy("mRestrictionsLock")
248 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
249
Makoto Onuki4f160732015-10-27 17:15:38 -0700250 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800251 * User restrictions that have already been applied in
252 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
253 * that have changed since the last
254 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700255 */
256 @GuardedBy("mRestrictionsLock")
257 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
258
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800259 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800260 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
261 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800262 */
263 @GuardedBy("mRestrictionsLock")
264 private Bundle mDevicePolicyGlobalUserRestrictions;
265
266 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800267 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
268 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800269 */
270 @GuardedBy("mRestrictionsLock")
271 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
272
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800273 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530274 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800275
276 /**
277 * Set of user IDs being actively removed. Removed IDs linger in this set
278 * for several seconds to work around a VFS caching issue.
279 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700280 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800281 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700282
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700284 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800285 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700286 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700287 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700288
Jason Monk62062992014-05-06 09:55:28 -0400289 private IAppOpsService mAppOpsService;
290
Makoto Onuki068c54a2015-10-13 14:34:03 -0700291 private final LocalService mLocalService;
292
Makoto Onukie7927da2015-11-25 10:05:17 -0800293 @GuardedBy("mUsersLock")
294 private boolean mIsDeviceManaged;
295
296 @GuardedBy("mUsersLock")
297 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
298
Makoto Onukid45a4a22015-11-02 17:17:38 -0800299 @GuardedBy("mUserRestrictionsListeners")
300 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
301 new ArrayList<>();
302
Clara Bayarria1771112015-12-18 16:29:18 +0000303 private final LockPatternUtils mLockPatternUtils;
304
Amith Yamasani258848d2012-08-10 17:06:33 -0700305 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700306
Dianne Hackborn4428e172012-08-24 17:43:05 -0700307 public static UserManagerService getInstance() {
308 synchronized (UserManagerService.class) {
309 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700311 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700312
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800313 @VisibleForTesting
314 UserManagerService(File dataDir) {
315 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700316 }
317
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 /**
319 * Called by package manager to create the service. This is closely
320 * associated with the package manager, and the given lock is the
321 * package manager's own lock.
322 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800323 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
324 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700325 }
326
Dianne Hackborn4428e172012-08-24 17:43:05 -0700327 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800328 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700329 mContext = context;
330 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700331 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800332 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 synchronized (mPackagesLock) {
334 mUsersDir = new File(dataDir, USER_INFO_DIR);
335 mUsersDir.mkdirs();
336 // Make zeroth user directory, for services to migrate their files to that location
337 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
338 userZeroDir.mkdirs();
339 FileUtils.setPermissions(mUsersDir.toString(),
340 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
341 -1, -1);
342 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
343 initDefaultGuestRestrictions();
344 readUserListLP();
345 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700346 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700347 mLocalService = new LocalService();
348 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000349 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700350 }
351
352 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100353 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800354 ArrayList<UserInfo> partials = new ArrayList<>();
355 synchronized (mUsersLock) {
356 final int userSize = mUsers.size();
357 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800358 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100359 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700363 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 final int partialsSize = partials.size();
365 for (int i = 0; i < partialsSize; i++) {
366 UserInfo ui = partials.get(i);
367 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
368 + " (name=" + ui.name + ")");
369 removeUserState(ui.id);
370 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800371
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700372 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800373
Jason Monk62062992014-05-06 09:55:28 -0400374 mAppOpsService = IAppOpsService.Stub.asInterface(
375 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800376
377 synchronized (mRestrictionsLock) {
378 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400379 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700380 }
381
382 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800383 public String getUserAccount(int userId) {
384 checkManageUserAndAcrossUsersFullPermission("get user account");
385 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800386 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800387 }
388 }
389
390 @Override
391 public void setUserAccount(int userId, String accountName) {
392 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800393 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800394 synchronized (mPackagesLock) {
395 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800396 final UserData userData = mUsers.get(userId);
397 if (userData == null) {
398 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
399 return;
400 }
401 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800402 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800403 userData.account = accountName;
404 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800405 }
406 }
407
408 if (userToUpdate != null) {
409 writeUserLP(userToUpdate);
410 }
411 }
412 }
413
414 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700415 public UserInfo getPrimaryUser() {
416 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700417 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700418 final int userSize = mUsers.size();
419 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800420 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800421 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700422 return ui;
423 }
424 }
425 }
426 return null;
427 }
428
429 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700430 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700431 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700432 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700433 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700434 final int userSize = mUsers.size();
435 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800436 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 if (ui.partial) {
438 continue;
439 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800440 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700442 }
Amith Yamasani13593602012-03-22 16:16:17 -0700443 }
444 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700445 }
Amith Yamasani13593602012-03-22 16:16:17 -0700446 }
447
Amith Yamasani258848d2012-08-10 17:06:33 -0700448 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100449 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800450 if (userId != UserHandle.getCallingUserId()) {
451 checkManageUsersPermission("getting profiles related to user " + userId);
452 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700453 final long ident = Binder.clearCallingIdentity();
454 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700455 synchronized (mUsersLock) {
456 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100457 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700458 } finally {
459 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000460 }
461 }
462
Amith Yamasanibe465322014-04-24 13:45:17 -0700463 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700464 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
465 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700466 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700467 if (user == null) {
468 // Probably a dying user
469 return users;
470 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700471 final int userSize = mUsers.size();
472 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800473 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700474 if (!isProfileOf(user, profile)) {
475 continue;
476 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100477 if (enabledOnly && !profile.isEnabled()) {
478 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700479 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700480 if (mRemovingUserIds.get(profile.id)) {
481 continue;
482 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700483 users.add(profile);
484 }
485 return users;
486 }
487
Jessica Hummelbe81c802014-04-22 15:49:22 +0100488 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700489 public int getCredentialOwnerProfile(int userHandle) {
490 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000491 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700492 synchronized (mUsersLock) {
493 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700494 if (profileParent != null) {
495 return profileParent.id;
496 }
497 }
498 }
499
500 return userHandle;
501 }
502
503 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700504 public boolean isSameProfileGroup(int userId, int otherUserId) {
505 if (userId == otherUserId) return true;
506 checkManageUsersPermission("check if in the same profile group");
507 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700508 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700509 }
510 }
511
Fyodor Kupolov82402752015-10-28 14:54:51 -0700512 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
513 synchronized (mUsersLock) {
514 UserInfo userInfo = getUserInfoLU(userId);
515 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
516 return false;
517 }
518 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
519 if (otherUserInfo == null
520 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
521 return false;
522 }
523 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700524 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700525 }
526
527 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100528 public UserInfo getProfileParent(int userHandle) {
529 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700530 synchronized (mUsersLock) {
531 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700532 }
533 }
534
Fyodor Kupolov82402752015-10-28 14:54:51 -0700535 private UserInfo getProfileParentLU(int userHandle) {
536 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700537 if (profile == null) {
538 return null;
539 }
540 int parentUserId = profile.profileGroupId;
541 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
542 return null;
543 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700544 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100545 }
546 }
547
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100549 return user.id == profile.id ||
550 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
551 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000552 }
553
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000554 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
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");
Jason Monk9a944532014-07-08 09:31:21 -0400733 long ident = Binder.clearCallingIdentity();
734 try {
735 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800736 UserData userData = getUserDataNoChecks(userId);
737 if (userData == null || userData.info.partial) {
Jason Monk9a944532014-07-08 09:31:21 -0400738 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
739 return;
740 }
Amith Yamasani12747872015-12-07 14:19:49 -0800741 writeBitmapLP(userData.info, bitmap);
742 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700743 }
Jason Monk9a944532014-07-08 09:31:21 -0400744 sendUserInfoChangedBroadcast(userId);
745 } finally {
746 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700747 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700748 }
749
750 private void sendUserInfoChangedBroadcast(int userId) {
751 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
752 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
753 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700754 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700755 }
756
Amith Yamasani258848d2012-08-10 17:06:33 -0700757 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100758 public ParcelFileDescriptor getUserIcon(int userId) {
759 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700760 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700762 if (info == null || info.partial) {
763 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
764 return null;
765 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700766 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100767 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
768 || callingGroupId != info.profileGroupId) {
769 checkManageUsersPermission("get the icon of a user who is not related");
770 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700771 if (info.iconPath == null) {
772 return null;
773 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100774 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700775 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100776
777 try {
778 return ParcelFileDescriptor.open(
779 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
780 } catch (FileNotFoundException e) {
781 Log.e(LOG_TAG, "Couldn't find icon file", e);
782 }
783 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700784 }
785
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700786 public void makeInitialized(int userId) {
787 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800788 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800789 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800790 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800791 userData = mUsers.get(userId);
792 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700793 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800794 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700795 }
Amith Yamasani12747872015-12-07 14:19:49 -0800796 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
797 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800798 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700799 }
800 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800801 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800802 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800803 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700804 }
805
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700806 /**
807 * If default guest restrictions haven't been initialized yet, add the basic
808 * restrictions.
809 */
810 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800811 synchronized (mGuestRestrictions) {
812 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800813 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800814 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
815 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
816 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700817 }
818 }
819
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800820 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530821 public Bundle getDefaultGuestRestrictions() {
822 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800823 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530824 return new Bundle(mGuestRestrictions);
825 }
826 }
827
828 @Override
829 public void setDefaultGuestRestrictions(Bundle restrictions) {
830 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800831 synchronized (mGuestRestrictions) {
832 mGuestRestrictions.clear();
833 mGuestRestrictions.putAll(restrictions);
834 }
835 synchronized (mPackagesLock) {
836 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530837 }
838 }
839
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800840 /**
841 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
842 */
843 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
844 @Nullable Bundle global) {
845 Preconditions.checkNotNull(local);
846 boolean globalChanged = false;
847 boolean localChanged;
848 synchronized (mRestrictionsLock) {
849 if (global != null) {
850 // Update global.
851 globalChanged = !UserRestrictionsUtils.areEqual(
852 mDevicePolicyGlobalUserRestrictions, global);
853 if (globalChanged) {
854 mDevicePolicyGlobalUserRestrictions = global;
855 }
856 }
857 {
858 // Update local.
859 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
860 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
861 if (localChanged) {
862 mDevicePolicyLocalUserRestrictions.put(userId, local);
863 }
864 }
865 }
866 if (DBG) {
867 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
868 + " global=" + global + (globalChanged ? " (changed)" : "")
869 + " local=" + local + (localChanged ? " (changed)" : "")
870 );
871 }
872 // Don't call them within the mRestrictionsLock.
873 synchronized (mPackagesLock) {
874 if (globalChanged) {
875 writeUserListLP();
876 }
877 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800878 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800879 }
880 }
881
882 synchronized (mRestrictionsLock) {
883 if (globalChanged) {
884 applyUserRestrictionsForAllUsersLR();
885 } else if (localChanged) {
886 applyUserRestrictionsLR(userId);
887 }
888 }
889 }
890
Makoto Onuki068c54a2015-10-13 14:34:03 -0700891 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700892 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 final Bundle baseRestrictions =
894 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
895 final Bundle global = mDevicePolicyGlobalUserRestrictions;
896 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700897
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800898 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
899 // Common case first.
900 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700901 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800902 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
903 UserRestrictionsUtils.merge(effective, global);
904 UserRestrictionsUtils.merge(effective, local);
905
Makoto Onuki068c54a2015-10-13 14:34:03 -0700906 return effective;
907 }
908
909 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700910 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700911 if (DBG) {
912 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
913 }
914 mCachedEffectiveUserRestrictions.remove(userId);
915 }
916
917 private Bundle getEffectiveUserRestrictions(int userId) {
918 synchronized (mRestrictionsLock) {
919 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
920 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700921 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700922 mCachedEffectiveUserRestrictions.put(userId, restrictions);
923 }
924 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700925 }
926 }
927
Makoto Onuki068c54a2015-10-13 14:34:03 -0700928 /** @return a specific user restriction that's in effect currently. */
929 @Override
930 public boolean hasUserRestriction(String restrictionKey, int userId) {
931 Bundle restrictions = getEffectiveUserRestrictions(userId);
932 return restrictions != null && restrictions.getBoolean(restrictionKey);
933 }
934
935 /**
936 * @return UserRestrictions that are in effect currently. This always returns a new
937 * {@link Bundle}.
938 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700939 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800940 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800941 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800942 }
943
944 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000945 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
946 checkManageUsersPermission("hasBaseUserRestriction");
947 synchronized (mRestrictionsLock) {
948 Bundle bundle = mBaseUserRestrictions.get(userId);
949 return (bundle != null && bundle.getBoolean(restrictionKey, false));
950 }
951 }
952
953 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700954 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700955 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700956 synchronized (mRestrictionsLock) {
957 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
958 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800959 final Bundle newRestrictions = UserRestrictionsUtils.clone(
960 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700961 newRestrictions.putBoolean(key, value);
962
Fyodor Kupolov82402752015-10-28 14:54:51 -0700963 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700964 }
965 }
966
Makoto Onuki068c54a2015-10-13 14:34:03 -0700967 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800968 * Optionally updating user restrictions, calculate the effective user restrictions and also
969 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700970 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800971 * @param newRestrictions User restrictions to set.
972 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700973 * @param userId target user ID.
974 */
975 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700976 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700977 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800978
979 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
980 mAppliedUserRestrictions.get(userId));
981
982 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700983 if (newRestrictions != null) {
984 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800985 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
986
987 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700988 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
989 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800990
991 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
992 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800993 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800994 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700995 }
996
Fyodor Kupolov82402752015-10-28 14:54:51 -0700997 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700998
Makoto Onuki759a7632015-10-28 16:43:10 -0700999 mCachedEffectiveUserRestrictions.put(userId, effective);
1000
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001001 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001002 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 debug("Applying user restrictions: userId=" + userId
1004 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001005 }
1006
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001007 if (mAppOpsService != null) { // We skip it until system-ready.
1008 final long token = Binder.clearCallingIdentity();
1009 try {
1010 mAppOpsService.setUserRestrictions(effective, userId);
1011 } catch (RemoteException e) {
1012 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1013 } finally {
1014 Binder.restoreCallingIdentity(token);
1015 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001016 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001017
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001018 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001019
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001021 }
1022
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001023 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001024 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001025 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1026 // actually, but we still need some kind of synchronization otherwise we might end up
1027 // calling listeners out-of-order, thus "LR".
1028
1029 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1030 return;
1031 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001032
1033 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1034 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1035
1036 mHandler.post(new Runnable() {
1037 @Override
1038 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001039 UserRestrictionsUtils.applyUserRestrictions(
1040 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001041
Makoto Onukid45a4a22015-11-02 17:17:38 -08001042 final UserRestrictionsListener[] listeners;
1043 synchronized (mUserRestrictionsListeners) {
1044 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1045 mUserRestrictionsListeners.toArray(listeners);
1046 }
1047 for (int i = 0; i < listeners.length; i++) {
1048 listeners[i].onUserRestrictionsChanged(userId,
1049 newRestrictionsFinal, prevRestrictionsFinal);
1050 }
1051 }
1052 });
1053 }
1054
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001055 // Package private for the inner class.
1056 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001057 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001058 }
1059
1060 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001061 // Package private for the inner class.
1062 void applyUserRestrictionsForAllUsersLR() {
1063 if (DBG) {
1064 debug("applyUserRestrictionsForAllUsersLR");
1065 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001066 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001067 mCachedEffectiveUserRestrictions.clear();
1068
Makoto Onuki068c54a2015-10-13 14:34:03 -07001069 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1070 // it on a handler.
1071 final Runnable r = new Runnable() {
1072 @Override
1073 public void run() {
1074 // Then get the list of running users.
1075 final int[] runningUsers;
1076 try {
1077 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1078 } catch (RemoteException e) {
1079 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1080 return;
1081 }
1082 // Then re-calculate the effective restrictions and apply, only for running users.
1083 // It's okay if a new user has started after the getRunningUserIds() call,
1084 // because we'll do the same thing (re-calculate the restrictions and apply)
1085 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001086 synchronized (mRestrictionsLock) {
1087 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001088 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001089 }
1090 }
1091 }
1092 };
1093 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001094 }
1095
Amith Yamasani258848d2012-08-10 17:06:33 -07001096 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001097 * Check if we've hit the limit of how many users can be created.
1098 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001099 private boolean isUserLimitReached() {
1100 int count;
1101 synchronized (mUsersLock) {
1102 count = getAliveUsersExcludingGuestsCountLU();
1103 }
1104 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001105 }
1106
1107 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001108 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001109 checkManageUsersPermission("check if more managed profiles can be added.");
1110 if (ActivityManager.isLowRamDeviceStatic()) {
1111 return false;
1112 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001113 if (!mContext.getPackageManager().hasSystemFeature(
1114 PackageManager.FEATURE_MANAGED_USERS)) {
1115 return false;
1116 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001117 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001118 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1119 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1120 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001121 return false;
1122 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001123 synchronized(mUsersLock) {
1124 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001125 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001126 return false;
1127 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001128 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1129 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001130 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001131 return usersCountAfterRemoving == 1
1132 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001133 }
1134 }
1135
Fyodor Kupolov82402752015-10-28 14:54:51 -07001136 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001137 int aliveUserCount = 0;
1138 final int totalUserCount = mUsers.size();
1139 // Skip over users being removed
1140 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001141 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001142 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001143 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001144 aliveUserCount++;
1145 }
1146 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001147 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001148 }
1149
1150 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001151 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001152 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1153 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1154 * permissions can make certain calls to the UserManager.
1155 *
1156 * @param message used as message if SecurityException is thrown
1157 * @throws SecurityException if the caller does not have enough privilege.
1158 */
1159 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1160 final int uid = Binder.getCallingUid();
1161 if (uid != Process.SYSTEM_UID && uid != 0
1162 && ActivityManager.checkComponentPermission(
1163 Manifest.permission.MANAGE_USERS,
1164 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1165 && ActivityManager.checkComponentPermission(
1166 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1167 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1168 throw new SecurityException(
1169 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1170 + message);
1171 }
1172 }
1173
1174 /**
1175 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001176 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001177 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001178 *
1179 * @param message used as message if SecurityException is thrown
1180 * @throws SecurityException if the caller is not system or root
1181 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001182 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001183 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001184 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001185 && ActivityManager.checkComponentPermission(
1186 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001187 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1188 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1189 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001190 }
1191
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001192 /**
1193 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1194 * UserManager.
1195 *
1196 * @param message used as message if SecurityException is thrown
1197 * @throws SecurityException if the caller is not system or root
1198 */
1199 private static void checkSystemOrRoot(String message) {
1200 final int uid = Binder.getCallingUid();
1201 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1202 throw new SecurityException("Only system may: " + message);
1203 }
1204 }
1205
Fyodor Kupolov82402752015-10-28 14:54:51 -07001206 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001207 try {
1208 File dir = new File(mUsersDir, Integer.toString(info.id));
1209 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001210 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001211 if (!dir.exists()) {
1212 dir.mkdir();
1213 FileUtils.setPermissions(
1214 dir.getPath(),
1215 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1216 -1, -1);
1217 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001218 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001219 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1220 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001221 info.iconPath = file.getAbsolutePath();
1222 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001223 try {
1224 os.close();
1225 } catch (IOException ioe) {
1226 // What the ... !
1227 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001228 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001229 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001230 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001231 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001232 }
1233
Amith Yamasani0b285492011-04-14 17:35:23 -07001234 /**
1235 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1236 * cache it elsewhere.
1237 * @return the array of user ids.
1238 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001239 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001240 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001241 return mUserIds;
1242 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001243 }
1244
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001245 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001246 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001247 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 return;
1249 }
1250 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001251 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001252 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001253 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001255 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256 int type;
1257 while ((type = parser.next()) != XmlPullParser.START_TAG
1258 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001259 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 }
1261
1262 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001263 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001264 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001265 return;
1266 }
1267
Amith Yamasani2a003292012-08-14 18:25:45 -07001268 mNextSerialNumber = -1;
1269 if (parser.getName().equals(TAG_USERS)) {
1270 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1271 if (lastSerialNumber != null) {
1272 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1273 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001274 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1275 if (versionNumber != null) {
1276 mUserVersion = Integer.parseInt(versionNumber);
1277 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001278 }
1279
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001280 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1281
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001282 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301283 if (type == XmlPullParser.START_TAG) {
1284 final String name = parser.getName();
1285 if (name.equals(TAG_USER)) {
1286 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001287
Amith Yamasani12747872015-12-07 14:19:49 -08001288 UserData userData = readUserLP(Integer.parseInt(id));
1289
1290 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001291 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001292 mUsers.put(userData.info.id, userData);
1293 if (mNextSerialNumber < 0
1294 || mNextSerialNumber <= userData.info.id) {
1295 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001296 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301297 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001298 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301299 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001300 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1301 && type != XmlPullParser.END_TAG) {
1302 if (type == XmlPullParser.START_TAG) {
1303 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001304 synchronized (mGuestRestrictions) {
1305 UserRestrictionsUtils
1306 .readRestrictions(parser, mGuestRestrictions);
1307 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1309 ) {
1310 UserRestrictionsUtils.readRestrictions(parser,
1311 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001312 }
1313 break;
1314 }
1315 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001316 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 }
1318 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001319 synchronized (mRestrictionsLock) {
1320 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1321 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001322 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001323 upgradeIfNecessaryLP();
1324 } catch (IOException | XmlPullParserException e) {
1325 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001326 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001327 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 }
1329 }
1330
Amith Yamasani6f34b412012-10-22 18:19:27 -07001331 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001332 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001333 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001334 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001335 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001336 int userVersion = mUserVersion;
1337 if (userVersion < 1) {
1338 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001339 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1340 if ("Primary".equals(userData.info.name)) {
1341 userData.info.name =
1342 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1343 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001344 }
1345 userVersion = 1;
1346 }
1347
Amith Yamasanibc9625052012-11-15 14:39:18 -08001348 if (userVersion < 2) {
1349 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001350 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1351 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1352 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1353 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001354 }
1355 userVersion = 2;
1356 }
1357
Amith Yamasani350962c2013-08-06 11:18:53 -07001358
Amith Yamasani5e486f52013-08-07 11:06:44 -07001359 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001360 userVersion = 4;
1361 }
1362
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001363 if (userVersion < 5) {
1364 initDefaultGuestRestrictions();
1365 userVersion = 5;
1366 }
1367
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001368 if (userVersion < 6) {
1369 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001370 synchronized (mUsersLock) {
1371 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001372 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001373 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001374 if (!splitSystemUser && userData.info.isRestricted()
1375 && (userData.info.restrictedProfileParentId
1376 == UserInfo.NO_PROFILE_GROUP_ID)) {
1377 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1378 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001379 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001380 }
1381 }
1382 userVersion = 6;
1383 }
1384
Amith Yamasani6f34b412012-10-22 18:19:27 -07001385 if (userVersion < USER_VERSION) {
1386 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1387 + USER_VERSION);
1388 } else {
1389 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001390
1391 if (originalVersion < mUserVersion) {
1392 writeUserListLP();
1393 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001394 }
1395 }
1396
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001397 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001398 int flags = UserInfo.FLAG_INITIALIZED;
1399 // In split system user mode, the admin and primary flags are assigned to the first human
1400 // user.
1401 if (!UserManager.isSplitSystemUser()) {
1402 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1403 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001404 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001405 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001406 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001407 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001408 UserData userData = new UserData();
1409 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001410 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001411 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001413 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001414 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001415
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001416 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 synchronized (mRestrictionsLock) {
1418 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1419 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001420
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001422 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001423
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001424 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001425 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001426 }
1427
Amith Yamasani12747872015-12-07 14:19:49 -08001428 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 if (DBG) {
1430 debug("scheduleWriteUser");
1431 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001432 // No need to wrap it within a lock -- worst case, we'll just post the same message
1433 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001434 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1435 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001436 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1437 }
1438 }
1439
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001440 /*
1441 * Writes the user file in this format:
1442 *
1443 * <user flags="20039023" id="0">
1444 * <name>Primary</name>
1445 * </user>
1446 */
Amith Yamasani12747872015-12-07 14:19:49 -08001447 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001449 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001451 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001452 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001453 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001454 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001455 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1456
1457 // XmlSerializer serializer = XmlUtils.serializerInstance();
1458 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001459 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001460 serializer.startDocument(null, true);
1461 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1462
Amith Yamasani12747872015-12-07 14:19:49 -08001463 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 serializer.startTag(null, TAG_USER);
1465 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001466 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001467 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001468 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1469 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1470 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001471 if (userInfo.iconPath != null) {
1472 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1473 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001474 if (userInfo.partial) {
1475 serializer.attribute(null, ATTR_PARTIAL, "true");
1476 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001477 if (userInfo.guestToRemove) {
1478 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1479 }
Kenny Guy2a764942014-04-02 13:29:20 +01001480 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1481 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1482 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001483 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001484 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1485 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1486 Integer.toString(userInfo.restrictedProfileParentId));
1487 }
Amith Yamasani12747872015-12-07 14:19:49 -08001488 // Write seed data
1489 if (userData.persistSeedData) {
1490 if (userData.seedAccountName != null) {
1491 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1492 }
1493 if (userData.seedAccountType != null) {
1494 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1495 }
1496 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001497 serializer.startTag(null, TAG_NAME);
1498 serializer.text(userInfo.name);
1499 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001500 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 UserRestrictionsUtils.writeRestrictions(serializer,
1502 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1503 UserRestrictionsUtils.writeRestrictions(serializer,
1504 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1505 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001506 }
Amith Yamasani12747872015-12-07 14:19:49 -08001507
1508 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001509 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001510 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001511 serializer.endTag(null, TAG_ACCOUNT);
1512 }
1513
Amith Yamasani12747872015-12-07 14:19:49 -08001514 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1515 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1516 userData.seedAccountOptions.saveToXml(serializer);
1517 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1518 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001519 serializer.endTag(null, TAG_USER);
1520
1521 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001522 userFile.finishWrite(fos);
1523 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001524 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001525 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001526 }
1527 }
1528
1529 /*
1530 * Writes the user list file in this format:
1531 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001532 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001533 * <user id="0"></user>
1534 * <user id="2"></user>
1535 * </users>
1536 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001537 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 if (DBG) {
1539 debug("writeUserList");
1540 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001541 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001542 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001543 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001544 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001545 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1546
1547 // XmlSerializer serializer = XmlUtils.serializerInstance();
1548 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001549 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001550 serializer.startDocument(null, true);
1551 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1552
1553 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001554 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001555 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001556
Adam Lesinskieddeb492014-09-08 17:50:03 -07001557 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001558 synchronized (mGuestRestrictions) {
1559 UserRestrictionsUtils
1560 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1561 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301562 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 synchronized (mRestrictionsLock) {
1564 UserRestrictionsUtils.writeRestrictions(serializer,
1565 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1566 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001567 int[] userIdsToWrite;
1568 synchronized (mUsersLock) {
1569 userIdsToWrite = new int[mUsers.size()];
1570 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001571 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001572 userIdsToWrite[i] = user.id;
1573 }
1574 }
1575 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001576 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001577 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001578 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001579 }
1580
1581 serializer.endTag(null, TAG_USERS);
1582
1583 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001584 userListFile.finishWrite(fos);
1585 } catch (Exception e) {
1586 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001587 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001588 }
1589 }
1590
Amith Yamasani12747872015-12-07 14:19:49 -08001591 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001592 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001593 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001594 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001595 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001596 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001597 long creationTime = 0L;
1598 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001599 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001600 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001601 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001602 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001603 boolean persistSeedData = false;
1604 String seedAccountName = null;
1605 String seedAccountType = null;
1606 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001607 Bundle baseRestrictions = new Bundle();
1608 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001609
1610 FileInputStream fis = null;
1611 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001612 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001613 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001614 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001615 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001616 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001617 int type;
1618 while ((type = parser.next()) != XmlPullParser.START_TAG
1619 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001620 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 }
1622
1623 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001624 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 return null;
1626 }
1627
1628 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001629 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1630 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001631 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001632 return null;
1633 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001634 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1635 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001636 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001637 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1638 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001639 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1640 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001641 restrictedProfileParentId = readIntAttribute(parser,
1642 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001643 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1644 if ("true".equals(valueString)) {
1645 partial = true;
1646 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001647 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1648 if ("true".equals(valueString)) {
1649 guestToRemove = true;
1650 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651
Amith Yamasani12747872015-12-07 14:19:49 -08001652 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1653 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1654 if (seedAccountName != null || seedAccountType != null) {
1655 persistSeedData = true;
1656 }
1657
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001658 int outerDepth = parser.getDepth();
1659 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1660 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1661 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1662 continue;
1663 }
1664 String tag = parser.getName();
1665 if (TAG_NAME.equals(tag)) {
1666 type = parser.next();
1667 if (type == XmlPullParser.TEXT) {
1668 name = parser.getText();
1669 }
1670 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1672 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1673 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001674 } else if (TAG_ACCOUNT.equals(tag)) {
1675 type = parser.next();
1676 if (type == XmlPullParser.TEXT) {
1677 account = parser.getText();
1678 }
Amith Yamasani12747872015-12-07 14:19:49 -08001679 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1680 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1681 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 }
1683 }
1684 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001685
Amith Yamasani12747872015-12-07 14:19:49 -08001686 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001687 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001688 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001689 userInfo.creationTime = creationTime;
1690 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001691 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001692 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001693 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001694 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001695
1696 // Create the UserData object that's internal to this class
1697 UserData userData = new UserData();
1698 userData.info = userInfo;
1699 userData.account = account;
1700 userData.seedAccountName = seedAccountName;
1701 userData.seedAccountType = seedAccountType;
1702 userData.persistSeedData = persistSeedData;
1703 userData.seedAccountOptions = seedAccountOptions;
1704
Makoto Onuki068c54a2015-10-13 14:34:03 -07001705 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 mBaseUserRestrictions.put(id, baseRestrictions);
1707 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 }
Amith Yamasani12747872015-12-07 14:19:49 -08001709 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001710 } catch (IOException ioe) {
1711 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001712 } finally {
1713 if (fis != null) {
1714 try {
1715 fis.close();
1716 } catch (IOException e) {
1717 }
1718 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001719 }
1720 return null;
1721 }
1722
Amith Yamasani920ace02012-09-20 22:15:37 -07001723 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1724 String valueString = parser.getAttributeValue(null, attr);
1725 if (valueString == null) return defaultValue;
1726 try {
1727 return Integer.parseInt(valueString);
1728 } catch (NumberFormatException nfe) {
1729 return defaultValue;
1730 }
1731 }
1732
1733 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1734 String valueString = parser.getAttributeValue(null, attr);
1735 if (valueString == null) return defaultValue;
1736 try {
1737 return Long.parseLong(valueString);
1738 } catch (NumberFormatException nfe) {
1739 return defaultValue;
1740 }
1741 }
1742
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001743 private boolean isPackageInstalled(String pkg, int userId) {
1744 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1745 PackageManager.GET_UNINSTALLED_PACKAGES,
1746 userId);
1747 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1748 return false;
1749 }
1750 return true;
1751 }
1752
Amith Yamasanib82add22013-07-09 11:24:44 -07001753 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001754 * Removes the app restrictions file for a specific package and user id, if it exists.
1755 */
1756 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1757 synchronized (mPackagesLock) {
1758 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001759 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001760 if (resFile.exists()) {
1761 resFile.delete();
1762 }
1763 }
1764 }
1765
Kenny Guya52dc3e2014-02-11 15:33:14 +00001766 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001767 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001768 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001769 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001770 }
1771
Amith Yamasani258848d2012-08-10 17:06:33 -07001772 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001773 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001774 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001775 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001776 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001777
Jessica Hummelbe81c802014-04-22 15:49:22 +01001778 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001779 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001780 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1781 return null;
1782 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001783 if (ActivityManager.isLowRamDeviceStatic()) {
1784 return null;
1785 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001786 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001787 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001788 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001789 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001790 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001791 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001792 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001793 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001794 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001795 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001796 if (parentId != UserHandle.USER_NULL) {
1797 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001798 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001799 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001800 if (parent == null) return null;
1801 }
1802 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1803 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1804 return null;
1805 }
1806 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1807 // If we're not adding a guest user or a managed profile and the limit has
1808 // been reached, cannot add a user.
1809 return null;
1810 }
1811 // If we're adding a guest and there already exists one, bail.
1812 if (isGuest && findCurrentGuestUser() != null) {
1813 return null;
1814 }
1815 // In legacy mode, restricted profile's parent can only be the owner user
1816 if (isRestricted && !UserManager.isSplitSystemUser()
1817 && (parentId != UserHandle.USER_SYSTEM)) {
1818 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1819 return null;
1820 }
1821 if (isRestricted && UserManager.isSplitSystemUser()) {
1822 if (parent == null) {
1823 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1824 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001825 return null;
1826 }
Amith Yamasani12747872015-12-07 14:19:49 -08001827 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001828 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1829 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001830 return null;
1831 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001832 }
1833 // In split system user mode, we assign the first human user the primary flag.
1834 // And if there is no device owner, we also assign the admin flag to primary user.
1835 if (UserManager.isSplitSystemUser()
1836 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1837 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001838 synchronized (mUsersLock) {
1839 if (!mIsDeviceManaged) {
1840 flags |= UserInfo.FLAG_ADMIN;
1841 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001842 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001843 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001844
Lenka Trochtova02fee152015-12-22 14:26:18 +01001845 // Add ephemeral flag to guests if required. Also inherit it from parent.
1846 boolean ephemeralGuests = Resources.getSystem()
1847 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
1848 if ((isGuest && ephemeralGuests)
1849 || (parent != null && parent.info.isEphemeral())) {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001850 flags |= UserInfo.FLAG_EPHEMERAL;
1851 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001852 userId = getNextAvailableId();
1853 userInfo = new UserInfo(userId, name, null, flags);
1854 userInfo.serialNumber = mNextSerialNumber++;
1855 long now = System.currentTimeMillis();
1856 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1857 userInfo.partial = true;
Amith Yamasani12747872015-12-07 14:19:49 -08001858 userData = new UserData();
1859 userData.info = userInfo;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001860 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1861 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001862 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001863 }
1864 writeUserListLP();
1865 if (parent != null) {
1866 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001867 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1868 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001869 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001870 }
Amith Yamasani12747872015-12-07 14:19:49 -08001871 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001872 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001873 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1874 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001876 }
Amith Yamasani12747872015-12-07 14:19:49 -08001877 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001878 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001879 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001880 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001881 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001882 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001883 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1884 final String volumeUuid = vol.getFsUuid();
1885 try {
1886 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001887 storage.prepareUserStorage(
1888 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001889 enforceSerialNumber(userDir, userInfo.serialNumber);
1890 } catch (IOException e) {
1891 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1892 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001893 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 mPm.createNewUser(userId);
1895 userInfo.partial = false;
1896 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001897 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 }
1899 updateUserIds();
1900 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001901 if (isGuest) {
1902 synchronized (mGuestRestrictions) {
1903 restrictions.putAll(mGuestRestrictions);
1904 }
1905 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001906 synchronized (mRestrictionsLock) {
1907 mBaseUserRestrictions.append(userId, restrictions);
1908 }
1909 mPm.newUserCreated(userId);
1910 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1911 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1912 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1913 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001914 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001915 } finally {
1916 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001917 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001918 return userInfo;
1919 }
1920
Amith Yamasani0b285492011-04-14 17:35:23 -07001921 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001922 * @hide
1923 */
Amith Yamasani12747872015-12-07 14:19:49 -08001924 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001925 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1926 checkManageUsersPermission("setupRestrictedProfile");
1927 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1928 if (user == null) {
1929 return null;
1930 }
1931 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1932 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1933 // the putIntForUser() will fail.
1934 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1935 android.provider.Settings.Secure.LOCATION_MODE,
1936 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1937 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1938 return user;
1939 }
1940
1941 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001942 * Find the current guest user. If the Guest user is partial,
1943 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001944 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001945 private UserInfo findCurrentGuestUser() {
1946 synchronized (mUsersLock) {
1947 final int size = mUsers.size();
1948 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001949 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1951 return user;
1952 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001953 }
1954 }
1955 return null;
1956 }
1957
1958 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001959 * Mark this guest user for deletion to allow us to create another guest
1960 * and switch to that user before actually removing this guest.
1961 * @param userHandle the userid of the current guest
1962 * @return whether the user could be marked for deletion
1963 */
Amith Yamasani12747872015-12-07 14:19:49 -08001964 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001965 public boolean markGuestForDeletion(int userHandle) {
1966 checkManageUsersPermission("Only the system can remove users");
1967 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1968 UserManager.DISALLOW_REMOVE_USER, false)) {
1969 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1970 return false;
1971 }
1972
1973 long ident = Binder.clearCallingIdentity();
1974 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001975 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001976 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001977 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001978 userData = mUsers.get(userHandle);
1979 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001980 return false;
1981 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001982 }
Amith Yamasani12747872015-12-07 14:19:49 -08001983 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001984 return false;
1985 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001986 // We set this to a guest user that is to be removed. This is a temporary state
1987 // where we are allowed to add new Guest users, even if this one is still not
1988 // removed. This user will still show up in getUserInfo() calls.
1989 // If we don't get around to removing this Guest user, it will be purged on next
1990 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001991 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001992 // Mark it as disabled, so that it isn't returned any more when
1993 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001994 userData.info.flags |= UserInfo.FLAG_DISABLED;
1995 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07001996 }
1997 } finally {
1998 Binder.restoreCallingIdentity(ident);
1999 }
2000 return true;
2001 }
2002
2003 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002004 * Removes a user and all data directories created for that user. This method should be called
2005 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002006 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002007 */
Amith Yamasani12747872015-12-07 14:19:49 -08002008 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002009 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002010 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002011 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2012 UserManager.DISALLOW_REMOVE_USER, false)) {
2013 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2014 return false;
2015 }
2016
Kenny Guyee58b4f2014-05-23 15:19:53 +01002017 long ident = Binder.clearCallingIdentity();
2018 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002019 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002020 int currentUser = ActivityManager.getCurrentUser();
2021 if (currentUser == userHandle) {
2022 Log.w(LOG_TAG, "Current user cannot be removed");
2023 return false;
2024 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002025 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002026 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002027 userData = mUsers.get(userHandle);
2028 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002029 return false;
2030 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002031
Fyodor Kupolov82402752015-10-28 14:54:51 -07002032 // We remember deleted user IDs to prevent them from being
2033 // reused during the current boot; they can still be reused
2034 // after a reboot.
2035 mRemovingUserIds.put(userHandle, true);
2036 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002037
Kenny Guyee58b4f2014-05-23 15:19:53 +01002038 try {
2039 mAppOpsService.removeUser(userHandle);
2040 } catch (RemoteException e) {
2041 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2042 }
2043 // Set this to a partially created user, so that the user will be purged
2044 // on next startup, in case the runtime stops now before stopping and
2045 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002046 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002047 // Mark it as disabled, so that it isn't returned any more when
2048 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002049 userData.info.flags |= UserInfo.FLAG_DISABLED;
2050 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002051 }
2052
Amith Yamasani12747872015-12-07 14:19:49 -08002053 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2054 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002055 // Send broadcast to notify system that the user removed was a
2056 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002057 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002058 }
2059
2060 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2061 int res;
2062 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002063 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2064 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002065 @Override
2066 public void userStopped(int userId) {
2067 finishRemoveUser(userId);
2068 }
2069 @Override
2070 public void userStopAborted(int userId) {
2071 }
2072 });
2073 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002074 return false;
2075 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002076 return res == ActivityManager.USER_OP_SUCCESS;
2077 } finally {
2078 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002079 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002080 }
2081
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002082 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002083 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002084 // Let other services shutdown any activity and clean up their state before completely
2085 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002086 long ident = Binder.clearCallingIdentity();
2087 try {
2088 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2089 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002090 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2091 android.Manifest.permission.MANAGE_USERS,
2092
2093 new BroadcastReceiver() {
2094 @Override
2095 public void onReceive(Context context, Intent intent) {
2096 if (DBG) {
2097 Slog.i(LOG_TAG,
2098 "USER_REMOVED broadcast sent, cleaning up user data "
2099 + userHandle);
2100 }
2101 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002102 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002103 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002104 // Clean up any ActivityManager state
2105 LocalServices.getService(ActivityManagerInternal.class)
2106 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002107 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002108 }
2109 }.start();
2110 }
2111 },
2112
2113 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002117 }
2118
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002119 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002120 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002121 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002122 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002123
2124 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002125 synchronized (mUsersLock) {
2126 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002127 mIsUserManaged.delete(userHandle);
2128 }
2129 synchronized (mRestrictionsLock) {
2130 mBaseUserRestrictions.remove(userHandle);
2131 mAppliedUserRestrictions.remove(userHandle);
2132 mCachedEffectiveUserRestrictions.remove(userHandle);
2133 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002134 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002135 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002136 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002137 userFile.delete();
2138 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002139 synchronized (mPackagesLock) {
2140 writeUserListLP();
2141 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002142 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002143 File userDir = Environment.getUserSystemDirectory(userHandle);
2144 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2145 if (userDir.renameTo(renamedUserDir)) {
2146 removeDirectoryRecursive(renamedUserDir);
2147 } else {
2148 removeDirectoryRecursive(userDir);
2149 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002150 }
2151
Amith Yamasani61f57372012-08-31 12:12:28 -07002152 private void removeDirectoryRecursive(File parent) {
2153 if (parent.isDirectory()) {
2154 String[] files = parent.list();
2155 for (String filename : files) {
2156 File child = new File(parent, filename);
2157 removeDirectoryRecursive(child);
2158 }
2159 }
2160 parent.delete();
2161 }
2162
Kenny Guyf8d3a232014-05-15 16:09:52 +01002163 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002164 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002165 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2166 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002167 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002168 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002169 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002170 }
2171
Amith Yamasani2a003292012-08-14 18:25:45 -07002172 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002173 public Bundle getApplicationRestrictions(String packageName) {
2174 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2175 }
2176
2177 @Override
2178 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002179 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002180 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002181 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002182 }
2183 synchronized (mPackagesLock) {
2184 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002185 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002186 }
2187 }
2188
2189 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002190 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002191 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002192 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002193 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002194 if (restrictions == null || restrictions.isEmpty()) {
2195 cleanAppRestrictionsForPackage(packageName, userId);
2196 } else {
2197 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002198 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002199 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002200 }
Robin Lee66e5d962014-04-09 16:44:21 +01002201
Kenny Guyd21b2182014-07-17 16:38:55 +01002202 if (isPackageInstalled(packageName, userId)) {
2203 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2204 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2205 changeIntent.setPackage(packageName);
2206 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2207 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2208 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002209 }
2210
2211 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002212 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002213 try {
2214 return mContext.getPackageManager().getApplicationInfo(packageName,
2215 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2216 } catch (NameNotFoundException nnfe) {
2217 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002218 } finally {
2219 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002220 }
2221 }
2222
Fyodor Kupolov82402752015-10-28 14:54:51 -07002223 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002224 AtomicFile restrictionsFile =
2225 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2226 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002227 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002228 }
2229
2230 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002231 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002232 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002233 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002234 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002235 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002236 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002237
2238 FileInputStream fis = null;
2239 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002240 fis = restrictionsFile.openRead();
2241 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002242 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002243 XmlUtils.nextElement(parser);
2244 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002245 Slog.e(LOG_TAG, "Unable to read restrictions file "
2246 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002247 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002248 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002249 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2250 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002251 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002252 } catch (IOException|XmlPullParserException e) {
2253 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002254 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002255 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002256 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002257 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 }
2259
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002260 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2261 XmlPullParser parser) throws XmlPullParserException, IOException {
2262 int type = parser.getEventType();
2263 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2264 String key = parser.getAttributeValue(null, ATTR_KEY);
2265 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2266 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2267 if (multiple != null) {
2268 values.clear();
2269 int count = Integer.parseInt(multiple);
2270 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2271 if (type == XmlPullParser.START_TAG
2272 && parser.getName().equals(TAG_VALUE)) {
2273 values.add(parser.nextText().trim());
2274 count--;
2275 }
2276 }
2277 String [] valueStrings = new String[values.size()];
2278 values.toArray(valueStrings);
2279 restrictions.putStringArray(key, valueStrings);
2280 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2281 restrictions.putBundle(key, readBundleEntry(parser, values));
2282 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2283 final int outerDepth = parser.getDepth();
2284 ArrayList<Bundle> bundleList = new ArrayList<>();
2285 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2286 Bundle childBundle = readBundleEntry(parser, values);
2287 bundleList.add(childBundle);
2288 }
2289 restrictions.putParcelableArray(key,
2290 bundleList.toArray(new Bundle[bundleList.size()]));
2291 } else {
2292 String value = parser.nextText().trim();
2293 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2294 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2295 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2296 restrictions.putInt(key, Integer.parseInt(value));
2297 } else {
2298 restrictions.putString(key, value);
2299 }
2300 }
2301 }
2302 }
2303
2304 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2305 throws IOException, XmlPullParserException {
2306 Bundle childBundle = new Bundle();
2307 final int outerDepth = parser.getDepth();
2308 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2309 readEntry(childBundle, values, parser);
2310 }
2311 return childBundle;
2312 }
2313
Fyodor Kupolov82402752015-10-28 14:54:51 -07002314 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002315 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002316 AtomicFile restrictionsFile = new AtomicFile(
2317 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002318 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002319 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002320 }
2321
2322 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002323 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002324 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002325 try {
2326 fos = restrictionsFile.startWrite();
2327 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2328
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002330 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002331 serializer.startDocument(null, true);
2332 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2333
2334 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002335 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002336 serializer.endTag(null, TAG_RESTRICTIONS);
2337
2338 serializer.endDocument();
2339 restrictionsFile.finishWrite(fos);
2340 } catch (Exception e) {
2341 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002342 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2343 }
2344 }
2345
2346 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2347 throws IOException {
2348 for (String key : restrictions.keySet()) {
2349 Object value = restrictions.get(key);
2350 serializer.startTag(null, TAG_ENTRY);
2351 serializer.attribute(null, ATTR_KEY, key);
2352
2353 if (value instanceof Boolean) {
2354 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2355 serializer.text(value.toString());
2356 } else if (value instanceof Integer) {
2357 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2358 serializer.text(value.toString());
2359 } else if (value == null || value instanceof String) {
2360 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2361 serializer.text(value != null ? (String) value : "");
2362 } else if (value instanceof Bundle) {
2363 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2364 writeBundle((Bundle) value, serializer);
2365 } else if (value instanceof Parcelable[]) {
2366 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2367 Parcelable[] array = (Parcelable[]) value;
2368 for (Parcelable parcelable : array) {
2369 if (!(parcelable instanceof Bundle)) {
2370 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2371 }
2372 serializer.startTag(null, TAG_ENTRY);
2373 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2374 writeBundle((Bundle) parcelable, serializer);
2375 serializer.endTag(null, TAG_ENTRY);
2376 }
2377 } else {
2378 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2379 String[] values = (String[]) value;
2380 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2381 for (String choice : values) {
2382 serializer.startTag(null, TAG_VALUE);
2383 serializer.text(choice != null ? choice : "");
2384 serializer.endTag(null, TAG_VALUE);
2385 }
2386 }
2387 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002388 }
2389 }
2390
2391 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002392 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002394 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002395 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002396 }
2397 }
2398
2399 @Override
2400 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002401 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002402 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002403 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002404 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002405 }
2406 // Not found
2407 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002408 }
2409 }
2410
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002411 @Override
2412 public long getUserCreationTime(int userHandle) {
2413 int callingUserId = UserHandle.getCallingUserId();
2414 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002415 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002416 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002417 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002418 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002419 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002420 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002422 }
2423 }
2424 }
2425 if (userInfo == null) {
2426 throw new SecurityException("userHandle can only be the calling user or a managed "
2427 + "profile associated with this user");
2428 }
2429 return userInfo.creationTime;
2430 }
2431
Amith Yamasani0b285492011-04-14 17:35:23 -07002432 /**
2433 * Caches the list of user ids in an array, adjusting the array size when necessary.
2434 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002435 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002436 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002437 synchronized (mUsersLock) {
2438 final int userSize = mUsers.size();
2439 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002440 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 num++;
2442 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002443 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002444 final int[] newUsers = new int[num];
2445 int n = 0;
2446 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002447 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 newUsers[n++] = mUsers.keyAt(i);
2449 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002450 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002451 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002452 }
2453 }
2454
2455 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002456 * Called right before a user is started. This gives us a chance to prepare
2457 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002458 */
2459 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002460 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2461
2462 if (userId != UserHandle.USER_SYSTEM) {
2463 synchronized (mRestrictionsLock) {
2464 applyUserRestrictionsLR(userId);
2465 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002466 }
2467 }
2468
2469 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002470 * Called right before a user is unlocked. This gives us a chance to prepare
2471 * app storage.
2472 */
2473 public void onBeforeUnlockUser(int userId) {
2474 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2475 }
2476
2477 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002478 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002479 * @param userId the user that was just foregrounded
2480 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002481 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002482 UserData userData = getUserDataNoChecks(userId);
2483 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002484 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2485 return;
2486 }
2487 long now = System.currentTimeMillis();
2488 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002489 userData.info.lastLoggedInTime = now;
2490 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002491 }
2492 }
2493
2494 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002495 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002496 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2497 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002498 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002499 private int getNextAvailableId() {
2500 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002501 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002502 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002503 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002504 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002505 }
2506 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002507 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002508 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002509 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002510 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002511
Amith Yamasanifc95e702013-09-26 13:20:17 -07002512 private String packageToRestrictionsFileName(String packageName) {
2513 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2514 }
2515
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002516 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002517 * Enforce that serial number stored in user directory inode matches the
2518 * given expected value. Gracefully sets the serial number if currently
2519 * undefined.
2520 *
2521 * @throws IOException when problem extracting serial number, or serial
2522 * number is mismatched.
2523 */
2524 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2525 final int foundSerial = getSerialNumber(file);
2526 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2527
2528 if (foundSerial == -1) {
2529 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2530 try {
2531 setSerialNumber(file, serialNumber);
2532 } catch (IOException e) {
2533 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2534 }
2535
2536 } else if (foundSerial != serialNumber) {
2537 throw new IOException("Found serial number " + foundSerial
2538 + " doesn't match expected " + serialNumber);
2539 }
2540 }
2541
2542 /**
2543 * Set serial number stored in user directory inode.
2544 *
2545 * @throws IOException if serial number was already set
2546 */
2547 private static void setSerialNumber(File file, int serialNumber)
2548 throws IOException {
2549 try {
2550 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2551 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2552 } catch (ErrnoException e) {
2553 throw e.rethrowAsIOException();
2554 }
2555 }
2556
2557 /**
2558 * Return serial number stored in user directory inode.
2559 *
2560 * @return parsed serial number, or -1 if not set
2561 */
2562 private static int getSerialNumber(File file) throws IOException {
2563 try {
2564 final byte[] buf = new byte[256];
2565 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2566 final String serial = new String(buf, 0, len);
2567 try {
2568 return Integer.parseInt(serial);
2569 } catch (NumberFormatException e) {
2570 throw new IOException("Bad serial number: " + serial);
2571 }
2572 } catch (ErrnoException e) {
2573 if (e.errno == OsConstants.ENODATA) {
2574 return -1;
2575 } else {
2576 throw e.rethrowAsIOException();
2577 }
2578 }
2579 }
2580
Amith Yamasani920ace02012-09-20 22:15:37 -07002581 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002582 public void setSeedAccountData(int userId, String accountName, String accountType,
2583 PersistableBundle accountOptions, boolean persist) {
2584 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2585 synchronized (mPackagesLock) {
2586 final UserData userData;
2587 synchronized (mUsersLock) {
2588 userData = getUserDataLU(userId);
2589 if (userData == null) {
2590 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2591 return;
2592 }
2593 userData.seedAccountName = accountName;
2594 userData.seedAccountType = accountType;
2595 userData.seedAccountOptions = accountOptions;
2596 userData.persistSeedData = persist;
2597 }
2598 if (persist) {
2599 writeUserLP(userData);
2600 }
2601 }
2602 }
2603
2604 @Override
2605 public String getSeedAccountName() throws RemoteException {
2606 checkManageUsersPermission("Cannot get seed account information");
2607 synchronized (mUsersLock) {
2608 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2609 return userData.seedAccountName;
2610 }
2611 }
2612
2613 @Override
2614 public String getSeedAccountType() throws RemoteException {
2615 checkManageUsersPermission("Cannot get seed account information");
2616 synchronized (mUsersLock) {
2617 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2618 return userData.seedAccountType;
2619 }
2620 }
2621
2622 @Override
2623 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2624 checkManageUsersPermission("Cannot get seed account information");
2625 synchronized (mUsersLock) {
2626 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2627 return userData.seedAccountOptions;
2628 }
2629 }
2630
2631 @Override
2632 public void clearSeedAccountData() throws RemoteException {
2633 checkManageUsersPermission("Cannot clear seed account information");
2634 synchronized (mPackagesLock) {
2635 UserData userData;
2636 synchronized (mUsersLock) {
2637 userData = getUserDataLU(UserHandle.getCallingUserId());
2638 if (userData == null) return;
2639 userData.clearSeedAccountData();
2640 }
2641 writeUserLP(userData);
2642 }
2643 }
2644
2645 @Override
2646 public boolean someUserHasSeedAccount(String accountName, String accountType)
2647 throws RemoteException {
2648 checkManageUsersPermission("Cannot check seed account information");
2649 synchronized (mUsersLock) {
2650 final int userSize = mUsers.size();
2651 for (int i = 0; i < userSize; i++) {
2652 final UserData data = mUsers.valueAt(i);
2653 if (data.info.isInitialized()) continue;
2654 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2655 continue;
2656 }
2657 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2658 continue;
2659 }
2660 return true;
2661 }
2662 }
2663 return false;
2664 }
2665
2666 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002667 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2668 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2669 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2670 }
2671
2672 int onShellCommand(Shell shell, String cmd) {
2673 if (cmd == null) {
2674 return shell.handleDefaultCommands(cmd);
2675 }
2676
2677 final PrintWriter pw = shell.getOutPrintWriter();
2678 try {
2679 switch(cmd) {
2680 case "list":
2681 return runList(pw);
2682 }
2683 } catch (RemoteException e) {
2684 pw.println("Remote exception: " + e);
2685 }
2686 return -1;
2687 }
2688
2689 private int runList(PrintWriter pw) throws RemoteException {
2690 final IActivityManager am = ActivityManagerNative.getDefault();
2691 final List<UserInfo> users = getUsers(false);
2692 if (users == null) {
2693 pw.println("Error: couldn't get users");
2694 return 1;
2695 } else {
2696 pw.println("Users:");
2697 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002698 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002699 pw.println("\t" + users.get(i).toString() + running);
2700 }
2701 return 0;
2702 }
2703 }
2704
2705 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002706 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2707 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2708 != PackageManager.PERMISSION_GRANTED) {
2709 pw.println("Permission Denial: can't dump UserManager from from pid="
2710 + Binder.getCallingPid()
2711 + ", uid=" + Binder.getCallingUid()
2712 + " without permission "
2713 + android.Manifest.permission.DUMP);
2714 return;
2715 }
2716
2717 long now = System.currentTimeMillis();
2718 StringBuilder sb = new StringBuilder();
2719 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002720 synchronized (mUsersLock) {
2721 pw.println("Users:");
2722 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002723 UserData userData = mUsers.valueAt(i);
2724 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002725 continue;
2726 }
Amith Yamasani12747872015-12-07 14:19:49 -08002727 UserInfo userInfo = userData.info;
2728 final int userId = userInfo.id;
2729 pw.print(" "); pw.print(userInfo);
2730 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002731 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002732 pw.print(" <removing> ");
2733 }
Amith Yamasani12747872015-12-07 14:19:49 -08002734 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002735 pw.print(" <partial>");
2736 }
2737 pw.println();
2738 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002739 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002740 pw.println("<unknown>");
2741 } else {
2742 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002743 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002744 sb.append(" ago");
2745 pw.println(sb);
2746 }
2747 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002748 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002749 pw.println("<unknown>");
2750 } else {
2751 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002752 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002753 sb.append(" ago");
2754 pw.println(sb);
2755 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002756 pw.print(" Has profile owner: ");
2757 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002758 pw.println(" Restrictions:");
2759 synchronized (mRestrictionsLock) {
2760 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002761 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002762 pw.println(" Device policy local restrictions:");
2763 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002764 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002765 pw.println(" Effective restrictions:");
2766 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002767 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002768 }
Amith Yamasani12747872015-12-07 14:19:49 -08002769
2770 if (userData.account != null) {
2771 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002772 pw.println();
2773 }
Amith Yamasani12747872015-12-07 14:19:49 -08002774
2775 if (userData.seedAccountName != null) {
2776 pw.print(" Seed account name: " + userData.seedAccountName);
2777 pw.println();
2778 if (userData.seedAccountType != null) {
2779 pw.print(" account type: " + userData.seedAccountType);
2780 pw.println();
2781 }
2782 if (userData.seedAccountOptions != null) {
2783 pw.print(" account options exist");
2784 pw.println();
2785 }
2786 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002787 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002788 }
Amith Yamasani12747872015-12-07 14:19:49 -08002789 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002790 pw.println(" Device policy global restrictions:");
2791 synchronized (mRestrictionsLock) {
2792 UserRestrictionsUtils
2793 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2794 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002795 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002796 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002797 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002798 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002799 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002800 synchronized (mUsersLock) {
2801 pw.println();
2802 pw.println(" Device managed: " + mIsDeviceManaged);
2803 }
Amith Yamasani12747872015-12-07 14:19:49 -08002804 // Dump some capabilities
2805 pw.println();
2806 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2807 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002808 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2809 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002810 }
2811 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002812
2813 final class MainHandler extends Handler {
2814
2815 @Override
2816 public void handleMessage(Message msg) {
2817 switch (msg.what) {
2818 case WRITE_USER_MSG:
2819 removeMessages(WRITE_USER_MSG, msg.obj);
2820 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002821 int userId = ((UserData) msg.obj).info.id;
2822 UserData userData = getUserDataNoChecks(userId);
2823 if (userData != null) {
2824 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002825 }
2826 }
2827 }
2828 }
2829 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002830
2831 /**
2832 * @param userId
2833 * @return whether the user has been initialized yet
2834 */
2835 boolean isInitialized(int userId) {
2836 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2837 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002838
2839 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002840 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002841 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2842 @Nullable Bundle globalRestrictions) {
2843 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2844 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002845 }
2846
2847 @Override
2848 public Bundle getBaseUserRestrictions(int userId) {
2849 synchronized (mRestrictionsLock) {
2850 return mBaseUserRestrictions.get(userId);
2851 }
2852 }
2853
2854 @Override
2855 public void setBaseUserRestrictionsByDpmsForMigration(
2856 int userId, Bundle baseRestrictions) {
2857 synchronized (mRestrictionsLock) {
2858 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002859 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002860 }
2861
Amith Yamasani12747872015-12-07 14:19:49 -08002862 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002863 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002864 if (userData != null) {
2865 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002866 } else {
2867 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2868 }
2869 }
2870 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002871
2872 @Override
2873 public boolean getUserRestriction(int userId, String key) {
2874 return getUserRestrictions(userId).getBoolean(key);
2875 }
2876
2877 @Override
2878 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2879 synchronized (mUserRestrictionsListeners) {
2880 mUserRestrictionsListeners.add(listener);
2881 }
2882 }
2883
2884 @Override
2885 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2886 synchronized (mUserRestrictionsListeners) {
2887 mUserRestrictionsListeners.remove(listener);
2888 }
2889 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002890
2891 @Override
2892 public void setDeviceManaged(boolean isManaged) {
2893 synchronized (mUsersLock) {
2894 mIsDeviceManaged = isManaged;
2895 }
2896 }
2897
2898 @Override
2899 public void setUserManaged(int userId, boolean isManaged) {
2900 synchronized (mUsersLock) {
2901 mIsUserManaged.put(userId, isManaged);
2902 }
2903 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002904 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002905
2906 private class Shell extends ShellCommand {
2907 @Override
2908 public int onCommand(String cmd) {
2909 return onShellCommand(this, cmd);
2910 }
2911
2912 @Override
2913 public void onHelp() {
2914 final PrintWriter pw = getOutPrintWriter();
2915 pw.println("User manager (user) commands:");
2916 pw.println(" help");
2917 pw.println(" Print this help text.");
2918 pw.println("");
2919 pw.println(" list");
2920 pw.println(" Prints all users on the system.");
2921 }
2922 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002923
2924 private static void debug(String message) {
2925 Log.d(LOG_TAG, message +
2926 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2927 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002928}